1 /*
2 * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "core/components/web/resource/web_delegate.h"
17
18 #include <algorithm>
19 #include <cctype>
20 #include <cfloat>
21 #include <iomanip>
22 #include <optional>
23 #include <sstream>
24
25 #include "adapter/ohos/entrance/ace_container.h"
26 #include "base/json/json_util.h"
27 #include "base/log/ace_trace.h"
28 #include "base/log/log.h"
29 #include "base/memory/referenced.h"
30 #include "base/ressched/ressched_report.h"
31 #include "base/utils/utils.h"
32 #include "core/common/container.h"
33 #include "core/components/container_modal/container_modal_constants.h"
34 #include "core/components/web/render_web.h"
35 #include "core/components/web/web_event.h"
36 #include "core/components/web/web_property.h"
37 #include "core/components_ng/pattern/web/web_pattern.h"
38 #include "core/pipeline_ng/pipeline_context.h"
39 #ifdef ENABLE_ROSEN_BACKEND
40 #include "core/components_ng/render/adapter/rosen_render_context.h"
41 #include "core/components_ng/render/adapter/rosen_render_surface.h"
42 #endif
43 #include "core/common/ace_application_info.h"
44 #include "core/event/ace_event_helper.h"
45 #include "core/event/ace_events.h"
46 #include "core/event/back_end_event_manager.h"
47 #include "frameworks/bridge/js_frontend/frontend_delegate_impl.h"
48 #ifdef OHOS_STANDARD_SYSTEM
49 #include "application_env.h"
50 #include "nweb_adapter_helper.h"
51 #include "nweb_handler.h"
52 #include "parameters.h"
53 #include "screen_manager/screen_types.h"
54 #include "transaction/rs_interfaces.h"
55 #include "web_configuration_observer.h"
56 #include "web_javascript_execute_callback.h"
57 #include "web_javascript_result_callback.h"
58
59 #include "core/components_ng/base/ui_node.h"
60 #include "frameworks/base/utils/system_properties.h"
61 #endif
62
63 namespace OHOS::Ace {
64
65 namespace {
66
67 constexpr char WEB_METHOD_ROUTER_BACK[] = "routerBack";
68 constexpr char WEB_METHOD_UPDATEURL[] = "updateUrl";
69 constexpr char WEB_METHOD_CHANGE_PAGE_URL[] = "changePageUrl";
70 constexpr char WEB_METHOD_PAGE_PATH_INVALID[] = "pagePathInvalid";
71 constexpr char WEB_EVENT_PAGESTART[] = "onPageStarted";
72 constexpr char WEB_EVENT_PAGEFINISH[] = "onPageFinished";
73 constexpr char WEB_EVENT_PAGEERROR[] = "onPageError";
74 constexpr char WEB_EVENT_ONMESSAGE[] = "onMessage";
75 constexpr char WEB_EVENT_ROUTERPUSH[] = "routerPush";
76
77 constexpr char WEB_CREATE[] = "web";
78 constexpr char NTC_PARAM_WEB[] = "web";
79 constexpr char NTC_PARAM_WIDTH[] = "width";
80 constexpr char NTC_PARAM_HEIGHT[] = "height";
81 constexpr char NTC_PARAM_LEFT[] = "left";
82 constexpr char NTC_PARAM_TOP[] = "top";
83 constexpr char NTC_ERROR[] = "create error";
84 constexpr char NTC_PARAM_SRC[] = "src";
85 constexpr char NTC_PARAM_ERROR_CODE[] = "errorCode";
86 constexpr char NTC_PARAM_URL[] = "url";
87 constexpr char NTC_PARAM_PAGE_URL[] = "pageUrl";
88 constexpr char NTC_PARAM_PAGE_INVALID[] = "pageInvalid";
89 constexpr char NTC_PARAM_DESCRIPTION[] = "description";
90 constexpr char WEB_ERROR_CODE_CREATEFAIL[] = "error-web-delegate-000001";
91 constexpr char WEB_ERROR_MSG_CREATEFAIL[] = "create web_delegate failed.";
92
93 const std::string RESOURCE_VIDEO_CAPTURE = "TYPE_VIDEO_CAPTURE";
94 const std::string RESOURCE_AUDIO_CAPTURE = "TYPE_AUDIO_CAPTURE";
95 const std::string RESOURCE_PROTECTED_MEDIA_ID = "TYPE_PROTECTED_MEDIA_ID";
96 const std::string RESOURCE_MIDI_SYSEX = "TYPE_MIDI_SYSEX";
97 const std::string RESOURCE_CLIPBOARD_READ_WRITE = "TYPE_CLIPBOARD_READ_WRITE";
98
99 constexpr uint32_t DESTRUCT_DELAY_MILLISECONDS = 1000;
100
101 #define VISIBLERATIO_LENGTH 4
102 #define VISIBLERATIO_FLOAT_TO_INT 100
103
IsDeviceTabletOr2in1()104 static bool IsDeviceTabletOr2in1()
105 {
106 return OHOS::system::GetDeviceType() == "tablet" || OHOS::system::GetDeviceType() == "2in1";
107 }
108
GetWebOptimizationValue()109 static bool GetWebOptimizationValue()
110 {
111 return OHOS::system::GetBoolParameter("web.optimization", true);
112 }
113 } // namespace
114
115 #define EGLCONFIG_VERSION 3
116
SetPortHandle(std::string & handle)117 void WebMessagePortOhos::SetPortHandle(std::string& handle)
118 {
119 handle_ = handle;
120 }
121
GetPortHandle()122 std::string WebMessagePortOhos::GetPortHandle()
123 {
124 return handle_;
125 }
126
Close()127 void WebMessagePortOhos::Close()
128 {
129 auto delegate = webDelegate_.Upgrade();
130 if (!delegate) {
131 return;
132 }
133 delegate->ClosePort(handle_);
134 }
135
PostMessage(std::string & data)136 void WebMessagePortOhos::PostMessage(std::string& data)
137 {
138 auto delegate = webDelegate_.Upgrade();
139 if (!delegate) {
140 return;
141 }
142 delegate->PostPortMessage(handle_, data);
143 }
144
SetWebMessageCallback(std::function<void (const std::string &)> && callback)145 void WebMessagePortOhos::SetWebMessageCallback(std::function<void(const std::string&)>&& callback)
146 {
147 auto delegate = webDelegate_.Upgrade();
148 if (!delegate) {
149 return;
150 }
151 delegate->SetPortMessageCallback(handle_, std::move(callback));
152 }
153
GetLineNumber()154 int ConsoleLogOhos::GetLineNumber()
155 {
156 if (message_) {
157 return message_->LineNumer();
158 }
159 return -1;
160 }
161
GetLog()162 std::string ConsoleLogOhos::GetLog()
163 {
164 if (message_) {
165 return message_->Log();
166 }
167 return "";
168 }
169
GetLogLevel()170 int ConsoleLogOhos::GetLogLevel()
171 {
172 if (message_) {
173 return message_->LogLevel();
174 }
175 return -1;
176 }
177
GetSourceId()178 std::string ConsoleLogOhos::GetSourceId()
179 {
180 if (message_) {
181 return message_->SourceId();
182 }
183 return "";
184 }
185
Confirm()186 void ResultOhos::Confirm()
187 {
188 if (result_) {
189 result_->Confirm();
190 }
191 }
192
Confirm(const std::string & message)193 void ResultOhos::Confirm(const std::string& message)
194 {
195 if (result_) {
196 result_->Confirm(message);
197 }
198 }
199
Cancel()200 void ResultOhos::Cancel()
201 {
202 if (result_) {
203 result_->Cancel();
204 }
205 }
206
ExitFullScreen()207 void FullScreenExitHandlerOhos::ExitFullScreen()
208 {
209 auto delegate = webDelegate_.Upgrade();
210 CHECK_NULL_VOID(delegate);
211 CHECK_NULL_VOID(handler_);
212 if (Container::IsCurrentUseNewPipeline()) {
213 // notify chromium to exit fullscreen mode.
214 handler_->ExitFullScreen();
215 // notify web component in arkui to exit fullscreen mode.
216 delegate->ExitFullScreen();
217 }
218 }
219
Confirm(std::string & userName,std::string & pwd)220 bool AuthResultOhos::Confirm(std::string& userName, std::string& pwd)
221 {
222 if (result_) {
223 return result_->Confirm(userName, pwd);
224 }
225 return false;
226 }
227
IsHttpAuthInfoSaved()228 bool AuthResultOhos::IsHttpAuthInfoSaved()
229 {
230 if (result_) {
231 return result_->IsHttpAuthInfoSaved();
232 }
233 return false;
234 }
235
Cancel()236 void AuthResultOhos::Cancel()
237 {
238 if (result_) {
239 result_->Cancel();
240 }
241 }
242
HandleConfirm()243 void SslErrorResultOhos::HandleConfirm()
244 {
245 if (result_) {
246 result_->HandleConfirm();
247 }
248 }
249
HandleCancel()250 void SslErrorResultOhos::HandleCancel()
251 {
252 if (result_) {
253 result_->HandleCancel();
254 }
255 }
256
HandleConfirm(const std::string & privateKeyFile,const std::string & certChainFile)257 void SslSelectCertResultOhos::HandleConfirm(const std::string& privateKeyFile, const std::string& certChainFile)
258 {
259 if (result_) {
260 result_->Confirm(privateKeyFile, certChainFile);
261 }
262 }
263
HandleCancel()264 void SslSelectCertResultOhos::HandleCancel()
265 {
266 if (result_) {
267 result_->Cancel();
268 }
269 }
270
HandleIgnore()271 void SslSelectCertResultOhos::HandleIgnore()
272 {
273 if (result_) {
274 result_->Ignore();
275 }
276 }
277
GetTitle()278 std::string FileSelectorParamOhos::GetTitle()
279 {
280 if (param_) {
281 return param_->Title();
282 }
283 return "";
284 }
285
GetMode()286 int FileSelectorParamOhos::GetMode()
287 {
288 if (param_) {
289 return param_->Mode();
290 }
291 return 0;
292 }
293
GetDefaultFileName()294 std::string FileSelectorParamOhos::GetDefaultFileName()
295 {
296 if (param_) {
297 return param_->DefaultFilename();
298 }
299 return "";
300 }
301
GetAcceptType()302 std::vector<std::string> FileSelectorParamOhos::GetAcceptType()
303 {
304 if (param_) {
305 return param_->AcceptType();
306 }
307 return std::vector<std::string>();
308 }
309
IsCapture()310 bool FileSelectorParamOhos::IsCapture()
311 {
312 if (param_) {
313 return param_->IsCapture();
314 }
315 return false;
316 }
317
HandleFileList(std::vector<std::string> & result)318 void FileSelectorResultOhos::HandleFileList(std::vector<std::string>& result)
319 {
320 if (callback_) {
321 callback_->OnReceiveValue(result);
322 }
323 }
324
Deny() const325 void WebPermissionRequestOhos::Deny() const
326 {
327 if (request_) {
328 request_->Refuse();
329 }
330 }
331
GetOrigin() const332 std::string WebPermissionRequestOhos::GetOrigin() const
333 {
334 if (request_) {
335 return request_->Origin();
336 }
337 return "";
338 }
339
GetResources() const340 std::vector<std::string> WebPermissionRequestOhos::GetResources() const
341 {
342 std::vector<std::string> resources;
343 if (request_) {
344 uint32_t resourcesId = static_cast<uint32_t>(request_->ResourceAcessId());
345 if (resourcesId & OHOS::NWeb::NWebAccessRequest::Resources::VIDEO_CAPTURE) {
346 resources.push_back(RESOURCE_VIDEO_CAPTURE);
347 }
348 if (resourcesId & OHOS::NWeb::NWebAccessRequest::Resources::AUDIO_CAPTURE) {
349 resources.push_back(RESOURCE_AUDIO_CAPTURE);
350 }
351 if (resourcesId & OHOS::NWeb::NWebAccessRequest::Resources::PROTECTED_MEDIA_ID) {
352 resources.push_back(RESOURCE_PROTECTED_MEDIA_ID);
353 }
354 if (resourcesId & OHOS::NWeb::NWebAccessRequest::Resources::MIDI_SYSEX) {
355 resources.push_back(RESOURCE_MIDI_SYSEX);
356 }
357 if (resourcesId & OHOS::NWeb::NWebAccessRequest::Resources::CLIPBOARD_READ_WRITE) {
358 resources.push_back(RESOURCE_CLIPBOARD_READ_WRITE);
359 }
360 }
361 return resources;
362 }
363
Grant(std::vector<std::string> & resources) const364 void WebPermissionRequestOhos::Grant(std::vector<std::string>& resources) const
365 {
366 if (request_) {
367 uint32_t resourcesId = 0;
368 for (auto res : resources) {
369 if (res == RESOURCE_VIDEO_CAPTURE) {
370 resourcesId |= OHOS::NWeb::NWebAccessRequest::Resources::VIDEO_CAPTURE;
371 } else if (res == RESOURCE_AUDIO_CAPTURE) {
372 resourcesId |= OHOS::NWeb::NWebAccessRequest::Resources::AUDIO_CAPTURE;
373 } else if (res == RESOURCE_PROTECTED_MEDIA_ID) {
374 resourcesId |= OHOS::NWeb::NWebAccessRequest::Resources::PROTECTED_MEDIA_ID;
375 } else if (res == RESOURCE_MIDI_SYSEX) {
376 resourcesId |= OHOS::NWeb::NWebAccessRequest::Resources::MIDI_SYSEX;
377 } else if (res == RESOURCE_CLIPBOARD_READ_WRITE) {
378 resourcesId |= OHOS::NWeb::NWebAccessRequest::Resources::CLIPBOARD_READ_WRITE;
379 }
380 }
381 request_->Agree(resourcesId);
382 }
383 }
384
Deny() const385 void WebScreenCaptureRequestOhos::Deny() const
386 {
387 if (request_) {
388 request_->Refuse();
389 }
390 }
391
GetOrigin() const392 std::string WebScreenCaptureRequestOhos::GetOrigin() const
393 {
394 if (request_) {
395 return request_->Origin();
396 }
397 return "";
398 }
399
SetCaptureMode(int32_t mode)400 void WebScreenCaptureRequestOhos::SetCaptureMode(int32_t mode)
401 {
402 config_.mode = mode;
403 }
404
SetSourceId(int32_t sourceId)405 void WebScreenCaptureRequestOhos::SetSourceId(int32_t sourceId)
406 {
407 config_.sourceId = sourceId;
408 }
409
Grant() const410 void WebScreenCaptureRequestOhos::Grant() const
411 {
412 if (request_) {
413 request_->Agree(config_);
414 }
415 }
416
GetXCoord() const417 int32_t ContextMenuParamOhos::GetXCoord() const
418 {
419 if (param_) {
420 return param_->GetXCoord();
421 }
422 return -1;
423 }
424
GetYCoord() const425 int32_t ContextMenuParamOhos::GetYCoord() const
426 {
427 if (param_) {
428 return param_->GetYCoord();
429 }
430 return -1;
431 }
432
GetLinkUrl() const433 std::string ContextMenuParamOhos::GetLinkUrl() const
434 {
435 if (param_) {
436 return param_->GetLinkUrl();
437 }
438 return "";
439 }
440
GetUnfilteredLinkUrl() const441 std::string ContextMenuParamOhos::GetUnfilteredLinkUrl() const
442 {
443 if (param_) {
444 return param_->GetUnfilteredLinkUrl();
445 }
446 return "";
447 }
448
GetSourceUrl() const449 std::string ContextMenuParamOhos::GetSourceUrl() const
450 {
451 if (param_) {
452 return param_->GetSourceUrl();
453 }
454 return "";
455 }
456
HasImageContents() const457 bool ContextMenuParamOhos::HasImageContents() const
458 {
459 if (param_) {
460 return param_->HasImageContents();
461 }
462 return false;
463 }
464
IsEditable() const465 bool ContextMenuParamOhos::IsEditable() const
466 {
467 if (param_) {
468 return param_->IsEditable();
469 }
470 return false;
471 }
472
GetEditStateFlags() const473 int ContextMenuParamOhos::GetEditStateFlags() const
474 {
475 if (param_) {
476 return param_->GetEditStateFlags();
477 }
478 return OHOS::NWeb::NWebContextMenuParams::ContextMenuEditStateFlags::CM_ES_NONE;
479 }
480
GetSourceType() const481 int ContextMenuParamOhos::GetSourceType() const
482 {
483 if (param_) {
484 return param_->GetSourceType();
485 }
486 return OHOS::NWeb::NWebContextMenuParams::ContextMenuSourceType::CM_ST_NONE;
487 }
488
GetMediaType() const489 int ContextMenuParamOhos::GetMediaType() const
490 {
491 if (param_) {
492 return param_->GetMediaType();
493 }
494 return OHOS::NWeb::NWebContextMenuParams::ContextMenuMediaType::CM_MT_NONE;
495 }
496
GetInputFieldType() const497 int ContextMenuParamOhos::GetInputFieldType() const
498 {
499 if (param_) {
500 return param_->GetInputFieldType();
501 }
502 return OHOS::NWeb::NWebContextMenuParams::ContextMenuInputFieldType::CM_IT_NONE;
503 }
504
GetSelectionText() const505 std::string ContextMenuParamOhos::GetSelectionText() const
506 {
507 if (param_) {
508 return param_->GetSelectionText();
509 }
510 return "";
511 }
512
Cancel() const513 void ContextMenuResultOhos::Cancel() const
514 {
515 if (callback_) {
516 callback_->Cancel();
517 }
518 }
519
CopyImage() const520 void ContextMenuResultOhos::CopyImage() const
521 {
522 if (callback_) {
523 callback_->Continue(CI_IMAGE_COPY, EF_NONE);
524 }
525 }
526
Copy() const527 void ContextMenuResultOhos::Copy() const
528 {
529 if (callback_) {
530 callback_->Continue(CI_COPY, EF_NONE);
531 }
532 }
533
Paste() const534 void ContextMenuResultOhos::Paste() const
535 {
536 if (callback_) {
537 callback_->Continue(CI_PASTE, EF_NONE);
538 }
539 }
540
Cut() const541 void ContextMenuResultOhos::Cut() const
542 {
543 if (callback_) {
544 callback_->Continue(CI_CUT, EF_NONE);
545 }
546 }
547
SelectAll() const548 void ContextMenuResultOhos::SelectAll() const
549 {
550 if (callback_) {
551 callback_->Continue(CI_SELECT_ALL, EF_NONE);
552 }
553 }
554
SetWebController(int32_t id)555 void WebWindowNewHandlerOhos::SetWebController(int32_t id)
556 {
557 if (handler_) {
558 handler_->SetNWebHandlerById(id);
559 }
560 }
561
IsFrist() const562 bool WebWindowNewHandlerOhos::IsFrist() const
563 {
564 if (handler_) {
565 return handler_->IsFrist();
566 }
567 return true;
568 }
569
GetId() const570 int32_t WebWindowNewHandlerOhos::GetId() const
571 {
572 if (handler_) {
573 return handler_->GetId();
574 }
575 return -1;
576 }
577
GetParentNWebId() const578 int32_t WebWindowNewHandlerOhos::GetParentNWebId() const
579 {
580 return parentNWebId_;
581 }
582
Resend()583 void DataResubmittedOhos::Resend()
584 {
585 if (handler_) {
586 handler_->Resend();
587 }
588 }
589
Cancel()590 void DataResubmittedOhos::Cancel()
591 {
592 if (handler_) {
593 handler_->Cancel();
594 }
595 }
596
GetData()597 const void* FaviconReceivedOhos::GetData()
598 {
599 return data_;
600 }
601
GetWidth()602 size_t FaviconReceivedOhos::GetWidth()
603 {
604 return width_;
605 }
606
GetHeight()607 size_t FaviconReceivedOhos::GetHeight()
608 {
609 return height_;
610 }
611
GetColorType()612 int FaviconReceivedOhos::GetColorType()
613 {
614 return static_cast<int>(colorType_);
615 }
616
GetAlphaType()617 int FaviconReceivedOhos::GetAlphaType()
618 {
619 return static_cast<int>(alphaType_);
620 }
621
~WebDelegateObserver()622 WebDelegateObserver::~WebDelegateObserver() {}
623
NotifyDestory()624 void WebDelegateObserver::NotifyDestory()
625 {
626 auto context = context_.Upgrade();
627 CHECK_NULL_VOID(context);
628 auto taskExecutor = context->GetTaskExecutor();
629 CHECK_NULL_VOID(taskExecutor);
630 taskExecutor->PostDelayedTask(
631 [weak = WeakClaim(this)]() {
632 auto observer = weak.Upgrade();
633 CHECK_NULL_VOID(observer);
634 if (observer->delegate_) {
635 observer->delegate_.Reset();
636 }
637 },
638 TaskExecutor::TaskType::UI, DESTRUCT_DELAY_MILLISECONDS);
639 }
640
~WebDelegate()641 WebDelegate::~WebDelegate()
642 {
643 ReleasePlatformResource();
644 if (IsDeviceTabletOr2in1() && GetWebOptimizationValue()) {
645 OHOS::Rosen::RSInterfaces::GetInstance().UnRegisterSurfaceOcclusionChangeCallback(surfaceNodeId_);
646 }
647 if (nweb_) {
648 nweb_->UnRegisterScreenLockFunction(GetRosenWindowId());
649 nweb_->OnDestroy();
650 }
651 UnregisterSurfacePositionChangedCallback();
652 }
653
ReleasePlatformResource()654 void WebDelegate::ReleasePlatformResource()
655 {
656 Stop();
657 Release();
658 }
659
Invoke(const std::string & origin,const bool & allow,const bool & retain)660 void WebGeolocationOhos::Invoke(const std::string& origin, const bool& allow, const bool& retain)
661 {
662 if (geolocationCallback_) {
663 geolocationCallback_->GeolocationCallbackInvoke(origin, allow, retain,
664 incognito_);
665 }
666 }
667
Stop()668 void WebDelegate::Stop()
669 {
670 auto context = context_.Upgrade();
671 if (!context) {
672 return;
673 }
674 auto platformTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::PLATFORM);
675 if (platformTaskExecutor.IsRunOnCurrentThread()) {
676 UnregisterEvent();
677 } else {
678 platformTaskExecutor.PostTask([weak = WeakClaim(this)] {
679 auto delegate = weak.Upgrade();
680 if (delegate) {
681 delegate->UnregisterEvent();
682 }
683 });
684 }
685 }
686
UnregisterEvent()687 void WebDelegate::UnregisterEvent()
688 {
689 // TODO: add support for ng.
690 auto context = DynamicCast<PipelineContext>(context_.Upgrade());
691 if (!context) {
692 return;
693 }
694 auto resRegister = context->GetPlatformResRegister();
695 if (resRegister == nullptr) {
696 return;
697 }
698 resRegister->UnregisterEvent(MakeEventHash(WEB_EVENT_PAGESTART));
699 resRegister->UnregisterEvent(MakeEventHash(WEB_EVENT_PAGEFINISH));
700 resRegister->UnregisterEvent(MakeEventHash(WEB_EVENT_PAGEERROR));
701 resRegister->UnregisterEvent(MakeEventHash(WEB_EVENT_ROUTERPUSH));
702 resRegister->UnregisterEvent(MakeEventHash(WEB_EVENT_ONMESSAGE));
703 }
704
SetRenderWeb(const WeakPtr<RenderWeb> & renderWeb)705 void WebDelegate::SetRenderWeb(const WeakPtr<RenderWeb>& renderWeb)
706 {
707 renderWeb_ = renderWeb;
708 }
709
CreatePlatformResource(const Size & size,const Offset & position,const WeakPtr<PipelineContext> & context)710 void WebDelegate::CreatePlatformResource(
711 const Size& size, const Offset& position, const WeakPtr<PipelineContext>& context)
712 {
713 ReleasePlatformResource();
714 context_ = context;
715 CreatePluginResource(size, position, context);
716
717 auto reloadCallback = [weak = WeakClaim(this)]() {
718 auto delegate = weak.Upgrade();
719 if (!delegate) {
720 return false;
721 }
722 delegate->Reload();
723 return true;
724 };
725 WebClient::GetInstance().RegisterReloadCallback(reloadCallback);
726
727 auto updateUrlCallback = [weak = WeakClaim(this)](const std::string& url) {
728 auto delegate = weak.Upgrade();
729 if (!delegate) {
730 return false;
731 }
732 delegate->UpdateUrl(url);
733 return true;
734 };
735 WebClient::GetInstance().RegisterUpdageUrlCallback(updateUrlCallback);
736 InitWebEvent();
737 }
738
LoadUrl(const std::string & url,const std::map<std::string,std::string> & httpHeaders)739 void WebDelegate::LoadUrl(const std::string& url, const std::map<std::string, std::string>& httpHeaders)
740 {
741 auto context = context_.Upgrade();
742 if (!context) {
743 return;
744 }
745 context->GetTaskExecutor()->PostTask(
746 [weak = WeakClaim(this), url, httpHeaders]() {
747 auto delegate = weak.Upgrade();
748 if (!delegate) {
749 return;
750 }
751 if (delegate->nweb_) {
752 delegate->nweb_->Load(
753 const_cast<std::string&>(url), const_cast<std::map<std::string, std::string>&>(httpHeaders));
754 }
755 },
756 TaskExecutor::TaskType::PLATFORM);
757 }
758
759 #ifdef OHOS_STANDARD_SYSTEM
Backward()760 void WebDelegate::Backward()
761 {
762 auto context = context_.Upgrade();
763 if (!context) {
764 return;
765 }
766 context->GetTaskExecutor()->PostTask(
767 [weak = WeakClaim(this)]() {
768 auto delegate = weak.Upgrade();
769 if (!delegate) {
770 return;
771 }
772 if (delegate->nweb_) {
773 delegate->nweb_->NavigateBack();
774 }
775 },
776 TaskExecutor::TaskType::PLATFORM);
777 }
778
Forward()779 void WebDelegate::Forward()
780 {
781 auto context = context_.Upgrade();
782 if (!context) {
783 return;
784 }
785 context->GetTaskExecutor()->PostTask(
786 [weak = WeakClaim(this)]() {
787 auto delegate = weak.Upgrade();
788 if (!delegate) {
789 return;
790 }
791 if (delegate->nweb_) {
792 delegate->nweb_->NavigateForward();
793 }
794 },
795 TaskExecutor::TaskType::PLATFORM);
796 }
797
ClearHistory()798 void WebDelegate::ClearHistory()
799 {
800 auto context = context_.Upgrade();
801 if (!context) {
802 return;
803 }
804 context->GetTaskExecutor()->PostTask(
805 [weak = WeakClaim(this)]() {
806 auto delegate = weak.Upgrade();
807 if (!delegate) {
808 return;
809 }
810 if (delegate->nweb_) {
811 delegate->nweb_->DeleteNavigateHistory();
812 }
813 },
814 TaskExecutor::TaskType::PLATFORM);
815 }
816
ClearSslCache()817 void WebDelegate::ClearSslCache()
818 {
819 auto context = context_.Upgrade();
820 if (!context) {
821 return;
822 }
823 context->GetTaskExecutor()->PostTask(
824 [weak = WeakClaim(this)]() {
825 auto delegate = weak.Upgrade();
826 if (!delegate) {
827 return;
828 }
829 if (delegate->nweb_) {
830 delegate->nweb_->ClearSslCache();
831 }
832 },
833 TaskExecutor::TaskType::PLATFORM);
834 }
835
ClearClientAuthenticationCache()836 void WebDelegate::ClearClientAuthenticationCache()
837 {
838 auto context = context_.Upgrade();
839 if (!context) {
840 return;
841 }
842 context->GetTaskExecutor()->PostTask(
843 [weak = WeakClaim(this)]() {
844 auto delegate = weak.Upgrade();
845 if (!delegate) {
846 return;
847 }
848 if (delegate->nweb_) {
849 delegate->nweb_->ClearClientAuthenticationCache();
850 }
851 },
852 TaskExecutor::TaskType::PLATFORM);
853 }
854
AccessStep(int32_t step)855 bool WebDelegate::AccessStep(int32_t step)
856 {
857 auto delegate = WeakClaim(this).Upgrade();
858 if (!delegate) {
859 return false;
860 }
861 if (delegate->nweb_) {
862 return delegate->nweb_->CanNavigateBackOrForward(step);
863 }
864 return false;
865 }
866
BackOrForward(int32_t step)867 void WebDelegate::BackOrForward(int32_t step)
868 {
869 auto context = context_.Upgrade();
870 if (!context) {
871 return;
872 }
873
874 context->GetTaskExecutor()->PostTask(
875 [weak = WeakClaim(this), step] {
876 auto delegate = weak.Upgrade();
877 if (!delegate) {
878 return;
879 }
880 if (delegate->nweb_) {
881 delegate->nweb_->NavigateBackOrForward(step);
882 }
883 },
884 TaskExecutor::TaskType::PLATFORM);
885 }
886
AccessBackward()887 bool WebDelegate::AccessBackward()
888 {
889 auto delegate = WeakClaim(this).Upgrade();
890 if (!delegate) {
891 return false;
892 }
893 if (delegate->nweb_) {
894 return delegate->nweb_->IsNavigatebackwardAllowed();
895 }
896 return false;
897 }
898
AccessForward()899 bool WebDelegate::AccessForward()
900 {
901 auto delegate = WeakClaim(this).Upgrade();
902 if (!delegate) {
903 return false;
904 }
905 if (delegate->nweb_) {
906 return delegate->nweb_->IsNavigateForwardAllowed();
907 }
908 return false;
909 }
910
911 #endif
912
ExecuteTypeScript(const std::string & jscode,const std::function<void (const std::string)> && callback)913 void WebDelegate::ExecuteTypeScript(const std::string& jscode, const std::function<void(const std::string)>&& callback)
914 {
915 auto context = context_.Upgrade();
916 if (!context) {
917 return;
918 }
919 context->GetTaskExecutor()->PostTask(
920 [weak = WeakClaim(this), jscode, callback]() {
921 auto delegate = weak.Upgrade();
922 if (!delegate) {
923 return;
924 }
925 if (delegate->nweb_) {
926 auto callbackImpl = std::make_shared<WebJavaScriptExecuteCallBack>(Container::CurrentId());
927 if (callbackImpl && callback) {
928 callbackImpl->SetCallBack([weak, func = std::move(callback)](std::string result) {
929 auto delegate = weak.Upgrade();
930 if (!delegate) {
931 return;
932 }
933 auto context = delegate->context_.Upgrade();
934 if (context) {
935 context->GetTaskExecutor()->PostTask(
936 [callback = std::move(func), result]() { callback(result); },
937 TaskExecutor::TaskType::JS);
938 }
939 });
940 }
941 delegate->nweb_->ExecuteJavaScript(jscode, callbackImpl, false);
942 }
943 },
944 TaskExecutor::TaskType::PLATFORM);
945 }
946
LoadDataWithBaseUrl(const std::string & baseUrl,const std::string & data,const std::string & mimeType,const std::string & encoding,const std::string & historyUrl)947 void WebDelegate::LoadDataWithBaseUrl(const std::string& baseUrl, const std::string& data, const std::string& mimeType,
948 const std::string& encoding, const std::string& historyUrl)
949 {
950 auto context = context_.Upgrade();
951 if (!context) {
952 return;
953 }
954 context->GetTaskExecutor()->PostTask(
955 [weak = WeakClaim(this), baseUrl, data, mimeType, encoding, historyUrl]() {
956 auto delegate = weak.Upgrade();
957 if (!delegate) {
958 return;
959 }
960 if (delegate->nweb_) {
961 if (baseUrl.empty() && historyUrl.empty()) {
962 delegate->nweb_->LoadWithData(data, mimeType, encoding);
963 } else {
964 delegate->nweb_->LoadWithDataAndBaseUrl(baseUrl, data, mimeType, encoding, historyUrl);
965 }
966 }
967 },
968 TaskExecutor::TaskType::PLATFORM);
969 }
970
LoadDataWithRichText()971 bool WebDelegate::LoadDataWithRichText()
972 {
973 auto context = context_.Upgrade();
974 if (!context) {
975 return false;
976 }
977 #ifdef NG_BUILD
978 auto webPattern = webPattern_.Upgrade();
979 CHECK_NULL_RETURN(webPattern, false);
980 auto webData = webPattern->GetWebData();
981 CHECK_NULL_RETURN(webData, false);
982 const std::string& data = webData.value();
983 if (data.empty()) {
984 return false;
985 }
986
987 context->GetTaskExecutor()->PostTask(
988 [weak = WeakClaim(this), data]() {
989 auto delegate = weak.Upgrade();
990 if (!delegate) {
991 return;
992 }
993 if (delegate->nweb_) {
994 delegate->nweb_->LoadWithDataAndBaseUrl("", data, "", "", "");
995 }
996 },
997 TaskExecutor::TaskType::PLATFORM);
998 return true;
999 #else
1000 if (Container::IsCurrentUseNewPipeline()) {
1001 auto webPattern = webPattern_.Upgrade();
1002 CHECK_NULL_RETURN(webPattern, false);
1003 auto webData = webPattern->GetWebData();
1004 CHECK_NULL_RETURN(webData, false);
1005 const std::string& data = webData.value();
1006 if (data.empty()) {
1007 return false;
1008 }
1009
1010 context->GetTaskExecutor()->PostTask(
1011 [weak = WeakClaim(this), data]() {
1012 auto delegate = weak.Upgrade();
1013 if (!delegate) {
1014 return;
1015 }
1016 if (delegate->nweb_) {
1017 delegate->nweb_->LoadWithDataAndBaseUrl("", data, "", "", "");
1018 }
1019 },
1020 TaskExecutor::TaskType::PLATFORM);
1021 return true;
1022 }
1023
1024 auto webCom = webComponent_.Upgrade();
1025 CHECK_NULL_RETURN(webCom, false);
1026 if (webCom->GetData().empty()) {
1027 return false;
1028 }
1029 const std::string& data = webCom->GetData();
1030 context->GetTaskExecutor()->PostTask(
1031 [weak = WeakClaim(this), data]() {
1032 auto delegate = weak.Upgrade();
1033 if (!delegate) {
1034 return;
1035 }
1036 if (delegate->nweb_) {
1037 delegate->nweb_->LoadWithDataAndBaseUrl("", data, "", "", "");
1038 }
1039 },
1040 TaskExecutor::TaskType::PLATFORM);
1041 return true;
1042 #endif
1043 }
1044
Refresh()1045 void WebDelegate::Refresh()
1046 {
1047 auto context = context_.Upgrade();
1048 if (!context) {
1049 return;
1050 }
1051 context->GetTaskExecutor()->PostTask(
1052 [weak = WeakClaim(this)]() {
1053 auto delegate = weak.Upgrade();
1054 if (!delegate) {
1055 return;
1056 }
1057 if (delegate->nweb_) {
1058 delegate->nweb_->Reload();
1059 }
1060 },
1061 TaskExecutor::TaskType::PLATFORM);
1062 }
1063
StopLoading()1064 void WebDelegate::StopLoading()
1065 {
1066 auto context = context_.Upgrade();
1067 if (!context) {
1068 return;
1069 }
1070 context->GetTaskExecutor()->PostTask(
1071 [weak = WeakClaim(this)]() {
1072 auto delegate = weak.Upgrade();
1073 if (!delegate) {
1074 return;
1075 }
1076 if (delegate->nweb_) {
1077 delegate->nweb_->Stop();
1078 }
1079 },
1080 TaskExecutor::TaskType::PLATFORM);
1081 }
1082
AddJavascriptInterface(const std::string & objectName,const std::vector<std::string> & methodList)1083 void WebDelegate::AddJavascriptInterface(const std::string& objectName, const std::vector<std::string>& methodList)
1084 {
1085 auto context = context_.Upgrade();
1086 if (!context) {
1087 return;
1088 }
1089 context->GetTaskExecutor()->PostTask(
1090 [weak = WeakClaim(this), objectName, methodList]() {
1091 auto delegate = weak.Upgrade();
1092 if (!delegate) {
1093 return;
1094 }
1095 if (delegate->nweb_) {
1096 // webcontroller not support object, so the object_id param assign
1097 // error code
1098 delegate->nweb_->RegisterArkJSfunctionExt(
1099 objectName, methodList, static_cast<int32_t>(JavaScriptObjIdErrorCode::WEBCONTROLLERERROR));
1100 }
1101 },
1102 TaskExecutor::TaskType::PLATFORM);
1103 }
RemoveJavascriptInterface(const std::string & objectName,const std::vector<std::string> & methodList)1104 void WebDelegate::RemoveJavascriptInterface(const std::string& objectName, const std::vector<std::string>& methodList)
1105 {
1106 auto context = context_.Upgrade();
1107 if (!context) {
1108 return;
1109 }
1110 context->GetTaskExecutor()->PostTask(
1111 [weak = WeakClaim(this), objectName, methodList]() {
1112 auto delegate = weak.Upgrade();
1113 if (!delegate) {
1114 return;
1115 }
1116 if (delegate->nweb_) {
1117 delegate->nweb_->UnregisterArkJSfunction(objectName, methodList);
1118 }
1119 },
1120 TaskExecutor::TaskType::PLATFORM);
1121 }
1122
SetWebViewJavaScriptResultCallBack(const WebController::JavaScriptCallBackImpl && javaScriptCallBackImpl)1123 void WebDelegate::SetWebViewJavaScriptResultCallBack(
1124 const WebController::JavaScriptCallBackImpl&& javaScriptCallBackImpl)
1125 {
1126 auto context = context_.Upgrade();
1127 if (!context) {
1128 return;
1129 }
1130
1131 context->GetTaskExecutor()->PostTask(
1132 [weak = WeakClaim(this), javaScriptCallBackImpl]() {
1133 auto delegate = weak.Upgrade();
1134 if (delegate == nullptr || delegate->nweb_ == nullptr) {
1135 return;
1136 }
1137 auto webJSResultCallBack = std::make_shared<WebJavaScriptResultCallBack>(Container::CurrentId());
1138 if (webJSResultCallBack) {
1139 webJSResultCallBack->SetJavaScriptCallBack(std::move(javaScriptCallBackImpl));
1140 delegate->nweb_->SetNWebJavaScriptResultCallBack(webJSResultCallBack);
1141 }
1142 },
1143 TaskExecutor::TaskType::PLATFORM);
1144 }
1145
CreateWebMessagePorts(std::vector<RefPtr<WebMessagePort>> & ports)1146 void WebDelegate::CreateWebMessagePorts(std::vector<RefPtr<WebMessagePort>>& ports)
1147 {
1148 if (nweb_) {
1149 std::vector<std::string> portStr;
1150 nweb_->CreateWebMessagePorts(portStr);
1151 RefPtr<WebMessagePort> port0 = AceType::MakeRefPtr<WebMessagePortOhos>(WeakClaim(this));
1152 RefPtr<WebMessagePort> port1 = AceType::MakeRefPtr<WebMessagePortOhos>(WeakClaim(this));
1153 port0->SetPortHandle(portStr[0]);
1154 port1->SetPortHandle(portStr[1]);
1155 ports.push_back(port0);
1156 ports.push_back(port1);
1157 }
1158 }
1159
PostWebMessage(std::string & message,std::vector<RefPtr<WebMessagePort>> & ports,std::string & uri)1160 void WebDelegate::PostWebMessage(std::string& message, std::vector<RefPtr<WebMessagePort>>& ports, std::string& uri)
1161 {
1162 if (nweb_) {
1163 std::vector<std::string> sendPorts;
1164 for (RefPtr<WebMessagePort> port : ports) {
1165 sendPorts.push_back(port->GetPortHandle());
1166 }
1167 nweb_->PostWebMessage(message, sendPorts, uri);
1168 }
1169 }
1170
ClosePort(std::string & port)1171 void WebDelegate::ClosePort(std::string& port)
1172 {
1173 if (nweb_) {
1174 nweb_->ClosePort(port);
1175 }
1176 }
1177
PostPortMessage(std::string & port,std::string & data)1178 void WebDelegate::PostPortMessage(std::string& port, std::string& data)
1179 {
1180 if (nweb_) {
1181 auto webMsg = std::make_shared<OHOS::NWeb::NWebMessage>(NWebValue::Type::NONE);
1182 webMsg->SetType(NWebValue::Type::STRING);
1183 webMsg->SetString(data);
1184 nweb_->PostPortMessage(port, webMsg);
1185 }
1186 }
1187
SetPortMessageCallback(std::string & port,std::function<void (const std::string &)> && callback)1188 void WebDelegate::SetPortMessageCallback(std::string& port, std::function<void(const std::string&)>&& callback)
1189 {
1190 if (nweb_) {
1191 auto callbackImpl = std::make_shared<WebMessageValueCallBackImpl>(Container::CurrentId());
1192 if (callbackImpl && callback) {
1193 callbackImpl->SetCallBack([weak = WeakClaim(this), func = std::move(callback)](std::string result) {
1194 auto delegate = weak.Upgrade();
1195 if (!delegate) {
1196 return;
1197 }
1198 auto context = delegate->context_.Upgrade();
1199 if (context) {
1200 context->GetTaskExecutor()->PostTask(
1201 [callback = std::move(func), result]() { callback(result); }, TaskExecutor::TaskType::JS);
1202 }
1203 });
1204 }
1205 nweb_->SetPortMessageCallback(port, callbackImpl);
1206 }
1207 }
1208
RequestFocus()1209 bool WebDelegate::RequestFocus()
1210 {
1211 auto context = context_.Upgrade();
1212 CHECK_NULL_RETURN(context, false);
1213 bool result = false;
1214 context->GetTaskExecutor()->PostSyncTask(
1215 [weak = WeakClaim(this), &result]() {
1216 auto delegate = weak.Upgrade();
1217 CHECK_NULL_VOID(delegate);
1218
1219 if (Container::IsCurrentUseNewPipeline()) {
1220 auto webPattern = delegate->webPattern_.Upgrade();
1221 CHECK_NULL_VOID(webPattern);
1222 auto eventHub = webPattern->GetWebEventHub();
1223 CHECK_NULL_VOID(eventHub);
1224 auto focusHub = eventHub->GetOrCreateFocusHub();
1225 CHECK_NULL_VOID(focusHub);
1226
1227 result = focusHub->RequestFocusImmediately(true);
1228 return;
1229 }
1230
1231 auto webCom = delegate->webComponent_.Upgrade();
1232 CHECK_NULL_VOID(webCom);
1233 result = webCom->RequestFocus();
1234 },
1235 TaskExecutor::TaskType::PLATFORM);
1236 return result;
1237 }
1238
SearchAllAsync(const std::string & searchStr)1239 void WebDelegate::SearchAllAsync(const std::string& searchStr)
1240 {
1241 auto context = context_.Upgrade();
1242 if (!context) {
1243 return;
1244 }
1245 context->GetTaskExecutor()->PostTask(
1246 [weak = WeakClaim(this), searchStr]() {
1247 auto delegate = weak.Upgrade();
1248 if (!delegate) {
1249 return;
1250 }
1251 if (delegate->nweb_) {
1252 delegate->nweb_->FindAllAsync(searchStr);
1253 }
1254 },
1255 TaskExecutor::TaskType::PLATFORM);
1256 }
1257
ClearMatches()1258 void WebDelegate::ClearMatches()
1259 {
1260 auto context = context_.Upgrade();
1261 if (!context) {
1262 return;
1263 }
1264 context->GetTaskExecutor()->PostTask(
1265 [weak = WeakClaim(this)]() {
1266 auto delegate = weak.Upgrade();
1267 if (!delegate) {
1268 return;
1269 }
1270 if (delegate->nweb_) {
1271 delegate->nweb_->ClearMatches();
1272 }
1273 },
1274 TaskExecutor::TaskType::PLATFORM);
1275 }
1276
SearchNext(bool forward)1277 void WebDelegate::SearchNext(bool forward)
1278 {
1279 auto context = context_.Upgrade();
1280 if (!context) {
1281 return;
1282 }
1283 context->GetTaskExecutor()->PostTask(
1284 [weak = WeakClaim(this), forward]() {
1285 auto delegate = weak.Upgrade();
1286 if (!delegate) {
1287 return;
1288 }
1289 if (delegate->nweb_) {
1290 delegate->nweb_->FindNext(forward);
1291 }
1292 },
1293 TaskExecutor::TaskType::PLATFORM);
1294 }
1295
ConverToWebHitTestType(int hitType)1296 int WebDelegate::ConverToWebHitTestType(int hitType)
1297 {
1298 WebHitTestType webHitType;
1299 switch (hitType) {
1300 case OHOS::NWeb::HitTestResult::UNKNOWN_TYPE:
1301 webHitType = WebHitTestType::UNKNOWN;
1302 break;
1303 case OHOS::NWeb::HitTestResult::ANCHOR_TYPE:
1304 webHitType = WebHitTestType::HTTP;
1305 break;
1306 case OHOS::NWeb::HitTestResult::PHONE_TYPE:
1307 webHitType = WebHitTestType::PHONE;
1308 break;
1309 case OHOS::NWeb::HitTestResult::GEO_TYPE:
1310 webHitType = WebHitTestType::MAP;
1311 break;
1312 case OHOS::NWeb::HitTestResult::EMAIL_TYPE:
1313 webHitType = WebHitTestType::EMAIL;
1314 break;
1315 case OHOS::NWeb::HitTestResult::IMAGE_TYPE:
1316 webHitType = WebHitTestType::IMG;
1317 break;
1318 case OHOS::NWeb::HitTestResult::IMAGE_ANCHOR_TYPE:
1319 webHitType = WebHitTestType::HTTP_IMG;
1320 break;
1321 case OHOS::NWeb::HitTestResult::SRC_ANCHOR_TYPE:
1322 webHitType = WebHitTestType::HTTP;
1323 break;
1324 case OHOS::NWeb::HitTestResult::SRC_IMAGE_ANCHOR_TYPE:
1325 webHitType = WebHitTestType::HTTP_IMG;
1326 break;
1327 case OHOS::NWeb::HitTestResult::EDIT_TEXT_TYPE:
1328 webHitType = WebHitTestType::EDIT;
1329 break;
1330 default:
1331 webHitType = WebHitTestType::UNKNOWN;
1332 break;
1333 }
1334 return static_cast<int>(webHitType);
1335 }
1336
GetHitTestResult()1337 int WebDelegate::GetHitTestResult()
1338 {
1339 if (nweb_) {
1340 return ConverToWebHitTestType(nweb_->GetHitTestResult().GetType());
1341 }
1342 return static_cast<int>(WebHitTestType::UNKNOWN);
1343 }
1344
GetHitTestValue(HitTestResult & result)1345 void WebDelegate::GetHitTestValue(HitTestResult& result)
1346 {
1347 if (nweb_) {
1348 OHOS::NWeb::HitTestResult nwebResult = nweb_->GetHitTestResult();
1349 result.SetExtraData(nwebResult.GetExtra());
1350 result.SetHitType(ConverToWebHitTestType(nwebResult.GetType()));
1351 }
1352 }
1353
GetPageHeight()1354 int WebDelegate::GetPageHeight()
1355 {
1356 if (nweb_) {
1357 return nweb_->ContentHeight();
1358 }
1359 return 0;
1360 }
1361
GetWebId()1362 int WebDelegate::GetWebId()
1363 {
1364 if (nweb_) {
1365 return nweb_->GetWebId();
1366 }
1367 return -1;
1368 }
1369
GetTitle()1370 std::string WebDelegate::GetTitle()
1371 {
1372 if (nweb_) {
1373 return nweb_->Title();
1374 }
1375 return "";
1376 }
1377
GetDefaultUserAgent()1378 std::string WebDelegate::GetDefaultUserAgent()
1379 {
1380 if (!nweb_) {
1381 return "";
1382 }
1383 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_->GetPreference();
1384 if (!setting) {
1385 return "";
1386 }
1387 return setting->DefaultUserAgent();
1388 }
1389
SaveCookieSync()1390 bool WebDelegate::SaveCookieSync()
1391 {
1392 if (cookieManager_) {
1393 return cookieManager_->Store();
1394 }
1395 return false;
1396 }
1397
SetCookie(const std::string & url,const std::string & value,bool incognitoMode)1398 bool WebDelegate::SetCookie(const std::string& url,
1399 const std::string& value,
1400 bool incognitoMode)
1401 {
1402 if (cookieManager_) {
1403 return cookieManager_->SetCookie(url, value, incognitoMode);
1404 }
1405 return false;
1406 }
1407
GetCookie(const std::string & url,bool incognitoMode) const1408 std::string WebDelegate::GetCookie(const std::string& url,
1409 bool incognitoMode) const
1410 {
1411 if (cookieManager_) {
1412 bool isValid = true;
1413 return cookieManager_->ReturnCookie(url, isValid, incognitoMode);
1414 }
1415 return "";
1416 }
1417
DeleteEntirelyCookie(bool incognitoMode)1418 void WebDelegate::DeleteEntirelyCookie(bool incognitoMode)
1419 {
1420 if (cookieManager_) {
1421 cookieManager_->DeleteCookieEntirely(nullptr, incognitoMode);
1422 }
1423 }
1424
CreatePluginResource(const Size & size,const Offset & position,const WeakPtr<PipelineContext> & context)1425 void WebDelegate::CreatePluginResource(
1426 const Size& size, const Offset& position, const WeakPtr<PipelineContext>& context)
1427 {
1428 state_ = State::CREATING;
1429 // TODO: add ng pattern.
1430 auto webCom = webComponent_.Upgrade();
1431 if (!webCom) {
1432 state_ = State::CREATEFAILED;
1433 OnError(NTC_ERROR, "fail to call WebDelegate::Create due to webComponent is null");
1434 return;
1435 }
1436
1437 auto pipelineContext = context.Upgrade();
1438 if (!pipelineContext) {
1439 state_ = State::CREATEFAILED;
1440 OnError(NTC_ERROR, "fail to call WebDelegate::Create due to context is null");
1441 return;
1442 }
1443 context_ = context;
1444 auto platformTaskExecutor =
1445 SingleTaskExecutor::Make(pipelineContext->GetTaskExecutor(), TaskExecutor::TaskType::PLATFORM);
1446 auto resRegister = pipelineContext->GetPlatformResRegister();
1447 auto weakRes = AceType::WeakClaim(AceType::RawPtr(resRegister));
1448 platformTaskExecutor.PostTask([weakWeb = AceType::WeakClaim(this), weakRes, size, position] {
1449 auto webDelegate = weakWeb.Upgrade();
1450 if (webDelegate == nullptr) {
1451 return;
1452 }
1453 // TODO: add ng pattern.
1454 auto webCom = webDelegate->webComponent_.Upgrade();
1455 if (!webCom) {
1456 webDelegate->OnError(NTC_ERROR, "fail to call WebDelegate::SetSrc PostTask");
1457 return;
1458 }
1459 auto resRegister = weakRes.Upgrade();
1460 if (!resRegister) {
1461 if (webDelegate->onError_) {
1462 webDelegate->onError_(WEB_ERROR_CODE_CREATEFAIL, WEB_ERROR_MSG_CREATEFAIL);
1463 }
1464 return;
1465 }
1466 auto context = webDelegate->context_.Upgrade();
1467 if (!context) {
1468 return;
1469 }
1470
1471 std::string pageUrl;
1472 int32_t pageId;
1473 OHOS::Ace::Framework::DelegateClient::GetInstance().GetWebPageUrl(pageUrl, pageId);
1474
1475 std::stringstream paramStream;
1476 paramStream << NTC_PARAM_WEB << WEB_PARAM_EQUALS << webDelegate->id_ << WEB_PARAM_AND << NTC_PARAM_WIDTH
1477 << WEB_PARAM_EQUALS << size.Width() * context->GetViewScale() << WEB_PARAM_AND << NTC_PARAM_HEIGHT
1478 << WEB_PARAM_EQUALS << size.Height() * context->GetViewScale() << WEB_PARAM_AND << NTC_PARAM_LEFT
1479 << WEB_PARAM_EQUALS << position.GetX() * context->GetViewScale() << WEB_PARAM_AND << NTC_PARAM_TOP
1480 << WEB_PARAM_EQUALS << position.GetY() * context->GetViewScale() << WEB_PARAM_AND << NTC_PARAM_SRC
1481 << WEB_PARAM_EQUALS << webCom->GetSrc() << WEB_PARAM_AND << NTC_PARAM_PAGE_URL << WEB_PARAM_EQUALS
1482 << pageUrl;
1483
1484 std::string param = paramStream.str();
1485 webDelegate->id_ = resRegister->CreateResource(WEB_CREATE, param);
1486 if (webDelegate->id_ == INVALID_ID) {
1487 if (webDelegate->onError_) {
1488 webDelegate->onError_(WEB_ERROR_CODE_CREATEFAIL, WEB_ERROR_MSG_CREATEFAIL);
1489 }
1490 return;
1491 }
1492 webDelegate->state_ = State::CREATED;
1493 webDelegate->hash_ = webDelegate->MakeResourceHash();
1494 webDelegate->RegisterWebEvent();
1495 webDelegate->BindRouterBackMethod();
1496 webDelegate->BindPopPageSuccessMethod();
1497 webDelegate->BindIsPagePathInvalidMethod();
1498 });
1499 }
1500
InitWebEvent()1501 void WebDelegate::InitWebEvent()
1502 {
1503 auto webCom = webComponent_.Upgrade();
1504 if (!webCom) {
1505 state_ = State::CREATEFAILED;
1506 OnError(NTC_ERROR, "fail to call WebDelegate::Create due to webComponent is null");
1507 return;
1508 }
1509 auto context = DynamicCast<PipelineContext>(context_.Upgrade());
1510 if (!context) {
1511 state_ = State::CREATEFAILED;
1512 OnError(NTC_ERROR, "fail to call WebDelegate::Create due to webComponent is null");
1513 return;
1514 }
1515 CHECK_NULL_VOID(context);
1516 if (!webCom->GetPageStartedEventId().IsEmpty()) {
1517 onPageStarted_ = AceAsyncEvent<void(const std::string&)>::Create(webCom->GetPageStartedEventId(), context);
1518 }
1519 if (!webCom->GetPageFinishedEventId().IsEmpty()) {
1520 onPageFinished_ = AceAsyncEvent<void(const std::string&)>::Create(webCom->GetPageFinishedEventId(), context);
1521 }
1522 if (!webCom->GetPageErrorEventId().IsEmpty()) {
1523 onPageError_ = AceAsyncEvent<void(const std::string&)>::Create(webCom->GetPageErrorEventId(), context);
1524 }
1525 if (!webCom->GetMessageEventId().IsEmpty()) {
1526 onMessage_ = AceAsyncEvent<void(const std::string&)>::Create(webCom->GetMessageEventId(), context);
1527 }
1528 }
1529
1530 #ifdef OHOS_STANDARD_SYSTEM
ShowWebView()1531 void WebDelegate::ShowWebView()
1532 {
1533 if (window_) {
1534 window_->Show();
1535 }
1536
1537 OnActive();
1538 OnWebviewShow();
1539 }
1540
HideWebView()1541 void WebDelegate::HideWebView()
1542 {
1543 if (window_) {
1544 window_->Hide();
1545 }
1546
1547 OnInactive();
1548 OnWebviewHide();
1549 }
1550
InitOHOSWeb(const RefPtr<PipelineBase> & context,const RefPtr<NG::RenderSurface> & surface)1551 void WebDelegate::InitOHOSWeb(const RefPtr<PipelineBase>& context, const RefPtr<NG::RenderSurface>& surface)
1552 {
1553 #ifdef ENABLE_ROSEN_BACKEND
1554 CHECK_NULL_VOID(context);
1555 auto rosenRenderSurface = DynamicCast<NG::RosenRenderSurface>(surface);
1556 if (!rosenRenderSurface) {
1557 if (PrepareInitOHOSWeb(context)) {
1558 if (!isCreateWebView_) {
1559 #ifndef ENABLE_ROSEN_BACKEND
1560 InitWebViewWithWindow();
1561 isCreateWebView_ = true;
1562 #endif
1563 }
1564 }
1565 return;
1566 }
1567 SetSurface(rosenRenderSurface->GetSurface());
1568 InitOHOSWeb(context);
1569 #endif
1570 }
1571
PrepareInitOHOSWeb(const WeakPtr<PipelineBase> & context)1572 bool WebDelegate::PrepareInitOHOSWeb(const WeakPtr<PipelineBase>& context)
1573 {
1574 ACE_SCOPED_TRACE("PrepareInitOHOSWeb");
1575
1576 state_ = State::CREATING;
1577 // obtain hap data path
1578 auto container = Container::Current();
1579 if (container == nullptr) {
1580 return false;
1581 }
1582 const std::string& bundlePath = container->GetBundlePath();
1583 const std::string& filesDataPath = container->GetFilesDataPath();
1584 std::string baseDir = "base";
1585 std::size_t baseIndex = filesDataPath.find(baseDir);
1586 if (baseIndex == std::string::npos) {
1587 return false;
1588 }
1589 std::string dataPath = filesDataPath.substr(0, baseIndex + baseDir.length());
1590 bundlePath_ = bundlePath;
1591 bundleDataPath_ = dataPath;
1592 hapPath_ = container->GetWebHapPath();
1593 // get app temp dir
1594 tempDir_ = container->GetTempDir();
1595 // load webview so
1596 OHOS::NWeb::NWebHelper::Instance().SetBundlePath(bundlePath_);
1597 if (!OHOS::NWeb::NWebHelper::Instance().Init()) {
1598 return false;
1599 }
1600 auto webCom = webComponent_.Upgrade();
1601 auto webPattern = webPattern_.Upgrade();
1602 auto eventHub = webPattern ? webPattern->GetWebEventHub() : nullptr;
1603 auto useNewPipe = Container::IsCurrentUseNewPipeline();
1604 if (useNewPipe && !webPattern && !eventHub) {
1605 return false;
1606 }
1607 if (!useNewPipe && !webCom) {
1608 return false;
1609 }
1610 incognitoMode_ =
1611 useNewPipe ? webPattern->GetIncognitoMode() : webCom->GetIncognitoMode();
1612 context_ = context;
1613 RegisterSurfacePositionChangedCallback();
1614 auto pipelineContext = context.Upgrade();
1615 if (!pipelineContext) {
1616 return false;
1617 }
1618 state_ = State::CREATED;
1619
1620 SetWebCallBack();
1621 if (!pipelineContext->GetIsDeclarative()) {
1622 RegisterOHOSWebEventAndMethord();
1623 } else {
1624 auto oldContext = DynamicCast<PipelineContext>(pipelineContext);
1625
1626 onPageFinishedV2_ = useNewPipe ? eventHub->GetOnPageFinishedEvent()
1627 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1628 webCom->GetPageFinishedEventId(), oldContext);
1629 onPageStartedV2_ = useNewPipe ? eventHub->GetOnPageStartedEvent()
1630 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1631 webCom->GetPageStartedEventId(), oldContext);
1632 onTitleReceiveV2_ = useNewPipe ? eventHub->GetOnTitleReceiveEvent()
1633 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1634 webCom->GetTitleReceiveEventId(), oldContext);
1635 onFullScreenExitV2_ = useNewPipe ? eventHub->GetOnFullScreenExitEvent()
1636 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1637 webCom->GetOnFullScreenExitEventId(), oldContext);
1638 onGeolocationHideV2_ = useNewPipe ? eventHub->GetOnGeolocationHideEvent()
1639 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1640 webCom->GetGeolocationHideEventId(), oldContext);
1641 onGeolocationShowV2_ = useNewPipe ? eventHub->GetOnGeolocationShowEvent()
1642 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1643 webCom->GetGeolocationShowEventId(), oldContext);
1644 onErrorReceiveV2_ = useNewPipe ? eventHub->GetOnErrorReceiveEvent()
1645 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1646 webCom->GetPageErrorEventId(), oldContext);
1647 onHttpErrorReceiveV2_ = useNewPipe ? eventHub->GetOnHttpErrorReceiveEvent()
1648 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1649 webCom->GetHttpErrorEventId(), oldContext);
1650 onRequestFocusV2_ = useNewPipe ? eventHub->GetOnRequestFocusEvent()
1651 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1652 webCom->GetRequestFocusEventId(), oldContext);
1653 onDownloadStartV2_ = useNewPipe ? eventHub->GetOnDownloadStartEvent()
1654 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1655 webCom->GetDownloadStartEventId(), oldContext);
1656 onRenderExitedV2_ = useNewPipe ? eventHub->GetOnRenderExitedEvent()
1657 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1658 webCom->GetRenderExitedId(), oldContext);
1659 onRefreshAccessedHistoryV2_ = useNewPipe ? eventHub->GetOnRefreshAccessedHistoryEvent()
1660 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1661 webCom->GetRefreshAccessedHistoryId(), oldContext);
1662 onResourceLoadV2_ = useNewPipe ? eventHub->GetOnResourceLoadEvent()
1663 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1664 webCom->GetResourceLoadId(), oldContext);
1665 onScaleChangeV2_ = useNewPipe ? eventHub->GetOnScaleChangeEvent()
1666 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1667 webCom->GetScaleChangeId(), oldContext);
1668 onPermissionRequestV2_ = useNewPipe ? eventHub->GetOnPermissionRequestEvent()
1669 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1670 webCom->GetPermissionRequestEventId(), oldContext);
1671 onSearchResultReceiveV2_ = useNewPipe ? eventHub->GetOnSearchResultReceiveEvent()
1672 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1673 webCom->GetSearchResultReceiveEventId(), oldContext);
1674 onScrollV2_ = useNewPipe ? eventHub->GetOnScrollEvent()
1675 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1676 webCom->GetScrollId(), oldContext);
1677 onWindowExitV2_ = useNewPipe ? eventHub->GetOnWindowExitEvent()
1678 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1679 webCom->GetWindowExitEventId(), oldContext);
1680 onPageVisibleV2_ = useNewPipe ? eventHub->GetOnPageVisibleEvent() : nullptr;
1681 onTouchIconUrlV2_ = useNewPipe ? eventHub->GetOnTouchIconUrlEvent() : nullptr;
1682 onAudioStateChangedV2_ = GetAudioStateChangedCallback(useNewPipe, eventHub);
1683 onFirstContentfulPaintV2_ = useNewPipe ? eventHub->GetOnFirstContentfulPaintEvent() : nullptr;
1684 onSafeBrowsingCheckResultV2_ = useNewPipe ? eventHub->GetOnSafeBrowsingCheckResultEvent() : nullptr;
1685 onOverScrollV2_ = useNewPipe ? eventHub->GetOnOverScrollEvent()
1686 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1687 webCom->GetOverScrollId(), oldContext);
1688 onScreenCaptureRequestV2_ = useNewPipe ? eventHub->GetOnScreenCaptureRequestEvent() : nullptr;
1689 onNavigationEntryCommittedV2_ = useNewPipe ? eventHub->GetOnNavigationEntryCommittedEvent() : nullptr;
1690 OnNativeEmbedLifecycleChangeV2_ = useNewPipe ? eventHub->GetOnNativeEmbedLifecycleChangeEvent()
1691 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1692 webCom->GetNativeEmbedLifecycleChangeId(), oldContext);
1693 OnNativeEmbedGestureEventV2_ = useNewPipe ? eventHub->GetOnNativeEmbedGestureEvent()
1694 : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1695 webCom->GetNativeEmbedGestureEventId(), oldContext);
1696 }
1697 return true;
1698 }
1699
OnSurfaceCreated(const sptr<OHOS::Surface> & surface)1700 void WebSurfaceCallback::OnSurfaceCreated(const sptr<OHOS::Surface>& surface) {}
1701
OnSurfaceChanged(const sptr<OHOS::Surface> & surface,int32_t width,int32_t height)1702 void WebSurfaceCallback::OnSurfaceChanged(const sptr<OHOS::Surface>& surface, int32_t width, int32_t height)
1703 {
1704 auto delegate = delegate_.Upgrade();
1705 if (!delegate) {
1706 return;
1707 }
1708 delegate->Resize((double)width, (double)height);
1709 }
1710
OnSurfaceDestroyed()1711 void WebSurfaceCallback::OnSurfaceDestroyed() {}
1712
GLGetConfig(int version,EGLDisplay eglDisplay)1713 EGLConfig WebDelegate::GLGetConfig(int version, EGLDisplay eglDisplay)
1714 {
1715 int attribList[] = { EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8,
1716 EGL_ALPHA_SIZE, 8, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_NONE };
1717 EGLConfig configs = NULL;
1718 int configsNum;
1719 if (!eglChooseConfig(eglDisplay, attribList, &configs, 1, &configsNum)) {
1720 return NULL;
1721 }
1722 return configs;
1723 }
1724
GLContextInit(void * window)1725 void WebDelegate::GLContextInit(void* window)
1726 {
1727 if (!window) {
1728 return;
1729 }
1730 mEglWindow = static_cast<EGLNativeWindowType>(window);
1731
1732 // 1. create sharedcontext
1733 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
1734 if (mEGLDisplay == EGL_NO_DISPLAY) {
1735 return;
1736 }
1737
1738 EGLint eglMajVers, eglMinVers;
1739 if (!eglInitialize(mEGLDisplay, &eglMajVers, &eglMinVers)) {
1740 mEGLDisplay = EGL_NO_DISPLAY;
1741 return;
1742 }
1743
1744 mEGLConfig = GLGetConfig(EGLCONFIG_VERSION, mEGLDisplay);
1745 if (mEGLConfig == nullptr) {
1746 return;
1747 }
1748
1749 // 2. Create EGL Surface from Native Window
1750 mEGLSurface = eglCreateWindowSurface(mEGLDisplay, mEGLConfig, mEglWindow, nullptr);
1751 if (mEGLSurface == nullptr) {
1752 return;
1753 }
1754
1755 // 3. Create EGLContext from
1756 int attrib3_list[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
1757
1758 mEGLContext = eglCreateContext(mEGLDisplay, mEGLConfig, mSharedEGLContext, attrib3_list);
1759
1760 if (!eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext)) {
1761 return;
1762 }
1763
1764 glViewport(offset_.GetX(), offset_.GetY(), drawSize_.Width(), drawSize_.Height());
1765 glClearColor(1.0, 1.0, 1.0, 1.0);
1766 glClear(GL_COLOR_BUFFER_BIT);
1767
1768 glFlush();
1769 glFinish();
1770 eglSwapBuffers(mEGLDisplay, mEGLSurface);
1771
1772 eglDestroySurface(mEGLDisplay, mEGLSurface);
1773 eglDestroyContext(mEGLDisplay, mEGLContext);
1774 }
1775
InitWebSurfaceDelegate(const WeakPtr<PipelineBase> & context)1776 bool WebDelegate::InitWebSurfaceDelegate(const WeakPtr<PipelineBase>& context)
1777 {
1778 auto pipelineContext = context.Upgrade();
1779 if (!pipelineContext) {
1780 return false;
1781 }
1782 uint32_t windowId = pipelineContext->GetWindowId();
1783 surfaceDelegate_ = new OHOS::SurfaceDelegate(windowId);
1784 if (surfaceDelegate_ == nullptr) {
1785 return false;
1786 }
1787 surfaceCallback_ = new WebSurfaceCallback(AceType::WeakClaim(this));
1788 if (surfaceCallback_ == nullptr) {
1789 return false;
1790 }
1791 surfaceDelegate_->AddSurfaceCallback(surfaceCallback_);
1792 surfaceDelegate_->CreateSurface();
1793 SetBoundsOrResize(drawSize_, offset_);
1794 needResizeAtFirst_ = true;
1795 auto aNativeSurface = surfaceDelegate_->GetNativeWindow();
1796 if (aNativeSurface == nullptr) {
1797 return false;
1798 }
1799 GLContextInit(aNativeSurface);
1800 surfaceInfo_.window = aNativeSurface;
1801 return true;
1802 }
1803
InitOHOSWeb(const WeakPtr<PipelineBase> & context)1804 void WebDelegate::InitOHOSWeb(const WeakPtr<PipelineBase>& context)
1805 {
1806 if (!PrepareInitOHOSWeb(context)) {
1807 return;
1808 }
1809 if (!isCreateWebView_) {
1810 isCreateWebView_ = true;
1811 if (isEnhanceSurface_) {
1812 if (!InitWebSurfaceDelegate(context)) {
1813 return;
1814 }
1815 InitWebViewWithSurface();
1816 } else {
1817 #ifdef ENABLE_ROSEN_BACKEND
1818 InitWebViewWithSurface();
1819 #else
1820 InitWebViewWithWindow();
1821 #endif
1822 }
1823 }
1824 }
RegisterOHOSWebEventAndMethord()1825 void WebDelegate::RegisterOHOSWebEventAndMethord()
1826 {
1827 auto reloadCallback = [weak = WeakClaim(this)]() {
1828 auto delegate = weak.Upgrade();
1829 if (!delegate) {
1830 return false;
1831 }
1832 delegate->Reload();
1833 return true;
1834 };
1835 WebClient::GetInstance().RegisterReloadCallback(reloadCallback);
1836
1837 auto webCom = webComponent_.Upgrade();
1838 CHECK_NULL_VOID(webCom);
1839 auto context = DynamicCast<PipelineContext>(context_.Upgrade());
1840 CHECK_NULL_VOID(context);
1841 if (!webCom->GetPageStartedEventId().IsEmpty()) {
1842 onPageStarted_ = AceAsyncEvent<void(const std::string&)>::Create(webCom->GetPageStartedEventId(), context);
1843 }
1844 if (!webCom->GetPageFinishedEventId().IsEmpty()) {
1845 onPageFinished_ = AceAsyncEvent<void(const std::string&)>::Create(webCom->GetPageFinishedEventId(), context);
1846 }
1847 if (!webCom->GetPageErrorEventId().IsEmpty()) {
1848 onPageError_ = AceAsyncEvent<void(const std::string&)>::Create(webCom->GetPageErrorEventId(), context);
1849 }
1850 }
1851
NotifyPopupWindowResult(bool result)1852 void WebDelegate::NotifyPopupWindowResult(bool result)
1853 {
1854 if (parentNWebId_ != -1) {
1855 std::weak_ptr<OHOS::NWeb::NWeb> parentNWebWeak = OHOS::NWeb::NWebHelper::Instance().GetNWeb(parentNWebId_);
1856 auto parentNWebSptr = parentNWebWeak.lock();
1857 if (parentNWebSptr) {
1858 parentNWebSptr->NotifyPopupWindowResult(result);
1859 }
1860 }
1861 }
1862
RunSetWebIdAndHapPathCallback()1863 void WebDelegate::RunSetWebIdAndHapPathCallback()
1864 {
1865 CHECK_NULL_VOID(nweb_);
1866 auto webId = nweb_->GetWebId();
1867
1868 #ifdef NG_BUILD
1869 auto pattern = webPattern_.Upgrade();
1870 CHECK_NULL_VOID(pattern);
1871 auto setWebIdCallback = pattern->GetSetWebIdCallback();
1872 CHECK_NULL_VOID(setWebIdCallback);
1873 setWebIdCallback(webId);
1874 auto onControllerAttachedCallback = pattern->GetOnControllerAttachedCallback();
1875 if (onControllerAttachedCallback) {
1876 onControllerAttachedCallback();
1877 }
1878 if (!hapPath_.empty()) {
1879 auto setHapPathCallback = pattern->GetSetHapPathCallback();
1880 CHECK_NULL_VOID(setHapPathCallback);
1881 setHapPathCallback(hapPath_);
1882 }
1883 NotifyPopupWindowResult(true);
1884 return;
1885 #else
1886 if (Container::IsCurrentUseNewPipeline()) {
1887 auto pattern = webPattern_.Upgrade();
1888 CHECK_NULL_VOID(pattern);
1889 auto setWebIdCallback = pattern->GetSetWebIdCallback();
1890 CHECK_NULL_VOID(setWebIdCallback);
1891 setWebIdCallback(webId);
1892 auto onControllerAttachedCallback = pattern->GetOnControllerAttachedCallback();
1893 if (onControllerAttachedCallback) {
1894 onControllerAttachedCallback();
1895 }
1896 if (!hapPath_.empty()) {
1897 auto setHapPathCallback = pattern->GetSetHapPathCallback();
1898 CHECK_NULL_VOID(setHapPathCallback);
1899 setHapPathCallback(hapPath_);
1900 }
1901 NotifyPopupWindowResult(true);
1902 return;
1903 }
1904 auto webCom = webComponent_.Upgrade();
1905 CHECK_NULL_VOID(webCom);
1906 auto setWebIdCallback = webCom->GetSetWebIdCallback();
1907 CHECK_NULL_VOID(setWebIdCallback);
1908 setWebIdCallback(webId);
1909 if (!hapPath_.empty()) {
1910 auto setHapPathCallback = webCom->GetSetHapPathCallback();
1911 CHECK_NULL_VOID(setHapPathCallback);
1912 setHapPathCallback(hapPath_);
1913 }
1914 NotifyPopupWindowResult(true);
1915 #endif
1916 }
1917
RunJsProxyCallback()1918 void WebDelegate::RunJsProxyCallback()
1919 {
1920 #ifdef NG_BUILD
1921 auto pattern = webPattern_.Upgrade();
1922 CHECK_NULL_VOID(pattern);
1923 pattern->CallJsProxyCallback();
1924 return;
1925 #else
1926 if (Container::IsCurrentUseNewPipeline()) {
1927 auto pattern = webPattern_.Upgrade();
1928 CHECK_NULL_VOID(pattern);
1929 pattern->CallJsProxyCallback();
1930 return;
1931 }
1932 auto webCom = webComponent_.Upgrade();
1933 CHECK_NULL_VOID(webCom);
1934 webCom->CallJsProxyCallback();
1935 #endif
1936 }
1937
RegisterConfigObserver()1938 void WebDelegate::RegisterConfigObserver()
1939 {
1940 auto context = context_.Upgrade();
1941 if (!context) {
1942 return;
1943 }
1944 context->GetTaskExecutor()->PostTask(
1945 [weak = WeakClaim(this)]() {
1946 auto delegate = weak.Upgrade();
1947 CHECK_NULL_VOID(delegate);
1948 CHECK_NULL_VOID(delegate->nweb_);
1949 auto appMgrClient = std::make_shared<AppExecFwk::AppMgrClient>();
1950 if (appMgrClient->ConnectAppMgrService()) {
1951 return;
1952 }
1953 delegate->configChangeObserver_ =
1954 sptr<AppExecFwk::IConfigurationObserver>(new (std::nothrow) WebConfigurationObserver(delegate));
1955 if (appMgrClient->RegisterConfigurationObserver(delegate->configChangeObserver_)) {
1956 return;
1957 }
1958 },
1959 TaskExecutor::TaskType::PLATFORM);
1960 }
1961
UnRegisterConfigObserver()1962 void WebDelegate::UnRegisterConfigObserver()
1963 {
1964 auto context = context_.Upgrade();
1965 if (!context) {
1966 return;
1967 }
1968 context->GetTaskExecutor()->PostTask(
1969 [weak = WeakClaim(this)]() {
1970 auto delegate = weak.Upgrade();
1971 CHECK_NULL_VOID(delegate);
1972 CHECK_NULL_VOID(delegate->nweb_);
1973 if (delegate->configChangeObserver_) {
1974 auto appMgrClient = std::make_shared<AppExecFwk::AppMgrClient>();
1975 if (appMgrClient->ConnectAppMgrService()) {
1976 return;
1977 }
1978 appMgrClient->UnregisterConfigurationObserver(delegate->configChangeObserver_);
1979 delegate->configChangeObserver_ = nullptr;
1980 }
1981 },
1982 TaskExecutor::TaskType::PLATFORM);
1983 }
1984
SetWebCallBack()1985 void WebDelegate::SetWebCallBack()
1986 {
1987 RefPtr<WebController> webController;
1988 if (Container::IsCurrentUseNewPipeline()) {
1989 auto pattern = webPattern_.Upgrade();
1990 webController = pattern ? pattern->GetWebController() : nullptr;
1991 } else {
1992 auto webCom = webComponent_.Upgrade();
1993 webController = webCom ? webCom->GetController() : nullptr;
1994 }
1995 if (webController) {
1996 auto context = context_.Upgrade();
1997 if (!context) {
1998 return;
1999 }
2000 auto uiTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::UI);
2001 webController->SetLoadUrlImpl([weak = WeakClaim(this), uiTaskExecutor](
2002 std::string url, const std::map<std::string, std::string>& httpHeaders) {
2003 uiTaskExecutor.PostTask([weak, url, httpHeaders]() {
2004 auto delegate = weak.Upgrade();
2005 if (delegate) {
2006 delegate->LoadUrl(url, httpHeaders);
2007 }
2008 });
2009 });
2010 webController->SetBackwardImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2011 uiTaskExecutor.PostTask([weak]() {
2012 auto delegate = weak.Upgrade();
2013 if (delegate) {
2014 delegate->Backward();
2015 }
2016 });
2017 });
2018 webController->SetForwardImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2019 uiTaskExecutor.PostTask([weak]() {
2020 auto delegate = weak.Upgrade();
2021 if (delegate) {
2022 delegate->Forward();
2023 }
2024 });
2025 });
2026 webController->SetClearHistoryImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2027 uiTaskExecutor.PostTask([weak]() {
2028 auto delegate = weak.Upgrade();
2029 if (delegate) {
2030 delegate->ClearHistory();
2031 }
2032 });
2033 });
2034 webController->SetClearSslCacheImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2035 uiTaskExecutor.PostTask([weak]() {
2036 auto delegate = weak.Upgrade();
2037 if (delegate) {
2038 delegate->ClearSslCache();
2039 }
2040 });
2041 });
2042 webController->SetClearClientAuthenticationCacheImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2043 uiTaskExecutor.PostTask([weak]() {
2044 auto delegate = weak.Upgrade();
2045 if (delegate) {
2046 delegate->ClearClientAuthenticationCache();
2047 }
2048 });
2049 });
2050 webController->SetAccessStepImpl([weak = WeakClaim(this)](int32_t step) {
2051 auto delegate = weak.Upgrade();
2052 if (delegate) {
2053 return delegate->AccessStep(step);
2054 }
2055 return false;
2056 });
2057 webController->SetBackOrForwardImpl([weak = WeakClaim(this)](int32_t step) {
2058 auto delegate = weak.Upgrade();
2059 if (delegate) {
2060 delegate->BackOrForward(step);
2061 }
2062 });
2063 webController->SetAccessBackwardImpl([weak = WeakClaim(this)]() {
2064 auto delegate = weak.Upgrade();
2065 if (delegate) {
2066 return delegate->AccessBackward();
2067 }
2068 return false;
2069 });
2070 webController->SetAccessForwardImpl([weak = WeakClaim(this)]() {
2071 auto delegate = weak.Upgrade();
2072 if (delegate) {
2073 return delegate->AccessForward();
2074 }
2075 return false;
2076 });
2077 webController->SetExecuteTypeScriptImpl([weak = WeakClaim(this), uiTaskExecutor](std::string jscode,
2078 std::function<void(const std::string)>&& callback) {
2079 uiTaskExecutor.PostTask([weak, jscode, callback]() {
2080 auto delegate = weak.Upgrade();
2081 if (delegate) {
2082 delegate->ExecuteTypeScript(jscode, std::move(callback));
2083 }
2084 });
2085 });
2086 webController->SetLoadDataWithBaseUrlImpl(
2087 [weak = WeakClaim(this), uiTaskExecutor](std::string baseUrl, std::string data, std::string mimeType,
2088 std::string encoding, std::string historyUrl) {
2089 uiTaskExecutor.PostTask([weak, baseUrl, data, mimeType, encoding, historyUrl]() {
2090 auto delegate = weak.Upgrade();
2091 if (delegate) {
2092 delegate->LoadDataWithBaseUrl(baseUrl, data, mimeType, encoding, historyUrl);
2093 }
2094 });
2095 });
2096 webController->SetRefreshImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2097 uiTaskExecutor.PostTask([weak]() {
2098 auto delegate = weak.Upgrade();
2099 if (delegate) {
2100 delegate->Refresh();
2101 }
2102 });
2103 });
2104 webController->SetStopLoadingImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2105 uiTaskExecutor.PostTask([weak]() {
2106 auto delegate = weak.Upgrade();
2107 if (delegate) {
2108 delegate->StopLoading();
2109 }
2110 });
2111 });
2112 webController->SetGetHitTestResultImpl([weak = WeakClaim(this)]() {
2113 auto delegate = weak.Upgrade();
2114 if (delegate) {
2115 return delegate->GetHitTestResult();
2116 }
2117 return 0;
2118 });
2119 webController->SetGetHitTestValueImpl([weak = WeakClaim(this)](HitTestResult& result) {
2120 auto delegate = weak.Upgrade();
2121 if (delegate) {
2122 delegate->GetHitTestValue(result);
2123 }
2124 });
2125 webController->SetGetPageHeightImpl([weak = WeakClaim(this)]() {
2126 auto delegate = weak.Upgrade();
2127 if (delegate) {
2128 return delegate->GetPageHeight();
2129 }
2130 return 0;
2131 });
2132 webController->SetGetWebIdImpl([weak = WeakClaim(this)]() {
2133 auto delegate = weak.Upgrade();
2134 if (delegate) {
2135 return delegate->GetWebId();
2136 }
2137 return -1;
2138 });
2139 webController->SetGetTitleImpl([weak = WeakClaim(this)]() {
2140 auto delegate = weak.Upgrade();
2141 if (delegate) {
2142 return delegate->GetTitle();
2143 }
2144 return std::string();
2145 });
2146 webController->SetCreateMsgPortsImpl([weak = WeakClaim(this)](std::vector<RefPtr<WebMessagePort>>& ports) {
2147 auto delegate = weak.Upgrade();
2148 if (delegate) {
2149 delegate->CreateWebMessagePorts(ports);
2150 }
2151 });
2152 webController->SetPostWebMessageImpl([weak = WeakClaim(this)](std::string& message,
2153 std::vector<RefPtr<WebMessagePort>>& ports, std::string& uri) {
2154 auto delegate = weak.Upgrade();
2155 if (delegate) {
2156 delegate->PostWebMessage(message, ports, uri);
2157 }
2158 });
2159 webController->SetGetDefaultUserAgentImpl([weak = WeakClaim(this)]() {
2160 auto delegate = weak.Upgrade();
2161 if (delegate) {
2162 return delegate->GetDefaultUserAgent();
2163 }
2164 return std::string();
2165 });
2166 webController->SetSaveCookieSyncImpl([weak = WeakClaim(this)]() {
2167 auto delegate = weak.Upgrade();
2168 if (delegate) {
2169 return delegate->SaveCookieSync();
2170 }
2171 return false;
2172 });
2173 webController->SetSetCookieImpl([weak = WeakClaim(this)](const std::string& url, const std::string& value) {
2174 auto delegate = weak.Upgrade();
2175 if (delegate) {
2176 return delegate->SetCookie(url, value, delegate->incognitoMode_);
2177 }
2178 return false;
2179 });
2180 webController->SetGetCookieImpl([weak = WeakClaim(this)](const std::string& url) {
2181 auto delegate = weak.Upgrade();
2182 if (delegate) {
2183 return delegate->GetCookie(url, delegate->incognitoMode_);
2184 }
2185 return std::string();
2186 });
2187 webController->SetDeleteEntirelyCookieImpl([weak = WeakClaim(this)]() {
2188 auto delegate = weak.Upgrade();
2189 if (delegate) {
2190 delegate->DeleteEntirelyCookie(delegate->incognitoMode_);
2191 }
2192 });
2193 webController->SetWebViewJavaScriptResultCallBackImpl(
2194 [weak = WeakClaim(this), uiTaskExecutor](WebController::JavaScriptCallBackImpl&& javaScriptCallBackImpl) {
2195 uiTaskExecutor.PostTask([weak, javaScriptCallBackImpl]() {
2196 auto delegate = weak.Upgrade();
2197 if (delegate) {
2198 delegate->SetWebViewJavaScriptResultCallBack(std::move(javaScriptCallBackImpl));
2199 }
2200 });
2201 });
2202 webController->SetAddJavascriptInterfaceImpl([weak = WeakClaim(this), uiTaskExecutor](std::string objectName,
2203 const std::vector<std::string>& methodList) {
2204 uiTaskExecutor.PostTask([weak, objectName, methodList]() {
2205 auto delegate = weak.Upgrade();
2206 if (delegate) {
2207 delegate->AddJavascriptInterface(objectName, methodList);
2208 }
2209 });
2210 });
2211 webController->LoadInitJavascriptInterface();
2212 webController->SetRemoveJavascriptInterfaceImpl([weak = WeakClaim(this), uiTaskExecutor](std::string objectName,
2213 const std::vector<std::string>& methodList) {
2214 uiTaskExecutor.PostTask([weak, objectName, methodList]() {
2215 auto delegate = weak.Upgrade();
2216 if (delegate) {
2217 delegate->RemoveJavascriptInterface(objectName, methodList);
2218 }
2219 });
2220 });
2221 webController->SetOnInactiveImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2222 uiTaskExecutor.PostTask([weak]() {
2223 auto delegate = weak.Upgrade();
2224 if (delegate) {
2225 delegate->OnInactive();
2226 }
2227 });
2228 });
2229 webController->SetOnActiveImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2230 uiTaskExecutor.PostTask([weak]() {
2231 auto delegate = weak.Upgrade();
2232 if (delegate) {
2233 delegate->OnActive();
2234 }
2235 });
2236 });
2237 webController->SetZoomImpl([weak = WeakClaim(this), uiTaskExecutor](float factor) {
2238 uiTaskExecutor.PostTask([weak, factor]() {
2239 auto delegate = weak.Upgrade();
2240 if (delegate) {
2241 delegate->Zoom(factor);
2242 }
2243 });
2244 });
2245 webController->SetZoomInImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2246 bool result = false;
2247 uiTaskExecutor.PostSyncTask([weak, &result]() {
2248 auto delegate = weak.Upgrade();
2249 if (delegate) {
2250 result = delegate->ZoomIn();
2251 }
2252 });
2253 return result;
2254 });
2255 webController->SetZoomOutImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2256 bool result = false;
2257 uiTaskExecutor.PostSyncTask([weak, &result]() {
2258 auto delegate = weak.Upgrade();
2259 if (delegate) {
2260 result = delegate->ZoomOut();
2261 }
2262 });
2263 return result;
2264 });
2265 webController->SetRequestFocusImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2266 uiTaskExecutor.PostTask([weak]() {
2267 auto delegate = weak.Upgrade();
2268 if (delegate) {
2269 delegate->RequestFocus();
2270 }
2271 });
2272 });
2273
2274 webController->SetSearchAllAsyncImpl([weak = WeakClaim(this), uiTaskExecutor](const std::string& searchStr) {
2275 uiTaskExecutor.PostTask([weak, searchStr]() {
2276 auto delegate = weak.Upgrade();
2277 if (delegate) {
2278 delegate->SearchAllAsync(searchStr);
2279 }
2280 });
2281 });
2282 webController->SetClearMatchesImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2283 uiTaskExecutor.PostTask([weak]() {
2284 auto delegate = weak.Upgrade();
2285 if (delegate) {
2286 delegate->ClearMatches();
2287 }
2288 });
2289 });
2290 webController->SetSearchNextImpl([weak = WeakClaim(this), uiTaskExecutor](bool forward) {
2291 uiTaskExecutor.PostTask([weak, forward]() {
2292 auto delegate = weak.Upgrade();
2293 if (delegate) {
2294 delegate->SearchNext(forward);
2295 }
2296 });
2297 });
2298 webController->SetGetUrlImpl([weak = WeakClaim(this)]() {
2299 auto delegate = weak.Upgrade();
2300 if (delegate) {
2301 return delegate->GetUrl();
2302 }
2303 return std::string();
2304 });
2305 } else {
2306 TAG_LOGW(AceLogTag::ACE_WEB, "web controller is nullptr");
2307 }
2308 }
2309
InitWebViewWithWindow()2310 void WebDelegate::InitWebViewWithWindow()
2311 {
2312 auto context = context_.Upgrade();
2313 CHECK_NULL_VOID(context);
2314 context->GetTaskExecutor()->PostTask(
2315 [weak = WeakClaim(this)]() {
2316 auto delegate = weak.Upgrade();
2317 if (!delegate) {
2318 return;
2319 }
2320 OHOS::NWeb::NWebInitArgs initArgs;
2321 std::string app_path = GetDataPath();
2322 if (!app_path.empty()) {
2323 initArgs.web_engine_args_to_add.push_back(std::string("--user-data-dir=").append(app_path));
2324 }
2325
2326 delegate->window_ = delegate->CreateWindow();
2327 if (!delegate->window_) {
2328 return;
2329 }
2330
2331 delegate->nweb_ =
2332 OHOS::NWeb::NWebAdapterHelper::Instance().CreateNWeb(
2333 delegate->window_.GetRefPtr(), initArgs,
2334 delegate->incognitoMode_);
2335 if (delegate->nweb_ == nullptr) {
2336 delegate->window_ = nullptr;
2337 return;
2338 }
2339 delegate->JavaScriptOnDocumentStart();
2340 delegate->JavaScriptOnDocumentEnd();
2341 delegate->cookieManager_ = OHOS::NWeb::NWebHelper::Instance().GetCookieManager();
2342 if (delegate->cookieManager_ == nullptr) {
2343 return;
2344 }
2345 auto webviewClient = std::make_shared<WebClientImpl>(Container::CurrentId());
2346 webviewClient->SetWebDelegate(weak);
2347 delegate->nweb_->SetNWebHandler(webviewClient);
2348
2349 // Set downloadListenerImpl
2350 auto downloadListenerImpl = std::make_shared<DownloadListenerImpl>(Container::CurrentId());
2351 downloadListenerImpl->SetWebDelegate(weak);
2352 delegate->nweb_->PutDownloadCallback(downloadListenerImpl);
2353
2354 auto findListenerImpl = std::make_shared<FindListenerImpl>(Container::CurrentId());
2355 findListenerImpl->SetWebDelegate(weak);
2356 delegate->nweb_->PutFindCallback(findListenerImpl);
2357
2358 std::optional<std::string> src;
2359 auto isNewPipe = Container::IsCurrentUseNewPipeline();
2360 delegate->UpdateSettting(isNewPipe);
2361 if (isNewPipe) {
2362 auto webPattern = delegate->webPattern_.Upgrade();
2363 if (webPattern) {
2364 src = webPattern->GetWebSrc();
2365 }
2366 } else {
2367 auto webCom = delegate->webComponent_.Upgrade();
2368 if (webCom) {
2369 src = webCom->GetSrc();
2370 }
2371 }
2372 if (src) {
2373 delegate->nweb_->Load(src.value());
2374 }
2375 delegate->window_->Show();
2376 },
2377 TaskExecutor::TaskType::PLATFORM);
2378 }
2379
UpdateSettting(bool useNewPipe)2380 void WebDelegate::UpdateSettting(bool useNewPipe)
2381 {
2382 CHECK_NULL_VOID(nweb_);
2383 auto setting = nweb_->GetPreference();
2384 CHECK_NULL_VOID(setting);
2385 #ifdef NG_BUILD
2386 auto webPattern = webPattern_.Upgrade();
2387 CHECK_NULL_VOID(webPattern);
2388 setting->PutDomStorageEnabled(webPattern->GetDomStorageAccessEnabledValue(false));
2389 setting->PutJavaScriptEnabled(webPattern->GetJsEnabledValue(true));
2390 setting->PutEnableRawFileAccess(webPattern->GetFileAccessEnabledValue(true));
2391 setting->PutEnableContentAccess(true);
2392 setting->PutLoadImageFromNetworkDisabled(!webPattern->GetOnLineImageAccessEnabledValue(true));
2393 setting->PutImageLoadingAllowed(webPattern->GetImageAccessEnabledValue(true));
2394 setting->PutAccessModeForSecureOriginLoadFromInsecure(static_cast<OHOS::NWeb::NWebPreference::AccessMode>(
2395 webPattern->GetMixedModeValue(MixedModeContent::MIXED_CONTENT_NEVER_ALLOW)));
2396 setting->PutZoomingFunctionEnabled(webPattern->GetZoomAccessEnabledValue(true));
2397 setting->PutGeolocationAllowed(webPattern->GetGeolocationAccessEnabledValue(true));
2398 setting->PutCacheMode(
2399 static_cast<OHOS::NWeb::NWebPreference::CacheModeFlag>(webPattern->GetCacheModeValue(WebCacheMode::DEFAULT)));
2400 setting->PutLoadWithOverviewMode(webPattern->GetOverviewModeAccessEnabledValue(true));
2401 setting->PutEnableRawFileAccessFromFileURLs(webPattern->GetFileFromUrlAccessEnabledValue(true));
2402 setting->PutDatabaseAllowed(webPattern->GetDatabaseAccessEnabledValue(false));
2403 setting->PutZoomingForTextFactor(webPattern->GetTextZoomRatioValue(DEFAULT_TEXT_ZOOM_RATIO));
2404 setting->PutWebDebuggingAccess(webPattern->GetWebDebuggingAccessEnabledValue(false));
2405 setting->PutMediaPlayGestureAccess(webPattern->GetMediaPlayGestureAccessValue(true));
2406 return;
2407 #else
2408 if (useNewPipe) {
2409 auto webPattern = webPattern_.Upgrade();
2410 CHECK_NULL_VOID(webPattern);
2411 setting->PutDomStorageEnabled(webPattern->GetDomStorageAccessEnabledValue(false));
2412 setting->PutJavaScriptEnabled(webPattern->GetJsEnabledValue(true));
2413 setting->PutEnableRawFileAccess(webPattern->GetFileAccessEnabledValue(true));
2414 setting->PutEnableContentAccess(true);
2415 setting->PutLoadImageFromNetworkDisabled(!webPattern->GetOnLineImageAccessEnabledValue(true));
2416 setting->PutImageLoadingAllowed(webPattern->GetImageAccessEnabledValue(true));
2417 setting->PutAccessModeForSecureOriginLoadFromInsecure(static_cast<OHOS::NWeb::NWebPreference::AccessMode>(
2418 webPattern->GetMixedModeValue(MixedModeContent::MIXED_CONTENT_NEVER_ALLOW)));
2419 setting->PutZoomingFunctionEnabled(webPattern->GetZoomAccessEnabledValue(true));
2420 setting->PutGeolocationAllowed(webPattern->GetGeolocationAccessEnabledValue(true));
2421 setting->PutCacheMode(static_cast<OHOS::NWeb::NWebPreference::CacheModeFlag>(
2422 webPattern->GetCacheModeValue(WebCacheMode::DEFAULT)));
2423 setting->PutLoadWithOverviewMode(webPattern->GetOverviewModeAccessEnabledValue(true));
2424 setting->PutEnableRawFileAccessFromFileURLs(webPattern->GetFileFromUrlAccessEnabledValue(true));
2425 setting->PutDatabaseAllowed(webPattern->GetDatabaseAccessEnabledValue(false));
2426 setting->PutZoomingForTextFactor(webPattern->GetTextZoomRatioValue(DEFAULT_TEXT_ZOOM_RATIO));
2427 setting->PutWebDebuggingAccess(webPattern->GetWebDebuggingAccessEnabledValue(false));
2428 setting->PutMediaPlayGestureAccess(webPattern->GetMediaPlayGestureAccessValue(true));
2429 return;
2430 }
2431 auto component = webComponent_.Upgrade();
2432 CHECK_NULL_VOID(component);
2433 setting->PutDomStorageEnabled(component->GetDomStorageAccessEnabled());
2434 setting->PutJavaScriptEnabled(component->GetJsEnabled());
2435 setting->PutEnableRawFileAccess(component->GetFileAccessEnabled());
2436 setting->PutEnableContentAccess(component->GetContentAccessEnabled());
2437 setting->PutLoadImageFromNetworkDisabled(component->GetOnLineImageAccessEnabled());
2438 setting->PutImageLoadingAllowed(component->GetImageAccessEnabled());
2439 setting->PutAccessModeForSecureOriginLoadFromInsecure(
2440 static_cast<OHOS::NWeb::NWebPreference::AccessMode>(component->GetMixedMode()));
2441 setting->PutZoomingFunctionEnabled(component->GetZoomAccessEnabled());
2442 setting->PutGeolocationAllowed(component->GetGeolocationAccessEnabled());
2443 setting->PutCacheMode(static_cast<OHOS::NWeb::NWebPreference::CacheModeFlag>(component->GetCacheMode()));
2444 setting->PutLoadWithOverviewMode(component->GetOverviewModeAccessEnabled());
2445 setting->PutEnableRawFileAccessFromFileURLs(component->GetFileFromUrlAccessEnabled());
2446 setting->PutDatabaseAllowed(component->GetDatabaseAccessEnabled());
2447 setting->PutZoomingForTextFactor(component->GetTextZoomRatio());
2448 setting->PutWebDebuggingAccess(component->GetWebDebuggingAccessEnabled());
2449 setting->PutMediaPlayGestureAccess(component->IsMediaPlayGestureAccess());
2450 #endif
2451 }
2452
GetCustomScheme()2453 std::string WebDelegate::GetCustomScheme()
2454 {
2455 std::string customScheme;
2456 if (Container::IsCurrentUseNewPipeline()) {
2457 auto webPattern = webPattern_.Upgrade();
2458 if (webPattern) {
2459 auto webData = webPattern->GetCustomScheme();
2460 if (webData) {
2461 customScheme = webData.value();
2462 }
2463 }
2464 } else {
2465 auto webCom = webComponent_.Upgrade();
2466 if (webCom) {
2467 customScheme = webCom->GetCustomScheme();
2468 }
2469 }
2470 return customScheme;
2471 }
2472
SurfaceOcclusionCallback(float visibleRatio)2473 void WebDelegate::SurfaceOcclusionCallback(float visibleRatio)
2474 {
2475 TAG_LOGI(AceLogTag::ACE_WEB,
2476 "SurfaceOcclusion changed, occlusionPoints:%{public}f, surfacenode id: %{public}" PRIu64 "", visibleRatio,
2477 surfaceNodeId_);
2478 if (fabs(visibleRatio_ - visibleRatio) <= FLT_EPSILON || (fabs(visibleRatio) > FLT_EPSILON && visibleRatio < 0.0) ||
2479 (fabs(visibleRatio - 1.0) > FLT_EPSILON && visibleRatio > 1.0)) {
2480 TAG_LOGE(AceLogTag::ACE_WEB, "visibleRatio is ilegal or not changed.");
2481 return;
2482 }
2483 visibleRatio_ = visibleRatio;
2484
2485 if (fabs(visibleRatio_) > FLT_EPSILON && visibleRatio_ > 0.0) {
2486 CHECK_NULL_VOID(nweb_);
2487 nweb_->OnUnoccluded();
2488 if (fabs(visibleRatio_ - lowerFrameRateVisibleRatio_) <= FLT_EPSILON ||
2489 visibleRatio_ < lowerFrameRateVisibleRatio_) {
2490 nweb_->SetEnableLowerFrameRate(true);
2491 } else {
2492 nweb_->SetEnableLowerFrameRate(false);
2493 }
2494 } else {
2495 auto context = context_.Upgrade();
2496 CHECK_NULL_VOID(context);
2497 CHECK_NULL_VOID(context->GetTaskExecutor());
2498 context->GetTaskExecutor()->PostDelayedTask(
2499 [weak = WeakClaim(this)]() {
2500 auto delegate = weak.Upgrade();
2501 CHECK_NULL_VOID(delegate);
2502 if (fabs(delegate->visibleRatio_) <= FLT_EPSILON) {
2503 TAG_LOGI(AceLogTag::ACE_WEB, "the web is still all occluded");
2504 CHECK_NULL_VOID(delegate->nweb_);
2505 delegate->nweb_->OnOccluded();
2506 }
2507 },
2508 TaskExecutor::TaskType::UI, delayTime_);
2509 }
2510 }
2511
ratioStrToFloat(const std::string & str)2512 void WebDelegate::ratioStrToFloat(const std::string& str)
2513 {
2514 // LowerFrameRateConfig format x.xx, len is 4, [0.00, 1.00]
2515 if (str.size() != VISIBLERATIO_LENGTH) {
2516 TAG_LOGE(AceLogTag::ACE_WEB, "visibleRatio lenth is over 4.");
2517 return;
2518 }
2519 auto dotCount = std::count(str.begin(), str.end(), '.');
2520 if (dotCount != 1) {
2521 TAG_LOGE(AceLogTag::ACE_WEB, "visibleRatio does not have dot.");
2522 return;
2523 }
2524 auto pos = str.find('.', 0);
2525 if (pos != 1) {
2526 TAG_LOGE(AceLogTag::ACE_WEB, "visibleRatio dot position is wrong.");
2527 return;
2528 }
2529 auto notDigitCount = std::count_if(str.begin(), str.end(), [](char c) { return !isdigit(c) && c != '.'; });
2530 if (notDigitCount > 0) {
2531 TAG_LOGE(AceLogTag::ACE_WEB, "visibleRatio dot count is over 1.");
2532 return;
2533 }
2534 float f = std::stof(str);
2535 int i = f * VISIBLERATIO_FLOAT_TO_INT;
2536 if (i >= 0 && i <= VISIBLERATIO_FLOAT_TO_INT) {
2537 TAG_LOGI(AceLogTag::ACE_WEB, "visibleRatio check success.");
2538 lowerFrameRateVisibleRatio_ = f;
2539 }
2540 }
2541
RegisterSurfaceOcclusionChangeFun()2542 void WebDelegate::RegisterSurfaceOcclusionChangeFun()
2543 {
2544 if (!GetWebOptimizationValue()) {
2545 TAG_LOGI(AceLogTag::ACE_WEB, "web optimization is close.");
2546 return;
2547 }
2548 if (!IsDeviceTabletOr2in1()) {
2549 TAG_LOGI(AceLogTag::ACE_WEB, "device type does not satisfy.");
2550 return;
2551 }
2552 std::string visibleAreaRatio =
2553 OHOS::NWeb::NWebAdapterHelper::Instance().ParsePerfConfig("LowerFrameRateConfig", "visibleAreaRatio");
2554 ratioStrToFloat(visibleAreaRatio);
2555 std::vector<float> partitionPoints;
2556 TAG_LOGI(AceLogTag::ACE_WEB, "max visible rate to lower frame rate:%{public}f", lowerFrameRateVisibleRatio_);
2557 if ((int)(lowerFrameRateVisibleRatio_ * VISIBLERATIO_FLOAT_TO_INT) == 0) {
2558 partitionPoints = { 0 };
2559 } else {
2560 partitionPoints = { 0, lowerFrameRateVisibleRatio_ };
2561 }
2562 auto ret = OHOS::Rosen::RSInterfaces::GetInstance().RegisterSurfaceOcclusionChangeCallback(
2563 surfaceNodeId_,
2564 [weak = WeakClaim(this), weakContext = context_](float visibleRatio) {
2565 auto context = weakContext.Upgrade();
2566 CHECK_NULL_VOID(context);
2567 context->GetTaskExecutor()->PostTask(
2568 [weakDelegate = weak, webVisibleRatio = visibleRatio]() {
2569 auto delegate = weakDelegate.Upgrade();
2570 CHECK_NULL_VOID(delegate);
2571 delegate->SurfaceOcclusionCallback(webVisibleRatio);
2572 },
2573 TaskExecutor::TaskType::UI);
2574 },
2575 partitionPoints);
2576 if (ret != Rosen::StatusCode::SUCCESS) {
2577 TAG_LOGI(AceLogTag::ACE_WEB,
2578 "RegisterSurfaceOcclusionChangeCallback failed, surfacenode id:%{public}" PRIu64 ""
2579 ", ret: %{public}" PRIu32 "",
2580 surfaceNodeId_, ret);
2581 }
2582 }
2583
InitWebViewWithSurface()2584 void WebDelegate::InitWebViewWithSurface()
2585 {
2586 auto context = context_.Upgrade();
2587 CHECK_NULL_VOID(context);
2588 auto window = context->GetWindow();
2589 CHECK_NULL_VOID(window);
2590 rosenWindowId_ = window->GetWindowId();
2591 context->GetTaskExecutor()->PostTask(
2592 [weak = WeakClaim(this), context = context_, webType = webType_]() {
2593 auto delegate = weak.Upgrade();
2594 CHECK_NULL_VOID(delegate);
2595 OHOS::NWeb::NWebInitArgs initArgs;
2596 initArgs.web_engine_args_to_add.push_back(
2597 std::string("--user-data-dir=").append(delegate->bundleDataPath_));
2598 initArgs.web_engine_args_to_add.push_back(
2599 std::string("--bundle-installation-dir=").append(delegate->bundlePath_));
2600 initArgs.web_engine_args_to_add.push_back(
2601 std::string("--lang=").append(AceApplicationInfo::GetInstance().GetLanguage() + "-" +
2602 AceApplicationInfo::GetInstance().GetCountryOrRegion()));
2603 initArgs.web_engine_args_to_add.push_back(
2604 std::string("--user-api-version=")
2605 .append(std::to_string(AceApplicationInfo::GetInstance().GetApiTargetVersion())));
2606 bool isEnhanceSurface = delegate->isEnhanceSurface_;
2607 initArgs.is_enhance_surface = isEnhanceSurface;
2608 initArgs.is_popup = delegate->isPopup_;
2609 if (!delegate->hapPath_.empty()) {
2610 initArgs.web_engine_args_to_add.push_back(std::string("--user-hap-path=").append(delegate->hapPath_));
2611 }
2612
2613 if (!delegate->tempDir_.empty()) {
2614 initArgs.web_engine_args_to_add.push_back(std::string("--ohos-temp-dir=").append(delegate->tempDir_));
2615 }
2616
2617 std::string customScheme = delegate->GetCustomScheme();
2618 if (!customScheme.empty()) {
2619 initArgs.web_engine_args_to_add.push_back(std::string("--ohos-custom-scheme=").append(customScheme));
2620 }
2621 initArgs.web_engine_args_to_add.push_back(
2622 std::string("--init-background-color=").append(std::to_string(delegate->backgroundColor_)));
2623 if (delegate->richtextData_) {
2624 // Created a richtext component
2625 initArgs.web_engine_args_to_add.push_back(
2626 std::string("--init-richtext-data=").append(delegate->richtextData_.value()));
2627 }
2628 if (isEnhanceSurface) {
2629 TAG_LOGD(AceLogTag::ACE_WEB, "Create webview with isEnhanceSurface");
2630 delegate->nweb_ = OHOS::NWeb::NWebAdapterHelper::Instance().CreateNWeb(
2631 (void *)(&delegate->surfaceInfo_),
2632 initArgs,
2633 delegate->drawSize_.Width(),
2634 delegate->drawSize_.Height(),
2635 delegate->incognitoMode_);
2636 delegate->JavaScriptOnDocumentStart();
2637 delegate->JavaScriptOnDocumentEnd();
2638 } else {
2639 #ifdef ENABLE_ROSEN_BACKEND
2640 wptr<Surface> surfaceWeak(delegate->surface_);
2641 sptr<Surface> surface = surfaceWeak.promote();
2642 CHECK_NULL_VOID(surface);
2643 delegate->nweb_ = OHOS::NWeb::NWebAdapterHelper::Instance().CreateNWeb(
2644 surface,
2645 initArgs,
2646 delegate->drawSize_.Width(),
2647 delegate->drawSize_.Height(),
2648 delegate->incognitoMode_);
2649 delegate->JavaScriptOnDocumentStart();
2650 delegate->JavaScriptOnDocumentEnd();
2651 #endif
2652 }
2653 CHECK_NULL_VOID(delegate->nweb_);
2654 delegate->cookieManager_ = OHOS::NWeb::NWebHelper::Instance().GetCookieManager();
2655 CHECK_NULL_VOID(delegate->cookieManager_);
2656 auto nweb_handler = std::make_shared<WebClientImpl>(Container::CurrentId());
2657 nweb_handler->SetWebDelegate(weak);
2658 auto downloadListenerImpl = std::make_shared<DownloadListenerImpl>(Container::CurrentId());
2659 downloadListenerImpl->SetWebDelegate(weak);
2660 delegate->nweb_->SetNWebHandler(nweb_handler);
2661 delegate->nweb_->PutDownloadCallback(downloadListenerImpl);
2662 #ifdef OHOS_STANDARD_SYSTEM
2663 delegate->nweb_->RegisterScreenLockFunction(delegate->GetRosenWindowId(), [context](bool key) {
2664 auto weakContext = context.Upgrade();
2665 CHECK_NULL_VOID(weakContext);
2666 auto window = weakContext->GetWindow();
2667 CHECK_NULL_VOID(window);
2668 window->SetKeepScreenOn(key);
2669 });
2670 #endif
2671 auto findListenerImpl = std::make_shared<FindListenerImpl>(Container::CurrentId());
2672 findListenerImpl->SetWebDelegate(weak);
2673 delegate->nweb_->PutFindCallback(findListenerImpl);
2674 delegate->UpdateSettting(Container::IsCurrentUseNewPipeline());
2675 delegate->RunSetWebIdAndHapPathCallback();
2676 delegate->RunJsProxyCallback();
2677 auto releaseSurfaceListenerImpl = std::make_shared<ReleaseSurfaceImpl>(Container::CurrentId());
2678 releaseSurfaceListenerImpl->SetSurfaceDelegate(delegate->GetSurfaceDelegateClient());
2679 delegate->nweb_->PutReleaseSurfaceCallback(releaseSurfaceListenerImpl);
2680 auto upgradeContext = context.Upgrade();
2681 CHECK_NULL_VOID(upgradeContext);
2682 auto window_id = upgradeContext->GetWindowId();
2683 delegate->nweb_->SetWindowId(window_id);
2684 delegate->SetToken();
2685 delegate->RegisterSurfaceOcclusionChangeFun();
2686 delegate->nweb_->SetDrawMode(webType);
2687 },
2688 TaskExecutor::TaskType::PLATFORM);
2689 }
2690
SetKeepScreenOn(bool key)2691 void WebDelegate::SetKeepScreenOn(bool key)
2692 {
2693 auto context = context_.Upgrade();
2694 CHECK_NULL_VOID(context);
2695 auto window = context->GetWindow();
2696 CHECK_NULL_VOID(window);
2697 window->SetKeepScreenOn(key);
2698 }
2699
UpdateUserAgent(const std::string & userAgent)2700 void WebDelegate::UpdateUserAgent(const std::string& userAgent)
2701 {
2702 auto context = context_.Upgrade();
2703 if (!context) {
2704 return;
2705 }
2706 context->GetTaskExecutor()->PostTask(
2707 [weak = WeakClaim(this), userAgent]() {
2708 auto delegate = weak.Upgrade();
2709 if (delegate && delegate->nweb_) {
2710 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
2711 CHECK_NULL_VOID(setting);
2712 setting->PutUserAgent(userAgent);
2713 }
2714 },
2715 TaskExecutor::TaskType::PLATFORM);
2716 }
2717
UpdateBackgroundColor(const int backgroundColor)2718 void WebDelegate::UpdateBackgroundColor(const int backgroundColor)
2719 {
2720 auto context = context_.Upgrade();
2721 if (!context) {
2722 return;
2723 }
2724 context->GetTaskExecutor()->PostTask(
2725 [weak = WeakClaim(this), backgroundColor]() {
2726 auto delegate = weak.Upgrade();
2727 if (delegate && delegate->nweb_) {
2728 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
2729 delegate->nweb_->PutBackgroundColor(backgroundColor);
2730 }
2731 },
2732 TaskExecutor::TaskType::PLATFORM);
2733 }
2734
UpdateInitialScale(float scale)2735 void WebDelegate::UpdateInitialScale(float scale)
2736 {
2737 auto context = context_.Upgrade();
2738 if (!context) {
2739 return;
2740 }
2741 context->GetTaskExecutor()->PostTask(
2742 [weak = WeakClaim(this), scale]() {
2743 auto delegate = weak.Upgrade();
2744 if (delegate && delegate->nweb_) {
2745 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
2746 delegate->nweb_->InitialScale(scale);
2747 }
2748 },
2749 TaskExecutor::TaskType::PLATFORM);
2750 }
2751
Resize(const double & width,const double & height,bool isKeyboard)2752 void WebDelegate::Resize(const double& width, const double& height, bool isKeyboard)
2753 {
2754 if (width <= 0 || height <= 0) {
2755 return;
2756 }
2757
2758 auto context = context_.Upgrade();
2759 if (!context) {
2760 return;
2761 }
2762 context->GetTaskExecutor()->PostTask(
2763 [weak = WeakClaim(this), width, height, isKeyboard]() {
2764 auto delegate = weak.Upgrade();
2765 if (delegate && delegate->nweb_ && !delegate->window_) {
2766 // Sur need int value, greater than this value in case show black line.
2767 delegate->nweb_->Resize(std::ceil(width), std::ceil(height), isKeyboard);
2768 double offsetX = 0;
2769 double offsetY = 0;
2770 delegate->UpdateScreenOffSet(offsetX, offsetY);
2771 delegate->nweb_->SetScreenOffSet(offsetX, offsetY);
2772 }
2773 },
2774 TaskExecutor::TaskType::PLATFORM);
2775 }
2776
UpdateJavaScriptEnabled(const bool & isJsEnabled)2777 void WebDelegate::UpdateJavaScriptEnabled(const bool& isJsEnabled)
2778 {
2779 auto context = context_.Upgrade();
2780 if (!context) {
2781 return;
2782 }
2783 context->GetTaskExecutor()->PostTask(
2784 [weak = WeakClaim(this), isJsEnabled]() {
2785 auto delegate = weak.Upgrade();
2786 if (delegate && delegate->nweb_) {
2787 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
2788 CHECK_NULL_VOID(setting);
2789 setting->PutJavaScriptEnabled(isJsEnabled);
2790 }
2791 },
2792 TaskExecutor::TaskType::PLATFORM);
2793 }
2794
UpdateAllowFileAccess(const bool & isFileAccessEnabled)2795 void WebDelegate::UpdateAllowFileAccess(const bool& isFileAccessEnabled)
2796 {
2797 auto context = context_.Upgrade();
2798 if (!context) {
2799 return;
2800 }
2801 context->GetTaskExecutor()->PostTask(
2802 [weak = WeakClaim(this), isFileAccessEnabled]() {
2803 auto delegate = weak.Upgrade();
2804 if (delegate && delegate->nweb_) {
2805 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
2806 CHECK_NULL_VOID(setting);
2807 setting->PutEnableRawFileAccess(isFileAccessEnabled);
2808 }
2809 },
2810 TaskExecutor::TaskType::PLATFORM);
2811 }
2812
UpdateBlockNetworkImage(const bool & onLineImageAccessEnabled)2813 void WebDelegate::UpdateBlockNetworkImage(const bool& onLineImageAccessEnabled)
2814 {
2815 auto context = context_.Upgrade();
2816 if (!context) {
2817 return;
2818 }
2819 context->GetTaskExecutor()->PostTask(
2820 [weak = WeakClaim(this), onLineImageAccessEnabled]() {
2821 auto delegate = weak.Upgrade();
2822 if (delegate && delegate->nweb_) {
2823 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
2824 CHECK_NULL_VOID(setting);
2825 setting->PutLoadImageFromNetworkDisabled(onLineImageAccessEnabled);
2826 }
2827 },
2828 TaskExecutor::TaskType::PLATFORM);
2829 }
2830
UpdateLoadsImagesAutomatically(const bool & isImageAccessEnabled)2831 void WebDelegate::UpdateLoadsImagesAutomatically(const bool& isImageAccessEnabled)
2832 {
2833 auto context = context_.Upgrade();
2834 if (!context) {
2835 return;
2836 }
2837 context->GetTaskExecutor()->PostTask(
2838 [weak = WeakClaim(this), isImageAccessEnabled]() {
2839 auto delegate = weak.Upgrade();
2840 if (delegate && delegate->nweb_) {
2841 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
2842 CHECK_NULL_VOID(setting);
2843 setting->PutImageLoadingAllowed(isImageAccessEnabled);
2844 }
2845 },
2846 TaskExecutor::TaskType::PLATFORM);
2847 }
2848
UpdateMixedContentMode(const MixedModeContent & mixedMode)2849 void WebDelegate::UpdateMixedContentMode(const MixedModeContent& mixedMode)
2850 {
2851 auto context = context_.Upgrade();
2852 if (!context) {
2853 return;
2854 }
2855 context->GetTaskExecutor()->PostTask(
2856 [weak = WeakClaim(this), mixedMode]() {
2857 auto delegate = weak.Upgrade();
2858 if (delegate && delegate->nweb_) {
2859 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
2860 CHECK_NULL_VOID(setting);
2861 setting->PutAccessModeForSecureOriginLoadFromInsecure(
2862 static_cast<OHOS::NWeb::NWebPreference::AccessMode>(mixedMode));
2863 }
2864 },
2865 TaskExecutor::TaskType::PLATFORM);
2866 }
2867
UpdateSupportZoom(const bool & isZoomAccessEnabled)2868 void WebDelegate::UpdateSupportZoom(const bool& isZoomAccessEnabled)
2869 {
2870 auto context = context_.Upgrade();
2871 if (!context) {
2872 return;
2873 }
2874 context->GetTaskExecutor()->PostTask(
2875 [weak = WeakClaim(this), isZoomAccessEnabled]() {
2876 auto delegate = weak.Upgrade();
2877 if (delegate && delegate->nweb_) {
2878 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
2879 CHECK_NULL_VOID(setting);
2880 setting->PutZoomingFunctionEnabled(isZoomAccessEnabled);
2881 }
2882 },
2883 TaskExecutor::TaskType::PLATFORM);
2884 }
UpdateDomStorageEnabled(const bool & isDomStorageAccessEnabled)2885 void WebDelegate::UpdateDomStorageEnabled(const bool& isDomStorageAccessEnabled)
2886 {
2887 auto context = context_.Upgrade();
2888 if (!context) {
2889 return;
2890 }
2891 context->GetTaskExecutor()->PostTask(
2892 [weak = WeakClaim(this), isDomStorageAccessEnabled]() {
2893 auto delegate = weak.Upgrade();
2894 if (delegate && delegate->nweb_) {
2895 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
2896 CHECK_NULL_VOID(setting);
2897 setting->PutDomStorageEnabled(isDomStorageAccessEnabled);
2898 }
2899 },
2900 TaskExecutor::TaskType::PLATFORM);
2901 }
UpdateGeolocationEnabled(const bool & isGeolocationAccessEnabled)2902 void WebDelegate::UpdateGeolocationEnabled(const bool& isGeolocationAccessEnabled)
2903 {
2904 auto context = context_.Upgrade();
2905 if (!context) {
2906 return;
2907 }
2908 context->GetTaskExecutor()->PostTask(
2909 [weak = WeakClaim(this), isGeolocationAccessEnabled]() {
2910 auto delegate = weak.Upgrade();
2911 if (delegate && delegate->nweb_) {
2912 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
2913 CHECK_NULL_VOID(setting);
2914 setting->PutGeolocationAllowed(isGeolocationAccessEnabled);
2915 }
2916 },
2917 TaskExecutor::TaskType::PLATFORM);
2918 }
2919
UpdateCacheMode(const WebCacheMode & mode)2920 void WebDelegate::UpdateCacheMode(const WebCacheMode& mode)
2921 {
2922 auto context = context_.Upgrade();
2923 if (!context) {
2924 return;
2925 }
2926 context->GetTaskExecutor()->PostTask(
2927 [weak = WeakClaim(this), mode]() {
2928 auto delegate = weak.Upgrade();
2929 if (delegate && delegate->nweb_) {
2930 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
2931 CHECK_NULL_VOID(setting);
2932 setting->PutCacheMode(static_cast<OHOS::NWeb::NWebPreference::CacheModeFlag>(mode));
2933 }
2934 },
2935 TaskExecutor::TaskType::PLATFORM);
2936 }
2937
GetNweb()2938 std::shared_ptr<OHOS::NWeb::NWeb> WebDelegate::GetNweb()
2939 {
2940 return nweb_;
2941 }
2942
GetForceDarkMode()2943 bool WebDelegate::GetForceDarkMode()
2944 {
2945 return forceDarkMode_;
2946 }
2947
UpdateDarkMode(const WebDarkMode & mode)2948 void WebDelegate::UpdateDarkMode(const WebDarkMode& mode)
2949 {
2950 auto context = context_.Upgrade();
2951 if (!context) {
2952 return;
2953 }
2954 context->GetTaskExecutor()->PostTask(
2955 [weak = WeakClaim(this), mode]() {
2956 auto delegate = weak.Upgrade();
2957 CHECK_NULL_VOID(delegate);
2958 CHECK_NULL_VOID(delegate->nweb_);
2959 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
2960 CHECK_NULL_VOID(setting);
2961 if (mode == WebDarkMode::On) {
2962 delegate->UnRegisterConfigObserver();
2963 setting->PutDarkSchemeEnabled(true);
2964 if (delegate->forceDarkMode_) {
2965 setting->PutForceDarkModeEnabled(true);
2966 }
2967 return;
2968 }
2969 if (mode == WebDarkMode::Off) {
2970 delegate->UnRegisterConfigObserver();
2971 setting->PutDarkSchemeEnabled(false);
2972 setting->PutForceDarkModeEnabled(false);
2973 return;
2974 }
2975 if (mode == WebDarkMode::Auto) {
2976 delegate->UpdateDarkModeAuto(delegate, setting);
2977 }
2978 },
2979 TaskExecutor::TaskType::PLATFORM);
2980 }
2981
UpdateDarkModeAuto(RefPtr<WebDelegate> delegate,std::shared_ptr<OHOS::NWeb::NWebPreference> setting)2982 void WebDelegate::UpdateDarkModeAuto(RefPtr<WebDelegate> delegate, std::shared_ptr<OHOS::NWeb::NWebPreference> setting)
2983 {
2984 auto appMgrClient = std::make_shared<AppExecFwk::AppMgrClient>();
2985 if (appMgrClient->ConnectAppMgrService()) {
2986 return;
2987 }
2988 auto systemConfig = OHOS::AppExecFwk::Configuration();
2989 appMgrClient->GetConfiguration(systemConfig);
2990 std::string colorMode = systemConfig.GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE);
2991 CHECK_NULL_VOID(setting);
2992 if (colorMode == "dark") {
2993 setting->PutDarkSchemeEnabled(true);
2994 if (delegate->GetForceDarkMode()) {
2995 setting->PutForceDarkModeEnabled(true);
2996 }
2997 }
2998 if (colorMode == "light") {
2999 setting->PutDarkSchemeEnabled(false);
3000 setting->PutForceDarkModeEnabled(false);
3001 }
3002 delegate->RegisterConfigObserver();
3003 }
3004
UpdateForceDarkAccess(const bool & access)3005 void WebDelegate::UpdateForceDarkAccess(const bool& access)
3006 {
3007 auto context = context_.Upgrade();
3008 if (!context) {
3009 return;
3010 }
3011 context->GetTaskExecutor()->PostTask(
3012 [weak = WeakClaim(this), access]() {
3013 auto delegate = weak.Upgrade();
3014 CHECK_NULL_VOID(delegate);
3015 CHECK_NULL_VOID(delegate->nweb_);
3016 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3017 CHECK_NULL_VOID(setting);
3018 delegate->forceDarkMode_ = access;
3019 if (setting->DarkSchemeEnabled()) {
3020 setting->PutForceDarkModeEnabled(access);
3021 } else {
3022 setting->PutForceDarkModeEnabled(false);
3023 }
3024 },
3025 TaskExecutor::TaskType::PLATFORM);
3026 }
3027
UpdateAudioResumeInterval(const int32_t & resumeInterval)3028 void WebDelegate::UpdateAudioResumeInterval(const int32_t& resumeInterval)
3029 {
3030 auto context = context_.Upgrade();
3031 if (!context) {
3032 return;
3033 }
3034 context->GetTaskExecutor()->PostTask(
3035 [weak = WeakClaim(this), resumeInterval]() {
3036 auto delegate = weak.Upgrade();
3037 CHECK_NULL_VOID(delegate);
3038 CHECK_NULL_VOID(delegate->nweb_);
3039 delegate->nweb_->SetAudioResumeInterval(resumeInterval);
3040 },
3041 TaskExecutor::TaskType::PLATFORM);
3042 }
3043
UpdateAudioExclusive(const bool & audioExclusive)3044 void WebDelegate::UpdateAudioExclusive(const bool& audioExclusive)
3045 {
3046 auto context = context_.Upgrade();
3047 if (!context) {
3048 return;
3049 }
3050 context->GetTaskExecutor()->PostTask(
3051 [weak = WeakClaim(this), audioExclusive]() {
3052 auto delegate = weak.Upgrade();
3053 CHECK_NULL_VOID(delegate);
3054 CHECK_NULL_VOID(delegate->nweb_);
3055 delegate->nweb_->SetAudioExclusive(audioExclusive);
3056 },
3057 TaskExecutor::TaskType::PLATFORM);
3058 }
3059
UpdateOverviewModeEnabled(const bool & isOverviewModeAccessEnabled)3060 void WebDelegate::UpdateOverviewModeEnabled(const bool& isOverviewModeAccessEnabled)
3061 {
3062 auto context = context_.Upgrade();
3063 if (!context) {
3064 return;
3065 }
3066 context->GetTaskExecutor()->PostTask(
3067 [weak = WeakClaim(this), isOverviewModeAccessEnabled]() {
3068 auto delegate = weak.Upgrade();
3069 if (delegate && delegate->nweb_) {
3070 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3071 CHECK_NULL_VOID(setting);
3072 setting->PutLoadWithOverviewMode(isOverviewModeAccessEnabled);
3073 }
3074 },
3075 TaskExecutor::TaskType::PLATFORM);
3076 }
3077
UpdateFileFromUrlEnabled(const bool & isFileFromUrlAccessEnabled)3078 void WebDelegate::UpdateFileFromUrlEnabled(const bool& isFileFromUrlAccessEnabled)
3079 {
3080 auto context = context_.Upgrade();
3081 if (!context) {
3082 return;
3083 }
3084 context->GetTaskExecutor()->PostTask(
3085 [weak = WeakClaim(this), isFileFromUrlAccessEnabled]() {
3086 auto delegate = weak.Upgrade();
3087 if (delegate && delegate->nweb_) {
3088 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3089 CHECK_NULL_VOID(setting);
3090 setting->PutEnableRawFileAccessFromFileURLs(isFileFromUrlAccessEnabled);
3091 }
3092 },
3093 TaskExecutor::TaskType::PLATFORM);
3094 }
3095
UpdateDatabaseEnabled(const bool & isDatabaseAccessEnabled)3096 void WebDelegate::UpdateDatabaseEnabled(const bool& isDatabaseAccessEnabled)
3097 {
3098 auto context = context_.Upgrade();
3099 if (!context) {
3100 return;
3101 }
3102 context->GetTaskExecutor()->PostTask(
3103 [weak = WeakClaim(this), isDatabaseAccessEnabled]() {
3104 auto delegate = weak.Upgrade();
3105 if (delegate && delegate->nweb_) {
3106 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3107 CHECK_NULL_VOID(setting);
3108 setting->PutDatabaseAllowed(isDatabaseAccessEnabled);
3109 }
3110 },
3111 TaskExecutor::TaskType::PLATFORM);
3112 }
3113
UpdateTextZoomRatio(const int32_t & textZoomRatioNum)3114 void WebDelegate::UpdateTextZoomRatio(const int32_t& textZoomRatioNum)
3115 {
3116 auto context = context_.Upgrade();
3117 if (!context) {
3118 return;
3119 }
3120 context->GetTaskExecutor()->PostTask(
3121 [weak = WeakClaim(this), textZoomRatioNum]() {
3122 auto delegate = weak.Upgrade();
3123 if (delegate && delegate->nweb_) {
3124 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3125 CHECK_NULL_VOID(setting);
3126 setting->PutZoomingForTextFactor(textZoomRatioNum);
3127 }
3128 },
3129 TaskExecutor::TaskType::PLATFORM);
3130 }
3131
UpdateWebDebuggingAccess(bool isWebDebuggingAccessEnabled)3132 void WebDelegate::UpdateWebDebuggingAccess(bool isWebDebuggingAccessEnabled)
3133 {
3134 auto context = context_.Upgrade();
3135 if (!context) {
3136 return;
3137 }
3138 context->GetTaskExecutor()->PostTask(
3139 [weak = WeakClaim(this), isWebDebuggingAccessEnabled]() {
3140 auto delegate = weak.Upgrade();
3141 if (delegate && delegate->nweb_) {
3142 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3143 CHECK_NULL_VOID(setting);
3144 setting->PutWebDebuggingAccess(isWebDebuggingAccessEnabled);
3145 }
3146 },
3147 TaskExecutor::TaskType::PLATFORM);
3148 }
3149
UpdatePinchSmoothModeEnabled(bool isPinchSmoothModeEnabled)3150 void WebDelegate::UpdatePinchSmoothModeEnabled(bool isPinchSmoothModeEnabled)
3151 {
3152 auto context = context_.Upgrade();
3153 if (!context) {
3154 return;
3155 }
3156 context->GetTaskExecutor()->PostTask(
3157 [weak = WeakClaim(this), isPinchSmoothModeEnabled]() {
3158 auto delegate = weak.Upgrade();
3159 if (delegate && delegate->nweb_) {
3160 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3161 CHECK_NULL_VOID(setting);
3162 setting->PutPinchSmoothMode(isPinchSmoothModeEnabled);
3163 }
3164 },
3165 TaskExecutor::TaskType::PLATFORM);
3166 }
3167
UpdateMediaPlayGestureAccess(bool isNeedGestureAccess)3168 void WebDelegate::UpdateMediaPlayGestureAccess(bool isNeedGestureAccess)
3169 {
3170 auto context = context_.Upgrade();
3171 if (!context) {
3172 return;
3173 }
3174 context->GetTaskExecutor()->PostTask(
3175 [weak = WeakClaim(this), isNeedGestureAccess]() {
3176 auto delegate = weak.Upgrade();
3177 if (delegate && delegate->nweb_) {
3178 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3179 if (setting) {
3180 setting->PutMediaPlayGestureAccess(isNeedGestureAccess);
3181 }
3182 }
3183 },
3184 TaskExecutor::TaskType::PLATFORM);
3185 }
3186
UpdateMultiWindowAccess(bool isMultiWindowAccessEnabled)3187 void WebDelegate::UpdateMultiWindowAccess(bool isMultiWindowAccessEnabled)
3188 {
3189 auto context = context_.Upgrade();
3190 if (!context) {
3191 return;
3192 }
3193 context->GetTaskExecutor()->PostTask(
3194 [weak = WeakClaim(this), isMultiWindowAccessEnabled]() {
3195 auto delegate = weak.Upgrade();
3196 if (delegate && delegate->nweb_) {
3197 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3198 CHECK_NULL_VOID(setting);
3199 setting->PutMultiWindowAccess(isMultiWindowAccessEnabled);
3200 }
3201 },
3202 TaskExecutor::TaskType::PLATFORM);
3203 }
3204
UpdateAllowWindowOpenMethod(bool isAllowWindowOpenMethod)3205 void WebDelegate::UpdateAllowWindowOpenMethod(bool isAllowWindowOpenMethod)
3206 {
3207 auto context = context_.Upgrade();
3208 if (!context) {
3209 return;
3210 }
3211 context->GetTaskExecutor()->PostTask(
3212 [weak = WeakClaim(this), isAllowWindowOpenMethod]() {
3213 auto delegate = weak.Upgrade();
3214 if (delegate && delegate->nweb_) {
3215 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3216 CHECK_NULL_VOID(setting);
3217 setting->PutIsCreateWindowsByJavaScriptAllowed(isAllowWindowOpenMethod);
3218 }
3219 },
3220 TaskExecutor::TaskType::PLATFORM);
3221 }
3222
UpdateWebCursiveFont(const std::string & cursiveFontFamily)3223 void WebDelegate::UpdateWebCursiveFont(const std::string& cursiveFontFamily)
3224 {
3225 auto context = context_.Upgrade();
3226 if (!context) {
3227 return;
3228 }
3229 context->GetTaskExecutor()->PostTask(
3230 [weak = WeakClaim(this), cursiveFontFamily]() {
3231 auto delegate = weak.Upgrade();
3232 if (delegate && delegate->nweb_) {
3233 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3234 if (setting) {
3235 setting->PutCursiveFontFamilyName(cursiveFontFamily);
3236 }
3237 }
3238 },
3239 TaskExecutor::TaskType::PLATFORM);
3240 }
3241
UpdateWebFantasyFont(const std::string & fantasyFontFamily)3242 void WebDelegate::UpdateWebFantasyFont(const std::string& fantasyFontFamily)
3243 {
3244 auto context = context_.Upgrade();
3245 if (!context) {
3246 return;
3247 }
3248 context->GetTaskExecutor()->PostTask(
3249 [weak = WeakClaim(this), fantasyFontFamily]() {
3250 auto delegate = weak.Upgrade();
3251 if (delegate && delegate->nweb_) {
3252 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3253 if (setting) {
3254 setting->PutFantasyFontFamilyName(fantasyFontFamily);
3255 }
3256 }
3257 },
3258 TaskExecutor::TaskType::PLATFORM);
3259 }
3260
UpdateWebFixedFont(const std::string & fixedFontFamily)3261 void WebDelegate::UpdateWebFixedFont(const std::string& fixedFontFamily)
3262 {
3263 auto context = context_.Upgrade();
3264 if (!context) {
3265 return;
3266 }
3267 context->GetTaskExecutor()->PostTask(
3268 [weak = WeakClaim(this), fixedFontFamily]() {
3269 auto delegate = weak.Upgrade();
3270 if (delegate && delegate->nweb_) {
3271 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3272 if (setting) {
3273 setting->PutFixedFontFamilyName(fixedFontFamily);
3274 }
3275 }
3276 },
3277 TaskExecutor::TaskType::PLATFORM);
3278 }
3279
UpdateWebSansSerifFont(const std::string & sansSerifFontFamily)3280 void WebDelegate::UpdateWebSansSerifFont(const std::string& sansSerifFontFamily)
3281 {
3282 auto context = context_.Upgrade();
3283 if (!context) {
3284 return;
3285 }
3286 context->GetTaskExecutor()->PostTask(
3287 [weak = WeakClaim(this), sansSerifFontFamily]() {
3288 auto delegate = weak.Upgrade();
3289 if (delegate && delegate->nweb_) {
3290 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3291 if (setting) {
3292 setting->PutSansSerifFontFamilyName(sansSerifFontFamily);
3293 }
3294 }
3295 },
3296 TaskExecutor::TaskType::PLATFORM);
3297 }
3298
UpdateWebSerifFont(const std::string & serifFontFamily)3299 void WebDelegate::UpdateWebSerifFont(const std::string& serifFontFamily)
3300 {
3301 auto context = context_.Upgrade();
3302 if (!context) {
3303 return;
3304 }
3305 context->GetTaskExecutor()->PostTask(
3306 [weak = WeakClaim(this), serifFontFamily]() {
3307 auto delegate = weak.Upgrade();
3308 if (delegate && delegate->nweb_) {
3309 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3310 if (setting) {
3311 setting->PutSerifFontFamilyName(serifFontFamily);
3312 }
3313 }
3314 },
3315 TaskExecutor::TaskType::PLATFORM);
3316 }
3317
UpdateWebStandardFont(const std::string & standardFontFamily)3318 void WebDelegate::UpdateWebStandardFont(const std::string& standardFontFamily)
3319 {
3320 auto context = context_.Upgrade();
3321 if (!context) {
3322 return;
3323 }
3324 context->GetTaskExecutor()->PostTask(
3325 [weak = WeakClaim(this), standardFontFamily]() {
3326 auto delegate = weak.Upgrade();
3327 if (delegate && delegate->nweb_) {
3328 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3329 if (setting) {
3330 setting->PutStandardFontFamilyName(standardFontFamily);
3331 }
3332 }
3333 },
3334 TaskExecutor::TaskType::PLATFORM);
3335 }
3336
UpdateDefaultFixedFontSize(int32_t defaultFixedFontSize)3337 void WebDelegate::UpdateDefaultFixedFontSize(int32_t defaultFixedFontSize)
3338 {
3339 auto context = context_.Upgrade();
3340 if (!context) {
3341 return;
3342 }
3343 context->GetTaskExecutor()->PostTask(
3344 [weak = WeakClaim(this), defaultFixedFontSize]() {
3345 auto delegate = weak.Upgrade();
3346 if (delegate && delegate->nweb_) {
3347 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3348 if (setting) {
3349 setting->PutDefaultFixedFontSize(defaultFixedFontSize);
3350 }
3351 }
3352 },
3353 TaskExecutor::TaskType::PLATFORM);
3354 }
3355
OnConfigurationUpdated(const std::string & colorMode)3356 void WebDelegate::OnConfigurationUpdated(const std::string& colorMode)
3357 {
3358 auto context = context_.Upgrade();
3359 CHECK_NULL_VOID(context);
3360
3361 auto executor = context->GetTaskExecutor();
3362 CHECK_NULL_VOID(executor);
3363
3364 executor->PostTask(
3365 [weak = WeakClaim(this), colorMode]() {
3366 auto delegate = weak.Upgrade();
3367 CHECK_NULL_VOID(delegate);
3368 auto nweb = delegate->GetNweb();
3369 CHECK_NULL_VOID(nweb);
3370 auto setting = nweb->GetPreference();
3371 CHECK_NULL_VOID(setting);
3372
3373 if (colorMode == "dark") {
3374 setting->PutDarkSchemeEnabled(true);
3375 if (delegate->GetForceDarkMode()) {
3376 setting->PutForceDarkModeEnabled(true);
3377 }
3378 return;
3379 }
3380 if (colorMode == "light") {
3381 setting->PutDarkSchemeEnabled(false);
3382 setting->PutForceDarkModeEnabled(false);
3383 }
3384 },
3385 TaskExecutor::TaskType::PLATFORM);
3386 }
3387
UpdateDefaultFontSize(int32_t defaultFontSize)3388 void WebDelegate::UpdateDefaultFontSize(int32_t defaultFontSize)
3389 {
3390 auto context = context_.Upgrade();
3391 if (!context) {
3392 return;
3393 }
3394 context->GetTaskExecutor()->PostTask(
3395 [weak = WeakClaim(this), defaultFontSize]() {
3396 auto delegate = weak.Upgrade();
3397 if (delegate && delegate->nweb_) {
3398 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3399 if (setting) {
3400 setting->PutDefaultFontSize(defaultFontSize);
3401 }
3402 }
3403 },
3404 TaskExecutor::TaskType::PLATFORM);
3405 }
3406
UpdateMinFontSize(int32_t minFontSize)3407 void WebDelegate::UpdateMinFontSize(int32_t minFontSize)
3408 {
3409 auto context = context_.Upgrade();
3410 if (!context) {
3411 return;
3412 }
3413 context->GetTaskExecutor()->PostTask(
3414 [weak = WeakClaim(this), minFontSize]() {
3415 auto delegate = weak.Upgrade();
3416 if (delegate && delegate->nweb_) {
3417 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3418 if (setting) {
3419 setting->PutFontSizeLowerLimit(minFontSize);
3420 }
3421 }
3422 },
3423 TaskExecutor::TaskType::PLATFORM);
3424 }
3425
UpdateMinLogicalFontSize(int32_t minLogicalFontSize)3426 void WebDelegate::UpdateMinLogicalFontSize(int32_t minLogicalFontSize)
3427 {
3428 auto context = context_.Upgrade();
3429 if (!context) {
3430 return;
3431 }
3432 context->GetTaskExecutor()->PostTask(
3433 [weak = WeakClaim(this), minLogicalFontSize]() {
3434 auto delegate = weak.Upgrade();
3435 if (delegate && delegate->nweb_) {
3436 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3437 if (setting) {
3438 setting->PutLogicalFontSizeLowerLimit(minLogicalFontSize);
3439 }
3440 }
3441 },
3442 TaskExecutor::TaskType::PLATFORM);
3443 }
3444
UpdateBlockNetwork(bool isNetworkBlocked)3445 void WebDelegate::UpdateBlockNetwork(bool isNetworkBlocked)
3446 {
3447 auto context = context_.Upgrade();
3448 if (!context) {
3449 return;
3450 }
3451 context->GetTaskExecutor()->PostTask(
3452 [weak = WeakClaim(this), isNetworkBlocked]() {
3453 auto delegate = weak.Upgrade();
3454 if (delegate && delegate->nweb_) {
3455 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3456 if (setting) {
3457 setting->PutBlockNetwork(isNetworkBlocked);
3458 }
3459 }
3460 },
3461 TaskExecutor::TaskType::PLATFORM);
3462 }
3463
UpdateHorizontalScrollBarAccess(bool isHorizontalScrollBarAccessEnabled)3464 void WebDelegate::UpdateHorizontalScrollBarAccess(bool isHorizontalScrollBarAccessEnabled)
3465 {
3466 auto context = context_.Upgrade();
3467 if (!context) {
3468 return;
3469 }
3470 context->GetTaskExecutor()->PostTask(
3471 [weak = WeakClaim(this), isHorizontalScrollBarAccessEnabled]() {
3472 auto delegate = weak.Upgrade();
3473 if (delegate && delegate->nweb_) {
3474 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3475 if (setting) {
3476 setting->PutHorizontalScrollBarAccess(isHorizontalScrollBarAccessEnabled);
3477 }
3478 }
3479 },
3480 TaskExecutor::TaskType::PLATFORM);
3481 }
3482
UpdateVerticalScrollBarAccess(bool isVerticalScrollBarAccessEnabled)3483 void WebDelegate::UpdateVerticalScrollBarAccess(bool isVerticalScrollBarAccessEnabled)
3484 {
3485 auto context = context_.Upgrade();
3486 if (!context) {
3487 return;
3488 }
3489 context->GetTaskExecutor()->PostTask(
3490 [weak = WeakClaim(this), isVerticalScrollBarAccessEnabled]() {
3491 auto delegate = weak.Upgrade();
3492 if (delegate && delegate->nweb_) {
3493 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3494 if (setting) {
3495 setting->PutVerticalScrollBarAccess(isVerticalScrollBarAccessEnabled);
3496 }
3497 }
3498 },
3499 TaskExecutor::TaskType::PLATFORM);
3500 }
3501
UpdateNativeEmbedModeEnabled(bool isEmbedModeEnabled)3502 void WebDelegate::UpdateNativeEmbedModeEnabled(bool isEmbedModeEnabled)
3503 {
3504 auto context = context_.Upgrade();
3505 if (!context) {
3506 return;
3507 }
3508 isEmbedModeEnabled_ = isEmbedModeEnabled;
3509 context->GetTaskExecutor()->PostTask(
3510 [weak = WeakClaim(this), isEmbedModeEnabled]() {
3511 auto delegate = weak.Upgrade();
3512 if (delegate && delegate->nweb_) {
3513 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3514 if (setting) {
3515 setting->SetNativeEmbedMode(isEmbedModeEnabled);
3516 }
3517 }
3518 },
3519 TaskExecutor::TaskType::PLATFORM);
3520 }
3521
UpdateScrollBarColor(const std::string & colorValue)3522 void WebDelegate::UpdateScrollBarColor(const std::string& colorValue)
3523 {
3524 auto context = context_.Upgrade();
3525 if (!context) {
3526 return;
3527 }
3528
3529 auto pipeline = PipelineContext::GetCurrentContext();
3530 if (pipeline == nullptr) {
3531 return;
3532 }
3533
3534 auto themeManager = pipeline->GetThemeManager();
3535 if (themeManager == nullptr) {
3536 return;
3537 }
3538
3539 auto themeConstants = themeManager->GetThemeConstants();
3540 if (themeConstants == nullptr) {
3541 return;
3542 }
3543 Color color = themeConstants->GetColorByName(colorValue);
3544 uint32_t colorContent = color.GetValue();
3545 context->GetTaskExecutor()->PostTask(
3546 [weak = WeakClaim(this), colorContent]() {
3547 auto delegate = weak.Upgrade();
3548 if (delegate && delegate->nweb_) {
3549 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3550 if (setting) {
3551 setting->PutScrollBarColor(colorContent);
3552 }
3553 }
3554 },
3555 TaskExecutor::TaskType::PLATFORM);
3556 }
3557
LoadUrl()3558 void WebDelegate::LoadUrl()
3559 {
3560 auto context = context_.Upgrade();
3561 CHECK_NULL_VOID(context);
3562 context->GetTaskExecutor()->PostTask(
3563 [weak = WeakClaim(this)]() {
3564 auto delegate = weak.Upgrade();
3565 if (delegate && delegate->nweb_) {
3566 std::optional<std::string> src;
3567 if (Container::IsCurrentUseNewPipeline()) {
3568 auto webPattern = delegate->webPattern_.Upgrade();
3569 if (webPattern) {
3570 src = webPattern->GetWebSrc();
3571 }
3572 } else {
3573 auto webCom = delegate->webComponent_.Upgrade();
3574 if (webCom) {
3575 src = webCom->GetSrc();
3576 }
3577 }
3578 CHECK_NULL_VOID(src);
3579 delegate->nweb_->Load(src.value());
3580 }
3581 },
3582 TaskExecutor::TaskType::PLATFORM);
3583 }
3584
OnInactive()3585 void WebDelegate::OnInactive()
3586 {
3587 auto context = context_.Upgrade();
3588 if (!context) {
3589 return;
3590 }
3591 context->GetTaskExecutor()->PostTask(
3592 [weak = WeakClaim(this)]() {
3593 auto delegate = weak.Upgrade();
3594 if (!delegate) {
3595 return;
3596 }
3597 if (delegate->nweb_) {
3598 delegate->nweb_->OnPause();
3599 }
3600 },
3601 TaskExecutor::TaskType::PLATFORM);
3602 }
3603
OnActive()3604 void WebDelegate::OnActive()
3605 {
3606 auto context = context_.Upgrade();
3607 if (!context) {
3608 return;
3609 }
3610 context->GetTaskExecutor()->PostTask(
3611 [weak = WeakClaim(this)]() {
3612 auto delegate = weak.Upgrade();
3613 if (!delegate) {
3614 return;
3615 }
3616 if (delegate->nweb_) {
3617 delegate->nweb_->OnContinue();
3618 }
3619 },
3620 TaskExecutor::TaskType::PLATFORM);
3621 }
3622
OnWebviewHide()3623 void WebDelegate::OnWebviewHide()
3624 {
3625 auto context = context_.Upgrade();
3626 if (!context) {
3627 return;
3628 }
3629 context->GetTaskExecutor()->PostTask(
3630 [weak = WeakClaim(this)]() {
3631 auto delegate = weak.Upgrade();
3632 if (!delegate) {
3633 return;
3634 }
3635 if (delegate->nweb_) {
3636 delegate->nweb_->OnWebviewHide();
3637 }
3638 },
3639 TaskExecutor::TaskType::PLATFORM);
3640 }
3641
OnWebviewShow()3642 void WebDelegate::OnWebviewShow()
3643 {
3644 auto context = context_.Upgrade();
3645 if (!context) {
3646 return;
3647 }
3648 context->GetTaskExecutor()->PostTask(
3649 [weak = WeakClaim(this)]() {
3650 auto delegate = weak.Upgrade();
3651 if (!delegate) {
3652 return;
3653 }
3654 if (delegate->nweb_) {
3655 delegate->nweb_->OnWebviewShow();
3656 }
3657 },
3658 TaskExecutor::TaskType::PLATFORM);
3659 }
3660
SetShouldFrameSubmissionBeforeDraw(bool should)3661 void WebDelegate::SetShouldFrameSubmissionBeforeDraw(bool should)
3662 {
3663 auto context = context_.Upgrade();
3664 if (!context) {
3665 return;
3666 }
3667 context->GetTaskExecutor()->PostTask(
3668 [weak = WeakClaim(this), should]() {
3669 auto delegate = weak.Upgrade();
3670 if (!delegate) {
3671 return;
3672 }
3673 if (delegate->nweb_) {
3674 delegate->nweb_->SetShouldFrameSubmissionBeforeDraw(should);
3675 }
3676 },
3677 TaskExecutor::TaskType::PLATFORM);
3678 }
3679
NotifyMemoryLevel(int32_t level)3680 void WebDelegate::NotifyMemoryLevel(int32_t level)
3681 {
3682 auto context = context_.Upgrade();
3683 if (!context) {
3684 return;
3685 }
3686 context->GetTaskExecutor()->PostTask(
3687 [weak = WeakClaim(this), level]() {
3688 auto delegate = weak.Upgrade();
3689 if (!delegate) {
3690 return;
3691 }
3692 if (delegate->nweb_) {
3693 delegate->nweb_->NotifyMemoryLevel(level);
3694 }
3695 },
3696 TaskExecutor::TaskType::PLATFORM);
3697 }
3698
SetAudioMuted(bool muted)3699 void WebDelegate::SetAudioMuted(bool muted)
3700 {
3701 ACE_DCHECK(nweb_ != nullptr);
3702 if (nweb_) {
3703 nweb_->SetAudioMuted(muted);
3704 }
3705 }
3706
Zoom(float factor)3707 void WebDelegate::Zoom(float factor)
3708 {
3709 auto context = context_.Upgrade();
3710 if (!context) {
3711 return;
3712 }
3713
3714 context->GetTaskExecutor()->PostTask(
3715 [weak = WeakClaim(this), factor]() {
3716 auto delegate = weak.Upgrade();
3717 if (!delegate) {
3718 return;
3719 }
3720 if (delegate->nweb_) {
3721 delegate->nweb_->Zoom(factor);
3722 }
3723 },
3724 TaskExecutor::TaskType::PLATFORM);
3725 }
3726
ZoomIn()3727 bool WebDelegate::ZoomIn()
3728 {
3729 auto context = context_.Upgrade();
3730 if (!context) {
3731 return false;
3732 }
3733 bool result = false;
3734 context->GetTaskExecutor()->PostSyncTask(
3735 [weak = WeakClaim(this), &result]() {
3736 auto delegate = weak.Upgrade();
3737 if (!delegate) {
3738 return;
3739 }
3740 if (delegate->nweb_) {
3741 result = delegate->nweb_->ZoomIn();
3742 }
3743 },
3744 TaskExecutor::TaskType::PLATFORM);
3745 return result;
3746 }
3747
ZoomOut()3748 bool WebDelegate::ZoomOut()
3749 {
3750 auto context = context_.Upgrade();
3751 if (!context) {
3752 return false;
3753 }
3754 bool result = false;
3755 context->GetTaskExecutor()->PostSyncTask(
3756 [weak = WeakClaim(this), &result]() {
3757 auto delegate = weak.Upgrade();
3758 if (!delegate) {
3759 return;
3760 }
3761 if (delegate->nweb_) {
3762 result = delegate->nweb_->ZoomOut();
3763 }
3764 },
3765 TaskExecutor::TaskType::PLATFORM);
3766 return result;
3767 }
3768
CreateWindow()3769 sptr<OHOS::Rosen::Window> WebDelegate::CreateWindow()
3770 {
3771 auto context = context_.Upgrade();
3772 if (!context) {
3773 return nullptr;
3774 }
3775 float scale = context->GetViewScale();
3776
3777 constexpr int DEFAULT_HEIGHT = 1600;
3778 int DEFAULT_HEIGHT_WITHOUT_SYSTEM_BAR = (int)(scale * context->GetRootHeight());
3779 int DEFAULT_STATUS_BAR_HEIGHT = (DEFAULT_HEIGHT - DEFAULT_HEIGHT_WITHOUT_SYSTEM_BAR) / 2;
3780 constexpr int DEFAULT_LEFT = 0;
3781 int DEFAULT_TOP = DEFAULT_STATUS_BAR_HEIGHT;
3782 int DEFAULT_WIDTH = (int)(scale * context->GetRootWidth());
3783 sptr<Rosen::WindowOption> option = new Rosen::WindowOption();
3784 option->SetWindowRect({ DEFAULT_LEFT, DEFAULT_TOP, DEFAULT_WIDTH, DEFAULT_HEIGHT_WITHOUT_SYSTEM_BAR });
3785 option->SetWindowType(Rosen::WindowType::WINDOW_TYPE_APP_LAUNCHING);
3786 option->SetWindowMode(Rosen::WindowMode::WINDOW_MODE_FLOATING);
3787 auto window = Rosen::Window::Create("ohos_web_window", option);
3788 return window;
3789 }
3790 #endif
3791
RegisterWebEvent()3792 void WebDelegate::RegisterWebEvent()
3793 {
3794 // TODO: add support for ng.
3795 auto context = DynamicCast<PipelineContext>(context_.Upgrade());
3796 CHECK_NULL_VOID(context);
3797 auto resRegister = context->GetPlatformResRegister();
3798 if (resRegister == nullptr) {
3799 return;
3800 }
3801 resRegister->RegisterEvent(MakeEventHash(WEB_EVENT_PAGESTART), [weak = WeakClaim(this)](const std::string& param) {
3802 auto delegate = weak.Upgrade();
3803 if (delegate) {
3804 delegate->OnPageStarted(param);
3805 }
3806 });
3807 resRegister->RegisterEvent(MakeEventHash(WEB_EVENT_PAGEFINISH), [weak = WeakClaim(this)](const std::string& param) {
3808 auto delegate = weak.Upgrade();
3809 if (delegate) {
3810 delegate->OnPageFinished(param);
3811 }
3812 });
3813 resRegister->RegisterEvent(MakeEventHash(WEB_EVENT_PAGEERROR), [weak = WeakClaim(this)](const std::string& param) {
3814 auto delegate = weak.Upgrade();
3815 if (delegate) {
3816 delegate->OnPageError(param);
3817 }
3818 });
3819 resRegister->RegisterEvent(MakeEventHash(WEB_EVENT_ROUTERPUSH), [weak = WeakClaim(this)](const std::string& param) {
3820 auto delegate = weak.Upgrade();
3821 if (delegate) {
3822 delegate->OnRouterPush(param);
3823 }
3824 });
3825 resRegister->RegisterEvent(MakeEventHash(WEB_EVENT_ONMESSAGE), [weak = WeakClaim(this)](const std::string& param) {
3826 auto delegate = weak.Upgrade();
3827 if (delegate) {
3828 delegate->OnMessage(param);
3829 }
3830 });
3831 }
3832
3833 // upper ui component which inherited from WebComponent
3834 // could implement some curtain createdCallback to customized controller interface
3835 // eg: web.loadurl.
AddCreatedCallback(const CreatedCallback & createdCallback)3836 void WebDelegate::AddCreatedCallback(const CreatedCallback& createdCallback)
3837 {
3838 ACE_DCHECK(createdCallback != nullptr);
3839 ACE_DCHECK(state_ != State::RELEASED);
3840 createdCallbacks_.emplace_back(createdCallback);
3841 }
3842
RemoveCreatedCallback()3843 void WebDelegate::RemoveCreatedCallback()
3844 {
3845 ACE_DCHECK(state_ != State::RELEASED);
3846 createdCallbacks_.pop_back();
3847 }
3848
AddReleasedCallback(const ReleasedCallback & releasedCallback)3849 void WebDelegate::AddReleasedCallback(const ReleasedCallback& releasedCallback)
3850 {
3851 ACE_DCHECK(releasedCallback != nullptr && state_ != State::RELEASED);
3852 releasedCallbacks_.emplace_back(releasedCallback);
3853 }
3854
RemoveReleasedCallback()3855 void WebDelegate::RemoveReleasedCallback()
3856 {
3857 ACE_DCHECK(state_ != State::RELEASED);
3858 releasedCallbacks_.pop_back();
3859 }
3860
Reload()3861 void WebDelegate::Reload()
3862 {
3863 #ifdef OHOS_STANDARD_SYSTEM
3864 auto context = context_.Upgrade();
3865 if (!context) {
3866 return;
3867 }
3868 context->GetTaskExecutor()->PostTask(
3869 [weak = WeakClaim(this)]() {
3870 auto delegate = weak.Upgrade();
3871 if (!delegate) {
3872 return;
3873 }
3874 if (delegate->nweb_) {
3875 delegate->nweb_->Reload();
3876 }
3877 },
3878 TaskExecutor::TaskType::PLATFORM);
3879 #else
3880 hash_ = MakeResourceHash();
3881 reloadMethod_ = MakeMethodHash("reload");
3882 CallResRegisterMethod(reloadMethod_, WEB_PARAM_NONE, nullptr);
3883 #endif
3884 }
3885
UpdateUrl(const std::string & url)3886 void WebDelegate::UpdateUrl(const std::string& url)
3887 {
3888 hash_ = MakeResourceHash();
3889 updateUrlMethod_ = MakeMethodHash(WEB_METHOD_UPDATEURL);
3890 std::stringstream paramStream;
3891 paramStream << NTC_PARAM_SRC << WEB_PARAM_EQUALS << url;
3892 std::string param = paramStream.str();
3893 CallResRegisterMethod(updateUrlMethod_, param, nullptr);
3894 }
3895
CallWebRouterBack()3896 void WebDelegate::CallWebRouterBack()
3897 {
3898 hash_ = MakeResourceHash();
3899 routerBackMethod_ = MakeMethodHash(WEB_METHOD_ROUTER_BACK);
3900 CallResRegisterMethod(routerBackMethod_, WEB_PARAM_NONE, nullptr);
3901 }
3902
CallPopPageSuccessPageUrl(const std::string & url)3903 void WebDelegate::CallPopPageSuccessPageUrl(const std::string& url)
3904 {
3905 hash_ = MakeResourceHash();
3906 changePageUrlMethod_ = MakeMethodHash(WEB_METHOD_CHANGE_PAGE_URL);
3907 std::stringstream paramStream;
3908 paramStream << NTC_PARAM_PAGE_URL << WEB_PARAM_EQUALS << url;
3909 std::string param = paramStream.str();
3910 CallResRegisterMethod(changePageUrlMethod_, param, nullptr);
3911 }
3912
CallIsPagePathInvalid(const bool & isPageInvalid)3913 void WebDelegate::CallIsPagePathInvalid(const bool& isPageInvalid)
3914 {
3915 hash_ = MakeResourceHash();
3916 isPagePathInvalidMethod_ = MakeMethodHash(WEB_METHOD_PAGE_PATH_INVALID);
3917 std::stringstream paramStream;
3918 paramStream << NTC_PARAM_PAGE_INVALID << WEB_PARAM_EQUALS << isPageInvalid;
3919 std::string param = paramStream.str();
3920 CallResRegisterMethod(isPagePathInvalidMethod_, param, nullptr);
3921 }
3922
RecordWebEvent(Recorder::EventType eventType,const std::string & param) const3923 void WebDelegate::RecordWebEvent(Recorder::EventType eventType, const std::string& param) const
3924 {
3925 if (!Recorder::EventRecorder::Get().IsComponentRecordEnable()) {
3926 return;
3927 }
3928 auto pattern = webPattern_.Upgrade();
3929 CHECK_NULL_VOID(pattern);
3930 auto host = pattern->GetHost();
3931 CHECK_NULL_VOID(host);
3932 Recorder::EventParamsBuilder builder;
3933 builder.SetId(host->GetInspectorIdValue(""))
3934 .SetType(host->GetHostTag())
3935 .SetEventType(eventType)
3936 .SetText(param)
3937 .SetDescription(host->GetAutoEventParamValue(""));
3938 Recorder::EventRecorder::Get().OnEvent(std::move(builder));
3939 }
3940
OnPageStarted(const std::string & param)3941 void WebDelegate::OnPageStarted(const std::string& param)
3942 {
3943 auto context = context_.Upgrade();
3944 CHECK_NULL_VOID(context);
3945 context->GetTaskExecutor()->PostTask(
3946 [weak = WeakClaim(this), param]() {
3947 auto delegate = weak.Upgrade();
3948 CHECK_NULL_VOID(delegate);
3949 auto onPageStarted = delegate->onPageStarted_;
3950 if (onPageStarted) {
3951 std::string paramStart = std::string(R"(")").append(param).append(std::string(R"(")"));
3952 std::string urlParam = std::string(R"("pagestart",{"url":)").append(paramStart.append("},null"));
3953 onPageStarted(urlParam);
3954 }
3955
3956 // ace 2.0
3957 auto onPageStartedV2 = delegate->onPageStartedV2_;
3958 if (onPageStartedV2) {
3959 onPageStartedV2(std::make_shared<LoadWebPageStartEvent>(param));
3960 }
3961 delegate->RecordWebEvent(Recorder::EventType::WEB_PAGE_BEGIN, param);
3962 },
3963 TaskExecutor::TaskType::JS);
3964 }
3965
OnPageFinished(const std::string & param)3966 void WebDelegate::OnPageFinished(const std::string& param)
3967 {
3968 auto context = context_.Upgrade();
3969 CHECK_NULL_VOID(context);
3970 context->GetTaskExecutor()->PostTask(
3971 [weak = WeakClaim(this), param]() {
3972 auto delegate = weak.Upgrade();
3973 CHECK_NULL_VOID(delegate);
3974 auto onPageFinished = delegate->onPageFinished_;
3975 if (onPageFinished) {
3976 std::string paramFinish = std::string(R"(")").append(param).append(std::string(R"(")"));
3977 std::string urlParam = std::string(R"("pagefinish",{"url":)").append(paramFinish.append("},null"));
3978 onPageFinished(urlParam);
3979 }
3980 // ace 2.0
3981 auto onPageFinishedV2 = delegate->onPageFinishedV2_;
3982 if (onPageFinishedV2) {
3983 onPageFinishedV2(std::make_shared<LoadWebPageFinishEvent>(param));
3984 }
3985 delegate->RecordWebEvent(Recorder::EventType::WEB_PAGE_END, param);
3986 },
3987 TaskExecutor::TaskType::JS);
3988 }
3989
OnProgressChanged(int param)3990 void WebDelegate::OnProgressChanged(int param)
3991 {
3992 auto context = context_.Upgrade();
3993 CHECK_NULL_VOID(context);
3994 context->GetTaskExecutor()->PostTask(
3995 [weak = WeakClaim(this), param]() {
3996 auto delegate = weak.Upgrade();
3997 CHECK_NULL_VOID(delegate);
3998 auto eventParam = std::make_shared<LoadWebProgressChangeEvent>(param);
3999 if (Container::IsCurrentUseNewPipeline()) {
4000 auto webPattern = delegate->webPattern_.Upgrade();
4001 CHECK_NULL_VOID(webPattern);
4002 auto webEventHub = webPattern->GetWebEventHub();
4003 CHECK_NULL_VOID(webEventHub);
4004 webEventHub->FireOnProgressChangeEvent(eventParam);
4005 return;
4006 }
4007 auto webCom = delegate->webComponent_.Upgrade();
4008 CHECK_NULL_VOID(webCom);
4009 webCom->OnProgressChange(eventParam.get());
4010 },
4011 TaskExecutor::TaskType::JS);
4012 }
4013
OnReceivedTitle(const std::string & param)4014 void WebDelegate::OnReceivedTitle(const std::string& param)
4015 {
4016 auto context = context_.Upgrade();
4017 CHECK_NULL_VOID(context);
4018 context->GetTaskExecutor()->PostTask(
4019 [weak = WeakClaim(this), param]() {
4020 auto delegate = weak.Upgrade();
4021 CHECK_NULL_VOID(delegate);
4022 // ace 2.0
4023 auto onTitleReceiveV2 = delegate->onTitleReceiveV2_;
4024 if (onTitleReceiveV2) {
4025 onTitleReceiveV2(std::make_shared<LoadWebTitleReceiveEvent>(param));
4026 }
4027 },
4028 TaskExecutor::TaskType::JS);
4029 }
4030
ExitFullScreen()4031 void WebDelegate::ExitFullScreen()
4032 {
4033 if (Container::IsCurrentUseNewPipeline()) {
4034 auto webPattern = webPattern_.Upgrade();
4035 CHECK_NULL_VOID(webPattern);
4036 webPattern->ExitFullScreen();
4037 }
4038 }
4039
OnFullScreenExit()4040 void WebDelegate::OnFullScreenExit()
4041 {
4042 auto context = context_.Upgrade();
4043 CHECK_NULL_VOID(context);
4044 context->GetTaskExecutor()->PostTask(
4045 [weak = WeakClaim(this)]() {
4046 auto delegate = weak.Upgrade();
4047 CHECK_NULL_VOID(delegate);
4048 auto param = std::make_shared<FullScreenExitEvent>(false);
4049 #ifdef NG_BUILD
4050 auto webPattern = delegate->webPattern_.Upgrade();
4051 CHECK_NULL_VOID(webPattern);
4052 auto webEventHub = webPattern->GetWebEventHub();
4053 CHECK_NULL_VOID(webEventHub);
4054 auto propOnFullScreenExitEvent = webEventHub->GetOnFullScreenExitEvent();
4055 CHECK_NULL_VOID(propOnFullScreenExitEvent);
4056 propOnFullScreenExitEvent(param);
4057 return;
4058 #else
4059 if (Container::IsCurrentUseNewPipeline()) {
4060 auto webPattern = delegate->webPattern_.Upgrade();
4061 CHECK_NULL_VOID(webPattern);
4062 auto webEventHub = webPattern->GetWebEventHub();
4063 CHECK_NULL_VOID(webEventHub);
4064 auto propOnFullScreenExitEvent = webEventHub->GetOnFullScreenExitEvent();
4065 CHECK_NULL_VOID(propOnFullScreenExitEvent);
4066 propOnFullScreenExitEvent(param);
4067 return;
4068 }
4069 // ace 2.0
4070 auto onFullScreenExitV2 = delegate->onFullScreenExitV2_;
4071 if (onFullScreenExitV2) {
4072 onFullScreenExitV2(param);
4073 }
4074 #endif
4075 },
4076 TaskExecutor::TaskType::JS);
4077 }
4078
OnGeolocationPermissionsHidePrompt()4079 void WebDelegate::OnGeolocationPermissionsHidePrompt()
4080 {
4081 auto context = context_.Upgrade();
4082 CHECK_NULL_VOID(context);
4083 context->GetTaskExecutor()->PostTask(
4084 [weak = WeakClaim(this)]() {
4085 auto delegate = weak.Upgrade();
4086 CHECK_NULL_VOID(delegate);
4087 // ace 2.0
4088 auto onGeolocationHideV2 = delegate->onGeolocationHideV2_;
4089 if (onGeolocationHideV2) {
4090 onGeolocationHideV2(std::make_shared<LoadWebGeolocationHideEvent>(""));
4091 }
4092 },
4093 TaskExecutor::TaskType::JS);
4094 }
4095
OnGeolocationPermissionsShowPrompt(const std::string & origin,const std::shared_ptr<OHOS::NWeb::NWebGeolocationCallbackInterface> & callback)4096 void WebDelegate::OnGeolocationPermissionsShowPrompt(
4097 const std::string& origin, const std::shared_ptr<OHOS::NWeb::NWebGeolocationCallbackInterface>& callback)
4098 {
4099 auto context = context_.Upgrade();
4100 CHECK_NULL_VOID(context);
4101 context->GetTaskExecutor()->PostTask(
4102 [weak = WeakClaim(this), origin, callback]() {
4103 auto delegate = weak.Upgrade();
4104 CHECK_NULL_VOID(delegate);
4105 // ace 2.0
4106 auto onGeolocationShowV2 = delegate->onGeolocationShowV2_;
4107 if (onGeolocationShowV2) {
4108 auto geolocation =
4109 AceType::MakeRefPtr<WebGeolocationOhos>(callback,
4110 delegate->incognitoMode_);
4111 onGeolocationShowV2(std::make_shared<LoadWebGeolocationShowEvent>(origin, geolocation));
4112 }
4113 },
4114 TaskExecutor::TaskType::JS);
4115 }
4116
OnPermissionRequestPrompt(const std::shared_ptr<OHOS::NWeb::NWebAccessRequest> & request)4117 void WebDelegate::OnPermissionRequestPrompt(const std::shared_ptr<OHOS::NWeb::NWebAccessRequest>& request)
4118 {
4119 auto context = context_.Upgrade();
4120 CHECK_NULL_VOID(context);
4121 context->GetTaskExecutor()->PostTask(
4122 [weak = WeakClaim(this), request]() {
4123 auto delegate = weak.Upgrade();
4124 CHECK_NULL_VOID(delegate);
4125 if (request->ResourceAcessId() & OHOS::NWeb::NWebAccessRequest::Resources::CLIPBOARD_READ_WRITE) {
4126 auto webPattern = delegate->webPattern_.Upgrade();
4127 CHECK_NULL_VOID(webPattern);
4128 auto clipboardCallback = webPattern->GetPermissionClipboardCallback();
4129 CHECK_NULL_VOID(clipboardCallback);
4130 clipboardCallback(std::make_shared<WebPermissionRequestEvent>(
4131 AceType::MakeRefPtr<WebPermissionRequestOhos>(request)));
4132 return;
4133 }
4134 // ace 2.0
4135 auto onPermissionRequestV2 = delegate->onPermissionRequestV2_;
4136 if (onPermissionRequestV2) {
4137 onPermissionRequestV2(std::make_shared<WebPermissionRequestEvent>(
4138 AceType::MakeRefPtr<WebPermissionRequestOhos>(request)));
4139 }
4140 },
4141 TaskExecutor::TaskType::JS);
4142 }
4143
OnScreenCaptureRequest(const std::shared_ptr<OHOS::NWeb::NWebScreenCaptureAccessRequest> & request)4144 void WebDelegate::OnScreenCaptureRequest(const std::shared_ptr<OHOS::NWeb::NWebScreenCaptureAccessRequest>& request)
4145 {
4146 auto context = context_.Upgrade();
4147 CHECK_NULL_VOID(context);
4148 context->GetTaskExecutor()->PostTask(
4149 [weak = WeakClaim(this), request]() {
4150 auto delegate = weak.Upgrade();
4151 CHECK_NULL_VOID(delegate);
4152 // ace 2.0
4153 auto onScreenCaptureRequestV2 = delegate->onScreenCaptureRequestV2_;
4154 if (onScreenCaptureRequestV2) {
4155 onScreenCaptureRequestV2(std::make_shared<WebScreenCaptureRequestEvent>(
4156 AceType::MakeRefPtr<WebScreenCaptureRequestOhos>(request)));
4157 }
4158 },
4159 TaskExecutor::TaskType::JS);
4160 }
4161
OnConsoleLog(std::shared_ptr<OHOS::NWeb::NWebConsoleLog> message)4162 bool WebDelegate::OnConsoleLog(std::shared_ptr<OHOS::NWeb::NWebConsoleLog> message)
4163 {
4164 auto context = context_.Upgrade();
4165 CHECK_NULL_RETURN(context, false);
4166 bool result = false;
4167 auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
4168 jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), message, &result]() {
4169 auto delegate = weak.Upgrade();
4170 CHECK_NULL_VOID(delegate);
4171 auto param = std::make_shared<LoadWebConsoleLogEvent>(AceType::MakeRefPtr<ConsoleLogOhos>(message));
4172 if (Container::IsCurrentUseNewPipeline()) {
4173 auto webPattern = delegate->webPattern_.Upgrade();
4174 CHECK_NULL_VOID(webPattern);
4175 auto webEventHub = webPattern->GetWebEventHub();
4176 CHECK_NULL_VOID(webEventHub);
4177 auto propOnConsoleEvent = webEventHub->GetOnConsoleEvent();
4178 CHECK_NULL_VOID(propOnConsoleEvent);
4179 result = propOnConsoleEvent(param);
4180 }
4181 auto webCom = delegate->webComponent_.Upgrade();
4182 CHECK_NULL_VOID(webCom);
4183 result = webCom->OnConsole(param.get());
4184 return;
4185 });
4186 return result;
4187 }
4188
OnCommonDialog(const std::shared_ptr<BaseEventInfo> & info,DialogEventType dialogEventType)4189 bool WebDelegate::OnCommonDialog(const std::shared_ptr<BaseEventInfo>& info, DialogEventType dialogEventType)
4190 {
4191 auto context = context_.Upgrade();
4192 CHECK_NULL_RETURN(context, false);
4193 bool result = false;
4194 auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
4195 jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), info, dialogEventType, &result]() {
4196 auto delegate = weak.Upgrade();
4197 CHECK_NULL_VOID(delegate);
4198 #ifdef NG_BUILD
4199 auto webPattern = delegate->webPattern_.Upgrade();
4200 CHECK_NULL_VOID(webPattern);
4201 auto webEventHub = webPattern->GetWebEventHub();
4202 CHECK_NULL_VOID(webEventHub);
4203 result = webEventHub->FireOnCommonDialogEvent(info, dialogEventType);
4204 return;
4205 #else
4206 if (Container::IsCurrentUseNewPipeline()) {
4207 auto webPattern = delegate->webPattern_.Upgrade();
4208 CHECK_NULL_VOID(webPattern);
4209 auto webEventHub = webPattern->GetWebEventHub();
4210 CHECK_NULL_VOID(webEventHub);
4211 result = webEventHub->FireOnCommonDialogEvent(info, dialogEventType);
4212 return;
4213 }
4214 auto webCom = delegate->webComponent_.Upgrade();
4215 CHECK_NULL_VOID(webCom);
4216 result = webCom->OnCommonDialog(info.get(), dialogEventType);
4217 return;
4218 #endif
4219 });
4220 return result;
4221 }
4222
OnFullScreenEnter(std::shared_ptr<OHOS::NWeb::NWebFullScreenExitHandler> handler)4223 void WebDelegate::OnFullScreenEnter(std::shared_ptr<OHOS::NWeb::NWebFullScreenExitHandler> handler)
4224 {
4225 auto context = context_.Upgrade();
4226 CHECK_NULL_VOID(context);
4227 context->GetTaskExecutor()->PostTask(
4228 [weak = WeakClaim(this), handler]() {
4229 auto delegate = weak.Upgrade();
4230 CHECK_NULL_VOID(delegate);
4231 auto param =
4232 std::make_shared<FullScreenEnterEvent>(AceType::MakeRefPtr<FullScreenExitHandlerOhos>(handler, weak));
4233 #ifdef NG_BUILD
4234 auto webPattern = delegate->webPattern_.Upgrade();
4235 CHECK_NULL_VOID(webPattern);
4236 webPattern->RequestFullScreen();
4237 webPattern->SetFullScreenExitHandler(param);
4238 auto webEventHub = webPattern->GetWebEventHub();
4239 CHECK_NULL_VOID(webEventHub);
4240 auto propOnFullScreenEnterEvent = webEventHub->GetOnFullScreenEnterEvent();
4241 CHECK_NULL_VOID(propOnFullScreenEnterEvent);
4242 propOnFullScreenEnterEvent(param);
4243 return;
4244 #else
4245 if (Container::IsCurrentUseNewPipeline()) {
4246 auto webPattern = delegate->webPattern_.Upgrade();
4247 CHECK_NULL_VOID(webPattern);
4248 webPattern->RequestFullScreen();
4249 webPattern->SetFullScreenExitHandler(param);
4250 auto webEventHub = webPattern->GetWebEventHub();
4251 CHECK_NULL_VOID(webEventHub);
4252 auto propOnFullScreenEnterEvent = webEventHub->GetOnFullScreenEnterEvent();
4253 CHECK_NULL_VOID(propOnFullScreenEnterEvent);
4254 propOnFullScreenEnterEvent(param);
4255 return;
4256 }
4257 auto webCom = delegate->webComponent_.Upgrade();
4258 CHECK_NULL_VOID(webCom);
4259 webCom->OnFullScreenEnter(param.get());
4260 #endif
4261 },
4262 TaskExecutor::TaskType::JS);
4263 }
4264
OnHttpAuthRequest(const std::shared_ptr<BaseEventInfo> & info)4265 bool WebDelegate::OnHttpAuthRequest(const std::shared_ptr<BaseEventInfo>& info)
4266 {
4267 auto context = context_.Upgrade();
4268 CHECK_NULL_RETURN(context, false);
4269 bool result = false;
4270 auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
4271 jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), info, &result]() {
4272 auto delegate = weak.Upgrade();
4273 CHECK_NULL_VOID(delegate);
4274 #ifdef NG_BUILD
4275 auto webPattern = delegate->webPattern_.Upgrade();
4276 CHECK_NULL_VOID(webPattern);
4277 auto webEventHub = webPattern->GetWebEventHub();
4278 CHECK_NULL_VOID(webEventHub);
4279 auto propOnHttpAuthRequestEvent = webEventHub->GetOnHttpAuthRequestEvent();
4280 CHECK_NULL_VOID(propOnHttpAuthRequestEvent);
4281 result = propOnHttpAuthRequestEvent(info);
4282 return;
4283 #else
4284 if (Container::IsCurrentUseNewPipeline()) {
4285 auto webPattern = delegate->webPattern_.Upgrade();
4286 CHECK_NULL_VOID(webPattern);
4287 auto webEventHub = webPattern->GetWebEventHub();
4288 CHECK_NULL_VOID(webEventHub);
4289 auto propOnHttpAuthRequestEvent = webEventHub->GetOnHttpAuthRequestEvent();
4290 CHECK_NULL_VOID(propOnHttpAuthRequestEvent);
4291 result = propOnHttpAuthRequestEvent(info);
4292 return;
4293 }
4294 auto webCom = delegate->webComponent_.Upgrade();
4295 CHECK_NULL_VOID(webCom);
4296 result = webCom->OnHttpAuthRequest(info.get());
4297 #endif
4298 });
4299 return result;
4300 }
4301
OnSslErrorRequest(const std::shared_ptr<BaseEventInfo> & info)4302 bool WebDelegate::OnSslErrorRequest(const std::shared_ptr<BaseEventInfo>& info)
4303 {
4304 auto context = context_.Upgrade();
4305 CHECK_NULL_RETURN(context, false);
4306 bool result = false;
4307 auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
4308 jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), info, &result]() {
4309 auto delegate = weak.Upgrade();
4310 CHECK_NULL_VOID(delegate);
4311 #ifdef NG_BUILD
4312 auto webPattern = delegate->webPattern_.Upgrade();
4313 CHECK_NULL_VOID(webPattern);
4314 auto webEventHub = webPattern->GetWebEventHub();
4315 CHECK_NULL_VOID(webEventHub);
4316 auto propOnSslErrorEvent = webEventHub->GetOnSslErrorRequestEvent();
4317 CHECK_NULL_VOID(propOnSslErrorEvent);
4318 result = propOnSslErrorEvent(info);
4319 return;
4320 #else
4321 if (Container::IsCurrentUseNewPipeline()) {
4322 auto webPattern = delegate->webPattern_.Upgrade();
4323 CHECK_NULL_VOID(webPattern);
4324 auto webEventHub = webPattern->GetWebEventHub();
4325 CHECK_NULL_VOID(webEventHub);
4326 auto propOnSslErrorEvent = webEventHub->GetOnSslErrorRequestEvent();
4327 CHECK_NULL_VOID(propOnSslErrorEvent);
4328 result = propOnSslErrorEvent(info);
4329 return;
4330 }
4331 auto webCom = delegate->webComponent_.Upgrade();
4332 CHECK_NULL_VOID(webCom);
4333 result = webCom->OnSslErrorRequest(info.get());
4334 #endif
4335 });
4336 return result;
4337 }
4338
OnSslSelectCertRequest(const std::shared_ptr<BaseEventInfo> & info)4339 bool WebDelegate::OnSslSelectCertRequest(const std::shared_ptr<BaseEventInfo>& info)
4340 {
4341 auto context = context_.Upgrade();
4342 CHECK_NULL_RETURN(context, false);
4343 bool result = false;
4344 auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
4345 jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), info, &result]() {
4346 auto delegate = weak.Upgrade();
4347 CHECK_NULL_VOID(delegate);
4348 #ifdef NG_BUILD
4349 auto webPattern = delegate->webPattern_.Upgrade();
4350 CHECK_NULL_VOID(webPattern);
4351 auto webEventHub = webPattern->GetWebEventHub();
4352 CHECK_NULL_VOID(webEventHub);
4353 auto propOnSslSelectCertRequestEvent = webEventHub->GetOnSslSelectCertRequestEvent();
4354 CHECK_NULL_VOID(propOnSslSelectCertRequestEvent);
4355 result = propOnSslSelectCertRequestEvent(info);
4356 return;
4357 #else
4358 if (Container::IsCurrentUseNewPipeline()) {
4359 auto webPattern = delegate->webPattern_.Upgrade();
4360 CHECK_NULL_VOID(webPattern);
4361 auto webEventHub = webPattern->GetWebEventHub();
4362 CHECK_NULL_VOID(webEventHub);
4363 auto propOnSslSelectCertRequestEvent = webEventHub->GetOnSslSelectCertRequestEvent();
4364 CHECK_NULL_VOID(propOnSslSelectCertRequestEvent);
4365 result = propOnSslSelectCertRequestEvent(info);
4366 return;
4367 }
4368 auto webCom = delegate->webComponent_.Upgrade();
4369 CHECK_NULL_VOID(webCom);
4370 result = webCom->OnSslSelectCertRequest(info.get());
4371 #endif
4372 });
4373 return result;
4374 }
4375
OnDownloadStart(const std::string & url,const std::string & userAgent,const std::string & contentDisposition,const std::string & mimetype,long contentLength)4376 void WebDelegate::OnDownloadStart(const std::string& url, const std::string& userAgent,
4377 const std::string& contentDisposition, const std::string& mimetype, long contentLength)
4378 {
4379 auto context = context_.Upgrade();
4380 CHECK_NULL_VOID(context);
4381 context->GetTaskExecutor()->PostTask(
4382 [weak = WeakClaim(this), url, userAgent, contentDisposition, mimetype, contentLength]() {
4383 auto delegate = weak.Upgrade();
4384 CHECK_NULL_VOID(delegate);
4385 auto onDownloadStartV2 = delegate->onDownloadStartV2_;
4386 if (onDownloadStartV2) {
4387 onDownloadStartV2(
4388 std::make_shared<DownloadStartEvent>(url, userAgent, contentDisposition, mimetype, contentLength));
4389 }
4390 },
4391 TaskExecutor::TaskType::JS);
4392 }
4393
OnAccessibilityEvent(int64_t accessibilityId,AccessibilityEventType eventType)4394 void WebDelegate::OnAccessibilityEvent(int64_t accessibilityId, AccessibilityEventType eventType)
4395 {
4396 auto context = context_.Upgrade();
4397 CHECK_NULL_VOID(context);
4398 AccessibilityEvent event;
4399 if (accessibilityId <= 0) {
4400 auto webPattern = webPattern_.Upgrade();
4401 CHECK_NULL_VOID(webPattern);
4402 auto webNode = webPattern->GetHost();
4403 CHECK_NULL_VOID(webNode);
4404 accessibilityId = webNode->GetAccessibilityId();
4405 }
4406 event.nodeId = accessibilityId;
4407 event.type = eventType;
4408 context->SendEventToAccessibility(event);
4409 }
4410
OnErrorReceive(std::shared_ptr<OHOS::NWeb::NWebUrlResourceRequest> request,std::shared_ptr<OHOS::NWeb::NWebUrlResourceError> error)4411 void WebDelegate::OnErrorReceive(std::shared_ptr<OHOS::NWeb::NWebUrlResourceRequest> request,
4412 std::shared_ptr<OHOS::NWeb::NWebUrlResourceError> error)
4413 {
4414 auto context = context_.Upgrade();
4415 CHECK_NULL_VOID(context);
4416 context->GetTaskExecutor()->PostTask(
4417 [weak = WeakClaim(this), request, error]() {
4418 auto delegate = weak.Upgrade();
4419 CHECK_NULL_VOID(delegate);
4420 auto onPageError = delegate->onPageError_;
4421 if (onPageError) {
4422 std::string url = request->Url();
4423 int errorCode = error->ErrorCode();
4424 std::string description = error->ErrorInfo();
4425 std::string paramUrl = std::string(R"(")").append(url).append(std::string(R"(")")).append(",");
4426 std::string paramErrorCode =
4427 std::string(R"(")")
4428 .append(NTC_PARAM_ERROR_CODE)
4429 .append(std::string(R"(")"))
4430 .append(":")
4431 .append(std::to_string(errorCode))
4432 .append(",");
4433 std::string paramDesc =
4434 std::string(R"(")")
4435 .append(NTC_PARAM_DESCRIPTION)
4436 .append(std::string(R"(")"))
4437 .append(":")
4438 .append(std::string(R"(")").append(description).append(std::string(R"(")")));
4439 std::string errorParam =
4440 std::string(R"("error",{"url":)").append((paramUrl + paramErrorCode + paramDesc).append("},null"));
4441 onPageError(errorParam);
4442 }
4443 auto onErrorReceiveV2 = delegate->onErrorReceiveV2_;
4444 if (onErrorReceiveV2) {
4445 onErrorReceiveV2(std::make_shared<ReceivedErrorEvent>(
4446 AceType::MakeRefPtr<WebRequest>(request->RequestHeaders(), request->Method(), request->Url(),
4447 request->FromGesture(), request->IsAboutMainFrame(), request->IsRequestRedirect()),
4448 AceType::MakeRefPtr<WebError>(error->ErrorInfo(), error->ErrorCode())));
4449 }
4450 },
4451 TaskExecutor::TaskType::JS);
4452 }
4453
OnHttpErrorReceive(std::shared_ptr<OHOS::NWeb::NWebUrlResourceRequest> request,std::shared_ptr<OHOS::NWeb::NWebUrlResourceResponse> response)4454 void WebDelegate::OnHttpErrorReceive(std::shared_ptr<OHOS::NWeb::NWebUrlResourceRequest> request,
4455 std::shared_ptr<OHOS::NWeb::NWebUrlResourceResponse> response)
4456 {
4457 auto context = context_.Upgrade();
4458 CHECK_NULL_VOID(context);
4459 context->GetTaskExecutor()->PostTask(
4460 [weak = WeakClaim(this), request, response]() {
4461 auto delegate = weak.Upgrade();
4462 CHECK_NULL_VOID(delegate);
4463 auto onHttpErrorReceiveV2 = delegate->onHttpErrorReceiveV2_;
4464 if (onHttpErrorReceiveV2) {
4465 onHttpErrorReceiveV2(std::make_shared<ReceivedHttpErrorEvent>(
4466 AceType::MakeRefPtr<WebRequest>(request->RequestHeaders(), request->Method(), request->Url(),
4467 request->FromGesture(), request->IsAboutMainFrame(), request->IsRequestRedirect()),
4468 AceType::MakeRefPtr<WebResponse>(response->ResponseHeaders(), response->ResponseData(),
4469 response->ResponseEncoding(), response->ResponseMimeType(), response->ResponseStatus(),
4470 response->ResponseStatusCode())));
4471 }
4472 },
4473 TaskExecutor::TaskType::JS);
4474 }
4475
IsEmptyOnInterceptRequest()4476 bool WebDelegate::IsEmptyOnInterceptRequest()
4477 {
4478 #ifdef NG_BUILD
4479 auto webPattern = webPattern_.Upgrade();
4480 CHECK_NULL_RETURN(webPattern, false);
4481 auto webEventHub = webPattern->GetWebEventHub();
4482 CHECK_NULL_RETURN(webEventHub, false);
4483 return webEventHub->GetOnInterceptRequestEvent() == nullptr;
4484 #else
4485 if (Container::IsCurrentUseNewPipeline()) {
4486 auto webPattern = webPattern_.Upgrade();
4487 CHECK_NULL_RETURN(webPattern, false);
4488 auto webEventHub = webPattern->GetWebEventHub();
4489 CHECK_NULL_RETURN(webEventHub, false);
4490 return webEventHub->GetOnInterceptRequestEvent() == nullptr;
4491 }
4492 auto webCom = webComponent_.Upgrade();
4493 CHECK_NULL_RETURN(webCom, true);
4494 return webCom->IsEmptyOnInterceptRequest();
4495 #endif
4496 }
4497
OnInterceptRequest(const std::shared_ptr<BaseEventInfo> & info)4498 RefPtr<WebResponse> WebDelegate::OnInterceptRequest(const std::shared_ptr<BaseEventInfo>& info)
4499 {
4500 auto context = context_.Upgrade();
4501 CHECK_NULL_RETURN(context, nullptr);
4502 RefPtr<WebResponse> result = nullptr;
4503 auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
4504 jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), info, &result]() {
4505 auto delegate = weak.Upgrade();
4506 CHECK_NULL_VOID(delegate);
4507 if (Container::IsCurrentUseNewPipeline()) {
4508 auto webPattern = delegate->webPattern_.Upgrade();
4509 CHECK_NULL_VOID(webPattern);
4510 auto webEventHub = webPattern->GetWebEventHub();
4511 CHECK_NULL_VOID(webEventHub);
4512 auto propOnInterceptRequestEvent = webEventHub->GetOnInterceptRequestEvent();
4513 CHECK_NULL_VOID(propOnInterceptRequestEvent);
4514 result = propOnInterceptRequestEvent(info);
4515 }
4516 auto webCom = delegate->webComponent_.Upgrade();
4517 CHECK_NULL_VOID(webCom);
4518 result = webCom->OnInterceptRequest(info.get());
4519 });
4520 return result;
4521 }
4522
OnRequestFocus()4523 void WebDelegate::OnRequestFocus()
4524 {
4525 if (onRequestFocusV2_) {
4526 onRequestFocusV2_(std::make_shared<LoadWebRequestFocusEvent>(""));
4527 }
4528 }
4529
OnRenderExited(OHOS::NWeb::RenderExitReason reason)4530 void WebDelegate::OnRenderExited(OHOS::NWeb::RenderExitReason reason)
4531 {
4532 auto context = context_.Upgrade();
4533 CHECK_NULL_VOID(context);
4534 context->GetTaskExecutor()->PostTask(
4535 [weak = WeakClaim(this), reason]() {
4536 auto delegate = weak.Upgrade();
4537 CHECK_NULL_VOID(delegate);
4538 auto onRenderExitedV2 = delegate->onRenderExitedV2_;
4539 if (onRenderExitedV2) {
4540 onRenderExitedV2(std::make_shared<RenderExitedEvent>(static_cast<int32_t>(reason)));
4541 }
4542 },
4543 TaskExecutor::TaskType::JS);
4544 }
4545
OnRefreshAccessedHistory(const std::string & url,bool isRefreshed)4546 void WebDelegate::OnRefreshAccessedHistory(const std::string& url, bool isRefreshed)
4547 {
4548 auto context = context_.Upgrade();
4549 CHECK_NULL_VOID(context);
4550 context->GetTaskExecutor()->PostTask(
4551 [weak = WeakClaim(this), url, isRefreshed]() {
4552 auto delegate = weak.Upgrade();
4553 CHECK_NULL_VOID(delegate);
4554 auto onRefreshAccessedHistoryV2 = delegate->onRefreshAccessedHistoryV2_;
4555 if (onRefreshAccessedHistoryV2) {
4556 onRefreshAccessedHistoryV2(std::make_shared<RefreshAccessedHistoryEvent>(url, isRefreshed));
4557 }
4558 },
4559 TaskExecutor::TaskType::JS);
4560 }
4561
OnPageError(const std::string & param)4562 void WebDelegate::OnPageError(const std::string& param)
4563 {
4564 if (onPageError_) {
4565 int32_t errorCode = GetIntParam(param, NTC_PARAM_ERROR_CODE);
4566 std::string url = GetUrlStringParam(param, NTC_PARAM_URL);
4567 std::string description = GetStringParam(param, NTC_PARAM_DESCRIPTION);
4568
4569 std::string paramUrl = std::string(R"(")").append(url).append(std::string(R"(")")).append(",");
4570
4571 std::string paramErrorCode = std::string(R"(")")
4572 .append(NTC_PARAM_ERROR_CODE)
4573 .append(std::string(R"(")"))
4574 .append(":")
4575 .append(std::to_string(errorCode))
4576 .append(",");
4577
4578 std::string paramDesc = std::string(R"(")")
4579 .append(NTC_PARAM_DESCRIPTION)
4580 .append(std::string(R"(")"))
4581 .append(":")
4582 .append(std::string(R"(")").append(description).append(std::string(R"(")")));
4583 std::string errorParam =
4584 std::string(R"("error",{"url":)").append((paramUrl + paramErrorCode + paramDesc).append("},null"));
4585 onPageError_(errorParam);
4586 }
4587 }
4588
OnMessage(const std::string & param)4589 void WebDelegate::OnMessage(const std::string& param)
4590 {
4591 std::string removeQuotes;
4592 removeQuotes = param;
4593 removeQuotes.erase(std::remove(removeQuotes.begin(), removeQuotes.end(), '\"'), removeQuotes.end());
4594 if (onMessage_) {
4595 std::string paramMessage = std::string(R"(")").append(removeQuotes).append(std::string(R"(")"));
4596 std::string messageParam = std::string(R"("message",{"message":)").append(paramMessage.append("},null"));
4597 onMessage_(messageParam);
4598 }
4599 }
4600
OnRouterPush(const std::string & param)4601 void WebDelegate::OnRouterPush(const std::string& param)
4602 {
4603 OHOS::Ace::Framework::DelegateClient::GetInstance().RouterPush(param);
4604 }
4605
OnFileSelectorShow(const std::shared_ptr<BaseEventInfo> & info)4606 bool WebDelegate::OnFileSelectorShow(const std::shared_ptr<BaseEventInfo>& info)
4607 {
4608 auto context = context_.Upgrade();
4609 CHECK_NULL_RETURN(context, false);
4610 bool result = false;
4611 auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
4612 jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), info, &result]() {
4613 auto delegate = weak.Upgrade();
4614 CHECK_NULL_VOID(delegate);
4615 if (Container::IsCurrentUseNewPipeline()) {
4616 auto webPattern = delegate->webPattern_.Upgrade();
4617 CHECK_NULL_VOID(webPattern);
4618 auto webEventHub = webPattern->GetWebEventHub();
4619 CHECK_NULL_VOID(webEventHub);
4620 auto propOnFileSelectorShowEvent = webEventHub->GetOnFileSelectorShowEvent();
4621 CHECK_NULL_VOID(propOnFileSelectorShowEvent);
4622 result = propOnFileSelectorShowEvent(info);
4623 }
4624 auto webCom = delegate->webComponent_.Upgrade();
4625 CHECK_NULL_VOID(webCom);
4626 result = webCom->OnFileSelectorShow(info.get());
4627 });
4628 return result;
4629 }
4630
OnContextMenuShow(const std::shared_ptr<BaseEventInfo> & info)4631 bool WebDelegate::OnContextMenuShow(const std::shared_ptr<BaseEventInfo>& info)
4632 {
4633 auto context = context_.Upgrade();
4634 CHECK_NULL_RETURN(context, false);
4635 bool result = false;
4636 auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
4637 jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), info, &result]() {
4638 auto delegate = weak.Upgrade();
4639 CHECK_NULL_VOID(delegate);
4640 #ifdef NG_BUILD
4641 auto webPattern = delegate->webPattern_.Upgrade();
4642 CHECK_NULL_VOID(webPattern);
4643 auto webEventHub = webPattern->GetWebEventHub();
4644 CHECK_NULL_VOID(webEventHub);
4645 auto propOnContextMenuShowEvent = webEventHub->GetOnContextMenuShowEvent();
4646 CHECK_NULL_VOID(propOnContextMenuShowEvent);
4647 result = propOnContextMenuShowEvent(info);
4648 return;
4649 #else
4650 if (Container::IsCurrentUseNewPipeline()) {
4651 auto webPattern = delegate->webPattern_.Upgrade();
4652 CHECK_NULL_VOID(webPattern);
4653 auto webEventHub = webPattern->GetWebEventHub();
4654 CHECK_NULL_VOID(webEventHub);
4655 auto propOnContextMenuShowEvent = webEventHub->GetOnContextMenuShowEvent();
4656 CHECK_NULL_VOID(propOnContextMenuShowEvent);
4657 result = propOnContextMenuShowEvent(info);
4658 return;
4659 }
4660 auto webCom = delegate->webComponent_.Upgrade();
4661 CHECK_NULL_VOID(webCom);
4662 result = webCom->OnContextMenuShow(info.get());
4663 #endif
4664 });
4665 return result;
4666 }
4667
OnContextMenuHide(const std::string & info)4668 void WebDelegate::OnContextMenuHide(const std::string& info)
4669 {
4670 auto context = context_.Upgrade();
4671 CHECK_NULL_VOID(context);
4672 auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
4673 jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), info]() {
4674 auto delegate = weak.Upgrade();
4675 CHECK_NULL_VOID(delegate);
4676 if (Container::IsCurrentUseNewPipeline()) {
4677 auto webPattern = delegate->webPattern_.Upgrade();
4678 CHECK_NULL_VOID(webPattern);
4679 auto webEventHub = webPattern->GetWebEventHub();
4680 CHECK_NULL_VOID(webEventHub);
4681 auto propOnContextMenuHideEvent = webEventHub->GetOnContextMenuHideEvent();
4682 CHECK_NULL_VOID(propOnContextMenuHideEvent);
4683 propOnContextMenuHideEvent(std::make_shared<ContextMenuHideEvent>(info));
4684 return;
4685 } else {
4686 TAG_LOGW(AceLogTag::ACE_WEB, "current is not new pipeline");
4687 }
4688 });
4689 return;
4690 }
4691
OnHandleInterceptUrlLoading(const std::string & data)4692 bool WebDelegate::OnHandleInterceptUrlLoading(const std::string& data)
4693 {
4694 auto context = context_.Upgrade();
4695 CHECK_NULL_RETURN(context, false);
4696 bool result = false;
4697 auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
4698 jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), data, &result]() {
4699 auto delegate = weak.Upgrade();
4700 CHECK_NULL_VOID(delegate);
4701 auto param = std::make_shared<UrlLoadInterceptEvent>(data);
4702 if (Container::IsCurrentUseNewPipeline()) {
4703 auto webPattern = delegate->webPattern_.Upgrade();
4704 CHECK_NULL_VOID(webPattern);
4705 auto webEventHub = webPattern->GetWebEventHub();
4706 CHECK_NULL_VOID(webEventHub);
4707 auto propOnUrlLoadInterceptEvent = webEventHub->GetOnUrlLoadInterceptEvent();
4708 CHECK_NULL_VOID(propOnUrlLoadInterceptEvent);
4709 result = propOnUrlLoadInterceptEvent(param);
4710 }
4711 auto webCom = delegate->webComponent_.Upgrade();
4712 CHECK_NULL_VOID(webCom);
4713 result = webCom->OnUrlLoadIntercept(param.get());
4714 });
4715 return result;
4716 }
4717
OnHandleInterceptLoading(std::shared_ptr<OHOS::NWeb::NWebUrlResourceRequest> request)4718 bool WebDelegate::OnHandleInterceptLoading(std::shared_ptr<OHOS::NWeb::NWebUrlResourceRequest> request)
4719 {
4720 auto context = context_.Upgrade();
4721 CHECK_NULL_RETURN(context, false);
4722 bool result = false;
4723 auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
4724 jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), request, &result]() {
4725 auto delegate = weak.Upgrade();
4726 CHECK_NULL_VOID(delegate);
4727 auto webRequest = AceType::MakeRefPtr<WebRequest>(request->RequestHeaders(), request->Method(), request->Url(),
4728 request->FromGesture(), request->IsAboutMainFrame(), request->IsRequestRedirect());
4729 auto param = std::make_shared<LoadInterceptEvent>(webRequest);
4730 if (Container::IsCurrentUseNewPipeline()) {
4731 auto webPattern = delegate->webPattern_.Upgrade();
4732 CHECK_NULL_VOID(webPattern);
4733 auto webEventHub = webPattern->GetWebEventHub();
4734 CHECK_NULL_VOID(webEventHub);
4735 auto propOnLoadInterceptEvent = webEventHub->GetOnLoadInterceptEvent();
4736 CHECK_NULL_VOID(propOnLoadInterceptEvent);
4737 result = propOnLoadInterceptEvent(param);
4738 }
4739 auto webCom = delegate->webComponent_.Upgrade();
4740 CHECK_NULL_VOID(webCom);
4741 result = webCom->OnLoadIntercept(param.get());
4742 });
4743 return result;
4744 }
4745
OnResourceLoad(const std::string & url)4746 void WebDelegate::OnResourceLoad(const std::string& url)
4747 {
4748 if (onResourceLoadV2_) {
4749 onResourceLoadV2_(std::make_shared<ResourceLoadEvent>(url));
4750 }
4751 }
4752
OnScaleChange(float oldScaleFactor,float newScaleFactor)4753 void WebDelegate::OnScaleChange(float oldScaleFactor, float newScaleFactor)
4754 {
4755 auto context = context_.Upgrade();
4756 CHECK_NULL_VOID(context);
4757 context->GetTaskExecutor()->PostTask(
4758 [weak = WeakClaim(this), oldScaleFactor, newScaleFactor]() {
4759 auto delegate = weak.Upgrade();
4760 CHECK_NULL_VOID(delegate);
4761 auto onScaleChangeV2 = delegate->onScaleChangeV2_;
4762 if (onScaleChangeV2) {
4763 onScaleChangeV2(std::make_shared<ScaleChangeEvent>(oldScaleFactor, newScaleFactor));
4764 }
4765 },
4766 TaskExecutor::TaskType::JS);
4767 }
4768
OnScroll(double xOffset,double yOffset)4769 void WebDelegate::OnScroll(double xOffset, double yOffset)
4770 {
4771 auto context = context_.Upgrade();
4772 CHECK_NULL_VOID(context);
4773 context->GetTaskExecutor()->PostTask(
4774 [weak = WeakClaim(this), xOffset, yOffset]() {
4775 auto delegate = weak.Upgrade();
4776 CHECK_NULL_VOID(delegate);
4777 auto onScrollV2 = delegate->onScrollV2_;
4778 if (onScrollV2) {
4779 onScrollV2(std::make_shared<WebOnScrollEvent>(xOffset, yOffset));
4780 }
4781 },
4782 TaskExecutor::TaskType::JS);
4783 }
4784
OnSearchResultReceive(int activeMatchOrdinal,int numberOfMatches,bool isDoneCounting)4785 void WebDelegate::OnSearchResultReceive(int activeMatchOrdinal, int numberOfMatches, bool isDoneCounting)
4786 {
4787 auto context = context_.Upgrade();
4788 CHECK_NULL_VOID(context);
4789 context->GetTaskExecutor()->PostTask(
4790 [weak = WeakClaim(this), activeMatchOrdinal, numberOfMatches, isDoneCounting]() {
4791 auto delegate = weak.Upgrade();
4792 CHECK_NULL_VOID(delegate);
4793 auto onSearchResultReceiveV2 = delegate->onSearchResultReceiveV2_;
4794 if (onSearchResultReceiveV2) {
4795 onSearchResultReceiveV2(
4796 std::make_shared<SearchResultReceiveEvent>(activeMatchOrdinal, numberOfMatches, isDoneCounting));
4797 }
4798 },
4799 TaskExecutor::TaskType::JS);
4800 }
4801
OnDragAndDropData(const void * data,size_t len,int width,int height)4802 bool WebDelegate::OnDragAndDropData(const void* data, size_t len, int width, int height)
4803 {
4804 pixelMap_ = PixelMap::ConvertSkImageToPixmap(static_cast<const uint32_t*>(data), len, width, height);
4805 if (pixelMap_ == nullptr) {
4806 return false;
4807 }
4808 isRefreshPixelMap_ = true;
4809
4810 auto webPattern = webPattern_.Upgrade();
4811 if (!webPattern) {
4812 return false;
4813 }
4814 return webPattern->NotifyStartDragTask();
4815 }
4816
OnDragAndDropDataUdmf(std::shared_ptr<OHOS::NWeb::NWebDragData> dragData)4817 bool WebDelegate::OnDragAndDropDataUdmf(std::shared_ptr<OHOS::NWeb::NWebDragData> dragData)
4818 {
4819 const void* data = nullptr;
4820 size_t len = 0;
4821 int width = 0;
4822 int height = 0;
4823 dragData->GetPixelMapSetting(&data, len, width, height);
4824 pixelMap_ = PixelMap::ConvertSkImageToPixmap(static_cast<const uint32_t*>(data), len, width, height);
4825 if (pixelMap_ == nullptr) {
4826 return false;
4827 }
4828 isRefreshPixelMap_ = true;
4829
4830 dragData_ = dragData;
4831 auto webPattern = webPattern_.Upgrade();
4832 if (!webPattern) {
4833 return false;
4834 }
4835 return webPattern->NotifyStartDragTask();
4836 }
4837
IsImageDrag()4838 bool WebDelegate::IsImageDrag()
4839 {
4840 if (dragData_) {
4841 return dragData_->IsSingleImageContent();
4842 }
4843 return false;
4844 }
4845
GetOrCreateDragData()4846 std::shared_ptr<OHOS::NWeb::NWebDragData> WebDelegate::GetOrCreateDragData()
4847 {
4848 if (dragData_) {
4849 return dragData_;
4850 }
4851
4852 if (nweb_) {
4853 dragData_ = nweb_->GetOrCreateDragData();
4854 return dragData_;
4855 }
4856 return nullptr;
4857 }
4858
OnWindowNew(const std::string & targetUrl,bool isAlert,bool isUserTrigger,const std::shared_ptr<OHOS::NWeb::NWebControllerHandler> & handler)4859 void WebDelegate::OnWindowNew(const std::string& targetUrl, bool isAlert, bool isUserTrigger,
4860 const std::shared_ptr<OHOS::NWeb::NWebControllerHandler>& handler)
4861 {
4862 auto context = context_.Upgrade();
4863 CHECK_NULL_VOID(context);
4864 context->GetTaskExecutor()->PostSyncTask(
4865 [weak = WeakClaim(this), targetUrl, isAlert, isUserTrigger, handler]() {
4866 auto delegate = weak.Upgrade();
4867 CHECK_NULL_VOID(delegate);
4868 int32_t parentNWebId = (delegate->nweb_ ? delegate->nweb_->GetWebId() : -1);
4869 auto param = std::make_shared<WebWindowNewEvent>(
4870 targetUrl, isAlert, isUserTrigger, AceType::MakeRefPtr<WebWindowNewHandlerOhos>(handler, parentNWebId));
4871 #ifdef NG_BUILD
4872 auto webPattern = delegate->webPattern_.Upgrade();
4873 CHECK_NULL_VOID(webPattern);
4874 auto webEventHub = webPattern->GetWebEventHub();
4875 CHECK_NULL_VOID(webEventHub);
4876 auto propOnWindowNewEvent = webEventHub->GetOnWindowNewEvent();
4877 CHECK_NULL_VOID(propOnWindowNewEvent);
4878 propOnWindowNewEvent(param);
4879 return;
4880 #else
4881 if (Container::IsCurrentUseNewPipeline()) {
4882 auto webPattern = delegate->webPattern_.Upgrade();
4883 CHECK_NULL_VOID(webPattern);
4884 auto webEventHub = webPattern->GetWebEventHub();
4885 CHECK_NULL_VOID(webEventHub);
4886 auto propOnWindowNewEvent = webEventHub->GetOnWindowNewEvent();
4887 CHECK_NULL_VOID(propOnWindowNewEvent);
4888 propOnWindowNewEvent(param);
4889 return;
4890 }
4891 auto webCom = delegate->webComponent_.Upgrade();
4892 CHECK_NULL_VOID(webCom);
4893 webCom->OnWindowNewEvent(param);
4894 #endif
4895 },
4896 TaskExecutor::TaskType::JS);
4897 }
4898
OnWindowExit()4899 void WebDelegate::OnWindowExit()
4900 {
4901 auto context = context_.Upgrade();
4902 CHECK_NULL_VOID(context);
4903 context->GetTaskExecutor()->PostTask(
4904 [weak = WeakClaim(this)]() {
4905 auto delegate = weak.Upgrade();
4906 CHECK_NULL_VOID(delegate);
4907 auto onWindowExitV2 = delegate->onWindowExitV2_;
4908 if (onWindowExitV2) {
4909 onWindowExitV2(std::make_shared<WebWindowExitEvent>());
4910 }
4911 },
4912 TaskExecutor::TaskType::JS);
4913 }
4914
OnPageVisible(const std::string & url)4915 void WebDelegate::OnPageVisible(const std::string& url)
4916 {
4917 if (onPageVisibleV2_) {
4918 onPageVisibleV2_(std::make_shared<PageVisibleEvent>(url));
4919 }
4920 }
4921
OnFirstContentfulPaint(int64_t navigationStartTick,int64_t firstContentfulPaintMs)4922 void WebDelegate::OnFirstContentfulPaint(int64_t navigationStartTick, int64_t firstContentfulPaintMs)
4923 {
4924 if (onFirstContentfulPaintV2_) {
4925 onFirstContentfulPaintV2_(
4926 std::make_shared<FirstContentfulPaintEvent>(navigationStartTick, firstContentfulPaintMs));
4927 }
4928 }
4929
OnSafeBrowsingCheckResult(int threat_type)4930 void WebDelegate::OnSafeBrowsingCheckResult(int threat_type)
4931 {
4932 if (onSafeBrowsingCheckResultV2_) {
4933 onSafeBrowsingCheckResultV2_(
4934 std::make_shared<SafeBrowsingCheckResultEvent>(threat_type));
4935 }
4936 }
4937
OnDataResubmitted(std::shared_ptr<OHOS::NWeb::NWebDataResubmissionCallback> handler)4938 void WebDelegate::OnDataResubmitted(std::shared_ptr<OHOS::NWeb::NWebDataResubmissionCallback> handler)
4939 {
4940 auto param = std::make_shared<DataResubmittedEvent>(AceType::MakeRefPtr<DataResubmittedOhos>(handler));
4941 if (Container::IsCurrentUseNewPipeline()) {
4942 auto webPattern = webPattern_.Upgrade();
4943 CHECK_NULL_VOID(webPattern);
4944 auto webEventHub = webPattern->GetWebEventHub();
4945 CHECK_NULL_VOID(webEventHub);
4946 auto propOnDataResubmittedEvent = webEventHub->GetOnDataResubmittedEvent();
4947 CHECK_NULL_VOID(propOnDataResubmittedEvent);
4948 propOnDataResubmittedEvent(param);
4949 return;
4950 }
4951 }
4952
OnNavigationEntryCommitted(std::shared_ptr<OHOS::NWeb::NWebLoadCommittedDetails> details)4953 void WebDelegate::OnNavigationEntryCommitted(std::shared_ptr<OHOS::NWeb::NWebLoadCommittedDetails> details)
4954 {
4955 if (onNavigationEntryCommittedV2_) {
4956 NavigationType type = static_cast<NavigationType>(details->GetNavigationType());
4957 onNavigationEntryCommittedV2_(std::make_shared<NavigationEntryCommittedEvent>(details->GetURL(),
4958 type, details->IsMainFrame(), details->IsSameDocument(),
4959 details->DidReplaceEntry()));
4960 }
4961 }
4962
OnFaviconReceived(const void * data,size_t width,size_t height,OHOS::NWeb::ImageColorType colorType,OHOS::NWeb::ImageAlphaType alphaType)4963 void WebDelegate::OnFaviconReceived(const void* data, size_t width, size_t height, OHOS::NWeb::ImageColorType colorType,
4964 OHOS::NWeb::ImageAlphaType alphaType)
4965 {
4966 auto param = std::make_shared<FaviconReceivedEvent>(
4967 AceType::MakeRefPtr<FaviconReceivedOhos>(data, width, height, colorType, alphaType));
4968 if (Container::IsCurrentUseNewPipeline()) {
4969 auto webPattern = webPattern_.Upgrade();
4970 CHECK_NULL_VOID(webPattern);
4971 auto webEventHub = webPattern->GetWebEventHub();
4972 CHECK_NULL_VOID(webEventHub);
4973 auto propOnFaviconReceivedEvent = webEventHub->GetOnFaviconReceivedEvent();
4974 CHECK_NULL_VOID(propOnFaviconReceivedEvent);
4975 propOnFaviconReceivedEvent(param);
4976 return;
4977 }
4978 }
4979
OnTouchIconUrl(const std::string & iconUrl,bool precomposed)4980 void WebDelegate::OnTouchIconUrl(const std::string& iconUrl, bool precomposed)
4981 {
4982 if (onTouchIconUrlV2_) {
4983 onTouchIconUrlV2_(std::make_shared<TouchIconUrlEvent>(iconUrl, precomposed));
4984 }
4985 }
4986
OnAudioStateChanged(bool audible)4987 void WebDelegate::OnAudioStateChanged(bool audible)
4988 {
4989 if (onAudioStateChangedV2_) {
4990 onAudioStateChangedV2_(std::make_shared<AudioStateChangedEvent>(audible));
4991 }
4992 }
4993
OnGetTouchHandleHotZone(OHOS::NWeb::TouchHandleHotZone & hotZone)4994 void WebDelegate::OnGetTouchHandleHotZone(OHOS::NWeb::TouchHandleHotZone& hotZone)
4995 {
4996 auto pipeline = PipelineContext::GetCurrentContext();
4997 CHECK_NULL_VOID(pipeline);
4998 auto theme = pipeline->GetTheme<TextOverlayTheme>();
4999 CHECK_NULL_VOID(theme);
5000 auto touchHandleSize = theme->GetHandleHotZoneRadius().ConvertToPx();
5001 hotZone.width = touchHandleSize;
5002 hotZone.height = touchHandleSize;
5003 }
5004
GetDragPixelMap()5005 RefPtr<PixelMap> WebDelegate::GetDragPixelMap()
5006 {
5007 return pixelMap_;
5008 }
5009
5010 #ifdef OHOS_STANDARD_SYSTEM
HandleTouchDown(const int32_t & id,const double & x,const double & y,bool from_overlay)5011 void WebDelegate::HandleTouchDown(const int32_t& id, const double& x, const double& y, bool from_overlay)
5012 {
5013 ACE_DCHECK(nweb_ != nullptr);
5014 if (nweb_) {
5015 ResSchedReport::GetInstance().ResSchedDataReport("web_gesture");
5016 nweb_->OnTouchPress(id, x, y, from_overlay);
5017 }
5018 }
5019
HandleTouchUp(const int32_t & id,const double & x,const double & y,bool from_overlay)5020 void WebDelegate::HandleTouchUp(const int32_t& id, const double& x, const double& y, bool from_overlay)
5021 {
5022 ACE_DCHECK(nweb_ != nullptr);
5023 if (nweb_) {
5024 ResSchedReport::GetInstance().ResSchedDataReport("web_gesture");
5025 nweb_->OnTouchRelease(id, x, y, from_overlay);
5026 }
5027 }
5028
HandleTouchMove(const int32_t & id,const double & x,const double & y,bool from_overlay)5029 void WebDelegate::HandleTouchMove(const int32_t& id, const double& x, const double& y, bool from_overlay)
5030 {
5031 ACE_DCHECK(nweb_ != nullptr);
5032 if (nweb_) {
5033 nweb_->OnTouchMove(id, x, y, from_overlay);
5034 }
5035 }
5036
HandleTouchMove(const std::list<OHOS::NWeb::TouchPointInfo> & touchPointInfoList,bool from_overlay)5037 void WebDelegate::HandleTouchMove(const std::list<OHOS::NWeb::TouchPointInfo>& touchPointInfoList, bool from_overlay)
5038 {
5039 ACE_DCHECK(nweb_ != nullptr);
5040 if (nweb_) {
5041 nweb_->OnTouchMove(touchPointInfoList, from_overlay);
5042 }
5043 }
5044
HandleTouchCancel()5045 void WebDelegate::HandleTouchCancel()
5046 {
5047 ACE_DCHECK(nweb_ != nullptr);
5048 if (nweb_) {
5049 nweb_->OnTouchCancel();
5050 }
5051 }
5052
HandleAxisEvent(const double & x,const double & y,const double & deltaX,const double & deltaY)5053 void WebDelegate::HandleAxisEvent(const double& x, const double& y, const double& deltaX, const double& deltaY)
5054 {
5055 if (nweb_) {
5056 nweb_->SendMouseWheelEvent(x, y, deltaX, deltaY);
5057 }
5058 }
5059
OnKeyEvent(int32_t keyCode,int32_t keyAction)5060 bool WebDelegate::OnKeyEvent(int32_t keyCode, int32_t keyAction)
5061 {
5062 if (nweb_) {
5063 return nweb_->SendKeyEvent(keyCode, keyAction);
5064 }
5065 return false;
5066 }
5067
OnMouseEvent(int32_t x,int32_t y,const MouseButton button,const MouseAction action,int count)5068 void WebDelegate::OnMouseEvent(int32_t x, int32_t y, const MouseButton button, const MouseAction action, int count)
5069 {
5070 if (nweb_) {
5071 nweb_->SendMouseEvent(x, y, static_cast<int>(button), static_cast<int>(action), count);
5072 }
5073 }
5074
OnFocus()5075 void WebDelegate::OnFocus()
5076 {
5077 ACE_DCHECK(nweb_ != nullptr);
5078 if (nweb_) {
5079 nweb_->OnFocus(OHOS::NWeb::FocusReason::EVENT_REQUEST);
5080 }
5081 }
5082
NeedSoftKeyboard()5083 bool WebDelegate::NeedSoftKeyboard()
5084 {
5085 if (nweb_) {
5086 return nweb_->NeedSoftKeyboard();
5087 }
5088 return false;
5089 }
5090
OnBlur()5091 void WebDelegate::OnBlur()
5092 {
5093 ACE_DCHECK(nweb_ != nullptr);
5094 if (nweb_) {
5095 nweb_->OnBlur(blurReason_);
5096 }
5097 }
5098
RunQuickMenu(std::shared_ptr<OHOS::NWeb::NWebQuickMenuParams> params,std::shared_ptr<OHOS::NWeb::NWebQuickMenuCallback> callback)5099 bool WebDelegate::RunQuickMenu(std::shared_ptr<OHOS::NWeb::NWebQuickMenuParams> params,
5100 std::shared_ptr<OHOS::NWeb::NWebQuickMenuCallback> callback)
5101 {
5102 #ifdef NG_BUILD
5103 auto webPattern = webPattern_.Upgrade();
5104 CHECK_NULL_RETURN(webPattern, false);
5105 return webPattern->RunQuickMenu(params, callback);
5106 #else
5107 if (Container::IsCurrentUseNewPipeline()) {
5108 auto webPattern = webPattern_.Upgrade();
5109 CHECK_NULL_RETURN(webPattern, false);
5110 return webPattern->RunQuickMenu(params, callback);
5111 }
5112 auto renderWeb = renderWeb_.Upgrade();
5113 if (!renderWeb || !params || !callback) {
5114 return false;
5115 }
5116
5117 return renderWeb->RunQuickMenu(params, callback);
5118 #endif
5119 }
5120
OnQuickMenuDismissed()5121 void WebDelegate::OnQuickMenuDismissed()
5122 {
5123 #ifdef NG_BUILD
5124 auto webPattern = webPattern_.Upgrade();
5125 CHECK_NULL_VOID(webPattern);
5126 webPattern->OnQuickMenuDismissed();
5127 return;
5128 #else
5129 if (Container::IsCurrentUseNewPipeline()) {
5130 auto webPattern = webPattern_.Upgrade();
5131 CHECK_NULL_VOID(webPattern);
5132 webPattern->OnQuickMenuDismissed();
5133 return;
5134 }
5135 auto renderWeb = renderWeb_.Upgrade();
5136 CHECK_NULL_VOID(renderWeb);
5137 renderWeb->OnQuickMenuDismissed();
5138 #endif
5139 }
5140
OnTouchSelectionChanged(std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> insertHandle,std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> startSelectionHandle,std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> endSelectionHandle)5141 void WebDelegate::OnTouchSelectionChanged(std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> insertHandle,
5142 std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> startSelectionHandle,
5143 std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> endSelectionHandle)
5144 {
5145 #ifdef NG_BUILD
5146 auto webPattern = webPattern_.Upgrade();
5147 CHECK_NULL_VOID(webPattern);
5148 webPattern->OnTouchSelectionChanged(insertHandle, startSelectionHandle, endSelectionHandle);
5149 return;
5150 #else
5151 if (Container::IsCurrentUseNewPipeline()) {
5152 auto webPattern = webPattern_.Upgrade();
5153 CHECK_NULL_VOID(webPattern);
5154 webPattern->OnTouchSelectionChanged(insertHandle, startSelectionHandle, endSelectionHandle);
5155 return;
5156 }
5157 auto renderWeb = renderWeb_.Upgrade();
5158 CHECK_NULL_VOID(renderWeb);
5159 renderWeb->OnTouchSelectionChanged(insertHandle, startSelectionHandle, endSelectionHandle);
5160 #endif
5161 }
5162
OnCursorChange(const OHOS::NWeb::CursorType & type,const OHOS::NWeb::NWebCursorInfo & info)5163 bool WebDelegate::OnCursorChange(const OHOS::NWeb::CursorType& type, const OHOS::NWeb::NWebCursorInfo& info)
5164 {
5165 #ifdef NG_BUILD
5166 auto webPattern = webPattern_.Upgrade();
5167 CHECK_NULL_RETURN(webPattern, false);
5168 return webPattern->OnCursorChange(type, info);
5169 #else
5170 if (Container::IsCurrentUseNewPipeline()) {
5171 auto webPattern = webPattern_.Upgrade();
5172 CHECK_NULL_RETURN(webPattern, false);
5173 return webPattern->OnCursorChange(type, info);
5174 }
5175 auto renderWeb = renderWeb_.Upgrade();
5176 CHECK_NULL_RETURN(renderWeb, false);
5177 return renderWeb->OnCursorChange(type, info);
5178 #endif
5179 }
5180
OnSelectPopupMenu(std::shared_ptr<OHOS::NWeb::NWebSelectPopupMenuParam> params,std::shared_ptr<OHOS::NWeb::NWebSelectPopupMenuCallback> callback)5181 void WebDelegate::OnSelectPopupMenu(std::shared_ptr<OHOS::NWeb::NWebSelectPopupMenuParam> params,
5182 std::shared_ptr<OHOS::NWeb::NWebSelectPopupMenuCallback> callback)
5183 {
5184 #ifdef NG_BUILD
5185 auto webPattern = webPattern_.Upgrade();
5186 CHECK_NULL_VOID(webPattern);
5187 webPattern->OnSelectPopupMenu(params, callback);
5188 return;
5189 #else
5190 if (Container::IsCurrentUseNewPipeline()) {
5191 auto webPattern = webPattern_.Upgrade();
5192 CHECK_NULL_VOID(webPattern);
5193 webPattern->OnSelectPopupMenu(params, callback);
5194 return;
5195 }
5196 auto renderWeb = renderWeb_.Upgrade();
5197 CHECK_NULL_VOID(renderWeb);
5198 return renderWeb->OnSelectPopupMenu(params, callback);
5199 #endif
5200 }
5201
HandleDragEvent(int32_t x,int32_t y,const DragAction & dragAction)5202 void WebDelegate::HandleDragEvent(int32_t x, int32_t y, const DragAction& dragAction)
5203 {
5204 if (nweb_) {
5205 OHOS::NWeb::DragEvent dragEvent;
5206 dragEvent.x = x;
5207 dragEvent.y = y;
5208 dragEvent.action = static_cast<OHOS::NWeb::DragAction>(dragAction);
5209 nweb_->SendDragEvent(dragEvent);
5210 }
5211 }
5212
GetUrl()5213 std::string WebDelegate::GetUrl()
5214 {
5215 if (nweb_) {
5216 return nweb_->GetUrl();
5217 }
5218 return "";
5219 }
5220
UpdateLocale()5221 void WebDelegate::UpdateLocale()
5222 {
5223 ACE_DCHECK(nweb_ != nullptr);
5224 if (nweb_) {
5225 std::string language = AceApplicationInfo::GetInstance().GetLanguage();
5226 std::string region = AceApplicationInfo::GetInstance().GetCountryOrRegion();
5227 if (!language.empty() || !region.empty()) {
5228 nweb_->UpdateLocale(language, region);
5229 }
5230 }
5231 }
5232
SetDrawRect(int32_t x,int32_t y,int32_t width,int32_t height)5233 void WebDelegate::SetDrawRect(int32_t x, int32_t y, int32_t width, int32_t height)
5234 {
5235 ACE_DCHECK(nweb_ != nullptr);
5236 if (nweb_) {
5237 nweb_->SetDrawRect(x, y, width, height);
5238 }
5239 }
5240 #endif
5241
GetUrlStringParam(const std::string & param,const std::string & name) const5242 std::string WebDelegate::GetUrlStringParam(const std::string& param, const std::string& name) const
5243 {
5244 size_t len = name.length();
5245 size_t posErrorCode = param.find(NTC_PARAM_ERROR_CODE);
5246 size_t pos = param.find(name);
5247 std::string result;
5248
5249 if (pos != std::string::npos && posErrorCode != std::string::npos) {
5250 std::stringstream ss;
5251
5252 ss << param.substr(pos + 1 + len, posErrorCode - 5);
5253 ss >> result;
5254 }
5255 return result;
5256 }
5257
SetWebType(WebType type)5258 void WebDelegate::SetWebType(WebType type)
5259 {
5260 webType_ = static_cast<int32_t>(type);
5261 }
5262
BindRouterBackMethod()5263 void WebDelegate::BindRouterBackMethod()
5264 {
5265 auto context = context_.Upgrade();
5266 if (context) {
5267 context->SetRouterBackEventHandler([weak = WeakClaim(this)] {
5268 auto delegate = weak.Upgrade();
5269 if (delegate) {
5270 delegate->CallWebRouterBack();
5271 }
5272 });
5273 }
5274 }
5275
BindPopPageSuccessMethod()5276 void WebDelegate::BindPopPageSuccessMethod()
5277 {
5278 auto context = context_.Upgrade();
5279 if (context) {
5280 context->SetPopPageSuccessEventHandler(
5281 [weak = WeakClaim(this)](const std::string& pageUrl, const int32_t pageId) {
5282 std::string url = pageUrl.substr(0, pageUrl.length() - 3);
5283 auto delegate = weak.Upgrade();
5284 if (delegate) {
5285 delegate->CallPopPageSuccessPageUrl(url);
5286 }
5287 });
5288 }
5289 }
5290
BindIsPagePathInvalidMethod()5291 void WebDelegate::BindIsPagePathInvalidMethod()
5292 {
5293 auto context = context_.Upgrade();
5294 if (context) {
5295 context->SetIsPagePathInvalidEventHandler([weak = WeakClaim(this)](bool& isPageInvalid) {
5296 auto delegate = weak.Upgrade();
5297 if (delegate) {
5298 delegate->CallIsPagePathInvalid(isPageInvalid);
5299 }
5300 });
5301 }
5302 }
5303
SetComponent(const RefPtr<WebComponent> & component)5304 void WebDelegate::SetComponent(const RefPtr<WebComponent>& component)
5305 {
5306 webComponent_ = component;
5307 }
5308
SetNGWebPattern(const RefPtr<NG::WebPattern> & webPattern)5309 void WebDelegate::SetNGWebPattern(const RefPtr<NG::WebPattern>& webPattern)
5310 {
5311 webPattern_ = webPattern;
5312 }
5313
SetDrawSize(const Size & drawSize)5314 void WebDelegate::SetDrawSize(const Size& drawSize)
5315 {
5316 drawSize_ = drawSize;
5317 }
5318
SetEnhanceSurfaceFlag(const bool & isEnhanceSurface)5319 void WebDelegate::SetEnhanceSurfaceFlag(const bool& isEnhanceSurface)
5320 {
5321 isEnhanceSurface_ = isEnhanceSurface;
5322 }
5323
GetSurfaceDelegateClient()5324 sptr<OHOS::SurfaceDelegate> WebDelegate::GetSurfaceDelegateClient()
5325 {
5326 return surfaceDelegate_;
5327 }
5328
SetBoundsOrResize(const Size & drawSize,const Offset & offset,bool isKeyboard)5329 void WebDelegate::SetBoundsOrResize(const Size& drawSize, const Offset& offset, bool isKeyboard)
5330 {
5331 if ((drawSize.Width() == 0) && (drawSize.Height() == 0)) {
5332 return;
5333 }
5334 if (isEnhanceSurface_) {
5335 if (surfaceDelegate_) {
5336 if (needResizeAtFirst_) {
5337 Resize(drawSize.Width(), drawSize.Height(), isKeyboard);
5338 needResizeAtFirst_ = false;
5339 }
5340 Size webSize = GetEnhanceSurfaceSize(drawSize);
5341 surfaceDelegate_->SetBounds(offset.GetX(), (int32_t)offset.GetY(), webSize.Width(), webSize.Height());
5342 }
5343 } else {
5344 Resize(drawSize.Width(), drawSize.Height(), isKeyboard);
5345 }
5346 }
5347
GetWebRenderGlobalPos()5348 Offset WebDelegate::GetWebRenderGlobalPos()
5349 {
5350 return offset_;
5351 }
5352
GetEnhanceSurfaceSize(const Size & drawSize)5353 Size WebDelegate::GetEnhanceSurfaceSize(const Size& drawSize)
5354 {
5355 auto pipeline = PipelineBase::GetCurrentContext();
5356 CHECK_NULL_RETURN(pipeline, Size());
5357 double dipScale = pipeline->GetDipScale();
5358 if (NearZero(dipScale)) {
5359 return Size();
5360 }
5361 int width = std::ceil(std::floor(drawSize.Width() / dipScale) * dipScale);
5362 int height = std::ceil(std::floor(drawSize.Height() / dipScale) * dipScale);
5363 if (width <= 0) {
5364 width = 1;
5365 }
5366 if (height <= 0) {
5367 height = 1;
5368 }
5369 return Size(width, height);
5370 }
5371
GetAudioStateChangedCallback(bool useNewPipe,const RefPtr<NG::WebEventHub> & eventHub)5372 WebDelegate::EventCallbackV2 WebDelegate::GetAudioStateChangedCallback(
5373 bool useNewPipe, const RefPtr<NG::WebEventHub>& eventHub)
5374 {
5375 if (eventHub && useNewPipe) {
5376 return eventHub->GetOnAudioStateChangedEvent();
5377 }
5378 return nullptr;
5379 }
5380
5381 #ifdef ENABLE_ROSEN_BACKEND
SetSurface(const sptr<Surface> & surface)5382 void WebDelegate::SetSurface(const sptr<Surface>& surface)
5383 {
5384 surface_ = surface;
5385 auto webPattern = webPattern_.Upgrade();
5386 CHECK_NULL_VOID(webPattern);
5387 auto host = webPattern->GetHost();
5388 CHECK_NULL_VOID(host);
5389 auto renderContext = host->GetRenderContext();
5390 CHECK_NULL_VOID(renderContext);
5391 auto rosenRenderContext = AceType::DynamicCast<NG::RosenRenderContext>(renderContext);
5392 CHECK_NULL_VOID(rosenRenderContext);
5393 rsNode_ = rosenRenderContext->GetRSNode();
5394 CHECK_NULL_VOID(rsNode_);
5395 surfaceNodeId_ = rsNode_->GetId();
5396 }
5397 #endif
5398
UpdateScreenOffSet(double & offsetX,double & offsetY)5399 void WebDelegate::UpdateScreenOffSet(double& offsetX, double& offsetY)
5400 {
5401 #ifdef NG_BUILD
5402 auto webPattern = webPattern_.Upgrade();
5403 CHECK_NULL_VOID(webPattern);
5404 offsetX += webPattern->GetHost()->GetTransformRelativeOffset().GetX();
5405 offsetY += webPattern->GetHost()->GetTransformRelativeOffset().GetY();
5406 auto context = context_.Upgrade();
5407 CHECK_NULL_VOID(context);
5408 auto windowOffset = context->GetDisplayWindowRectInfo().GetOffset();
5409 offsetX += windowOffset.GetX();
5410 offsetY += windowOffset.GetY();
5411 return;
5412 #else
5413 if (Container::IsCurrentUseNewPipeline()) {
5414 auto webPattern = webPattern_.Upgrade();
5415 CHECK_NULL_VOID(webPattern);
5416 offsetX += webPattern->GetHost()->GetTransformRelativeOffset().GetX();
5417 offsetY += webPattern->GetHost()->GetTransformRelativeOffset().GetY();
5418 auto context = context_.Upgrade();
5419 CHECK_NULL_VOID(context);
5420 auto windowOffset = context->GetDisplayWindowRectInfo().GetOffset();
5421 offsetX += windowOffset.GetX();
5422 offsetY += windowOffset.GetY();
5423 return;
5424 }
5425 auto renderWeb = renderWeb_.Upgrade();
5426 CHECK_NULL_VOID(renderWeb);
5427 offsetX += renderWeb->GetGlobalOffset().GetX();
5428 offsetY += renderWeb->GetGlobalOffset().GetY();
5429 auto context = context_.Upgrade();
5430 CHECK_NULL_VOID(context);
5431 auto windowOffset = context->GetDisplayWindowRectInfo().GetOffset();
5432 offsetX += windowOffset.GetX();
5433 offsetY += windowOffset.GetY();
5434 WindowMode windowMode = context->GetWindowManager()->GetWindowMode();
5435 if (windowMode == WindowMode::WINDOW_MODE_FLOATING) {
5436 offsetX += CONTAINER_BORDER_WIDTH.ConvertToPx();
5437 offsetY += CONTAINER_TITLE_HEIGHT.ConvertToPx();
5438 }
5439 #endif
5440 }
5441
UpdateOverScrollMode(const int overscrollModeValue)5442 void WebDelegate::UpdateOverScrollMode(const int overscrollModeValue)
5443 {
5444 auto context = context_.Upgrade();
5445 CHECK_NULL_VOID(context);
5446 context->GetTaskExecutor()->PostTask(
5447 [weak = WeakClaim(this), overscrollModeValue]() {
5448 auto delegate = weak.Upgrade();
5449 CHECK_NULL_VOID(delegate);
5450 CHECK_NULL_VOID(delegate->nweb_);
5451 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
5452 CHECK_NULL_VOID(setting);
5453 setting->PutOverscrollMode(overscrollModeValue);
5454 },
5455 TaskExecutor::TaskType::PLATFORM);
5456 }
5457
UpdateCopyOptionMode(const int copyOptionModeValue)5458 void WebDelegate::UpdateCopyOptionMode(const int copyOptionModeValue)
5459 {
5460 auto context = context_.Upgrade();
5461 CHECK_NULL_VOID(context);
5462 context->GetTaskExecutor()->PostTask(
5463 [weak = WeakClaim(this), copyOptionModeValue]() {
5464 auto delegate = weak.Upgrade();
5465 CHECK_NULL_VOID(delegate);
5466 CHECK_NULL_VOID(delegate->nweb_);
5467 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
5468 CHECK_NULL_VOID(setting);
5469 setting->PutCopyOptionMode(
5470 static_cast<OHOS::NWeb::NWebPreference::CopyOptionMode>(copyOptionModeValue));
5471 },
5472 TaskExecutor::TaskType::PLATFORM);
5473 }
5474
RegisterSurfacePositionChangedCallback()5475 void WebDelegate::RegisterSurfacePositionChangedCallback()
5476 {
5477 #ifdef NG_BUILD
5478 auto pipelineContext = DynamicCast<NG::PipelineContext>(context_.Upgrade());
5479 CHECK_NULL_VOID(pipelineContext);
5480 if (callbackId_ <= 0) {
5481 callbackId_ = pipelineContext->RegisterSurfacePositionChangedCallback(
5482 [weak = WeakClaim(this)](int32_t posX, int32_t posY) {
5483 auto delegate = weak.Upgrade();
5484 if (delegate && delegate->nweb_ && !delegate->window_) {
5485 double offsetX = 0;
5486 double offsetY = 0;
5487 delegate->UpdateScreenOffSet(offsetX, offsetY);
5488 delegate->nweb_->SetScreenOffSet(offsetX, offsetY);
5489 }
5490 });
5491 }
5492 return;
5493 #else
5494 if (Container::IsCurrentUseNewPipeline()) {
5495 auto pipelineContext = DynamicCast<NG::PipelineContext>(context_.Upgrade());
5496 CHECK_NULL_VOID(pipelineContext);
5497 if (callbackId_ <= 0) {
5498 callbackId_ = pipelineContext->RegisterSurfacePositionChangedCallback(
5499 [weak = WeakClaim(this)](int32_t posX, int32_t posY) {
5500 auto delegate = weak.Upgrade();
5501 if (delegate && delegate->nweb_ && !delegate->window_) {
5502 double offsetX = 0;
5503 double offsetY = 0;
5504 delegate->UpdateScreenOffSet(offsetX, offsetY);
5505 delegate->nweb_->SetScreenOffSet(offsetX, offsetY);
5506 }
5507 });
5508 }
5509 return;
5510 }
5511 auto pipelineContext = DynamicCast<PipelineContext>(context_.Upgrade());
5512 CHECK_NULL_VOID(pipelineContext);
5513 if (callbackId_ <= 0) {
5514 callbackId_ = pipelineContext->RegisterSurfacePositionChangedCallback(
5515 [weak = WeakClaim(this)](int32_t posX, int32_t posY) {
5516 auto delegate = weak.Upgrade();
5517 if (delegate && delegate->nweb_ && !delegate->window_) {
5518 double offsetX = 0;
5519 double offsetY = 0;
5520 delegate->UpdateScreenOffSet(offsetX, offsetY);
5521 delegate->nweb_->SetScreenOffSet(offsetX, offsetY);
5522 }
5523 });
5524 }
5525 #endif
5526 }
5527
UnregisterSurfacePositionChangedCallback()5528 void WebDelegate::UnregisterSurfacePositionChangedCallback()
5529 {
5530 if (callbackId_ <= 0) {
5531 return;
5532 }
5533 #ifdef NG_BUILD
5534 auto pipelineContext = DynamicCast<NG::PipelineContext>(context_.Upgrade());
5535 CHECK_NULL_VOID(pipelineContext);
5536 pipelineContext->UnregisterSurfacePositionChangedCallback(callbackId_);
5537 callbackId_ = 0;
5538 return;
5539 #else
5540 if (Container::IsCurrentUseNewPipeline()) {
5541 auto pipelineContext = DynamicCast<NG::PipelineContext>(context_.Upgrade());
5542 CHECK_NULL_VOID(pipelineContext);
5543 pipelineContext->UnregisterSurfacePositionChangedCallback(callbackId_);
5544 callbackId_ = 0;
5545 return;
5546 }
5547 auto pipelineContext = DynamicCast<PipelineContext>(context_.Upgrade());
5548 CHECK_NULL_VOID(pipelineContext);
5549 pipelineContext->UnregisterSurfacePositionChangedCallback(callbackId_);
5550 callbackId_ = 0;
5551 #endif
5552 }
5553
OnCompleteSwapWithNewSize()5554 void WebDelegate::OnCompleteSwapWithNewSize()
5555 {
5556 auto webPattern = webPattern_.Upgrade();
5557 CHECK_NULL_VOID(webPattern);
5558 webPattern->OnCompleteSwapWithNewSize();
5559 }
5560
OnResizeNotWork()5561 void WebDelegate::OnResizeNotWork()
5562 {
5563 auto webPattern = webPattern_.Upgrade();
5564 CHECK_NULL_VOID(webPattern);
5565 webPattern->OnResizeNotWork();
5566 }
5567
OnDateTimeChooserPopup(const OHOS::NWeb::DateTimeChooser & chooser,const std::vector<OHOS::NWeb::DateTimeSuggestion> & suggestions,std::shared_ptr<OHOS::NWeb::NWebDateTimeChooserCallback> callback)5568 void WebDelegate::OnDateTimeChooserPopup(const OHOS::NWeb::DateTimeChooser& chooser,
5569 const std::vector<OHOS::NWeb::DateTimeSuggestion>& suggestions,
5570 std::shared_ptr<OHOS::NWeb::NWebDateTimeChooserCallback> callback)
5571 {
5572 auto webPattern = webPattern_.Upgrade();
5573 CHECK_NULL_VOID(webPattern);
5574 webPattern->OnDateTimeChooserPopup(chooser, suggestions, callback);
5575 }
5576
OnDateTimeChooserClose()5577 void WebDelegate::OnDateTimeChooserClose()
5578 {
5579 auto webPattern = webPattern_.Upgrade();
5580 CHECK_NULL_VOID(webPattern);
5581 webPattern->OnDateTimeChooserClose();
5582 }
5583
OnOverScroll(float xOffset,float yOffset)5584 void WebDelegate::OnOverScroll(float xOffset, float yOffset)
5585 {
5586 auto context = context_.Upgrade();
5587 CHECK_NULL_VOID(context);
5588 context->GetTaskExecutor()->PostTask(
5589 [weak = WeakClaim(this), xOffset, yOffset]() {
5590 auto delegate = weak.Upgrade();
5591 CHECK_NULL_VOID(delegate);
5592 auto onOverScrollV2 = delegate->onOverScrollV2_;
5593 if (onOverScrollV2) {
5594 onOverScrollV2(std::make_shared<WebOnOverScrollEvent>(xOffset, yOffset));
5595 }
5596 },
5597 TaskExecutor::TaskType::JS);
5598 }
5599
SetTouchEventInfo(const OHOS::NWeb::NativeEmbedTouchEvent & touchEvent,TouchEventInfo & touchEventInfo)5600 void WebDelegate::SetTouchEventInfo(const OHOS::NWeb::NativeEmbedTouchEvent& touchEvent, TouchEventInfo& touchEventInfo)
5601 {
5602 auto webPattern = webPattern_.Upgrade();
5603 CHECK_NULL_VOID(webPattern);
5604 TouchEvent event{touchEvent.id, touchEvent.x, touchEvent.y, touchEvent.screenX, touchEvent.screenY,
5605 static_cast<OHOS::Ace::TouchType>(touchEvent.type)};
5606 webPattern->SetTouchEventInfo(event, touchEventInfo);
5607 }
5608
OnNativeEmbedLifecycleChange(const OHOS::NWeb::NativeEmbedDataInfo & dataInfo)5609 void WebDelegate::OnNativeEmbedLifecycleChange(const OHOS::NWeb::NativeEmbedDataInfo& dataInfo)
5610 {
5611 if (!isEmbedModeEnabled_) {
5612 return;
5613 }
5614 auto embedInfo = dataInfo.info;
5615 auto status = static_cast<OHOS::Ace::NativeEmbedStatus>(dataInfo.status);
5616 auto surfaceId = dataInfo.surfaceId;
5617 auto embedId = dataInfo.embedId;
5618 EmbedInfo info = {embedInfo.id, embedInfo.type,
5619 embedInfo.src, embedInfo.url, embedInfo.width, embedInfo.height};
5620 auto context = context_.Upgrade();
5621 CHECK_NULL_VOID(context);
5622 context->GetTaskExecutor()->PostTask(
5623 [weak = WeakClaim(this), status, surfaceId, embedId, info]() {
5624 auto delegate = weak.Upgrade();
5625 CHECK_NULL_VOID(delegate);
5626 auto OnNativeEmbedLifecycleChangeV2_ = delegate->OnNativeEmbedLifecycleChangeV2_;
5627 if (OnNativeEmbedLifecycleChangeV2_) {
5628 OnNativeEmbedLifecycleChangeV2_(
5629 std::make_shared<NativeEmbedDataInfo>(status, surfaceId, embedId, info));
5630 }
5631 },
5632 TaskExecutor::TaskType::JS);
5633 }
OnNativeEmbedGestureEvent(const OHOS::NWeb::NativeEmbedTouchEvent & event)5634 void WebDelegate::OnNativeEmbedGestureEvent(const OHOS::NWeb::NativeEmbedTouchEvent& event)
5635 {
5636 auto context = context_.Upgrade();
5637 TouchEventInfo touchEventInfo("touchEvent");
5638 auto embedId = event.embedId;
5639 SetTouchEventInfo(event, touchEventInfo);
5640 CHECK_NULL_VOID(context);
5641 TAG_LOGD(AceLogTag::ACE_WEB, "hit Emebed gusture event notify");
5642 context->GetTaskExecutor()->PostTask(
5643 [weak = WeakClaim(this), embedId, touchEventInfo]() {
5644 auto delegate = weak.Upgrade();
5645 CHECK_NULL_VOID(delegate);
5646 auto OnNativeEmbedGestureEventV2_ = delegate->OnNativeEmbedGestureEventV2_;
5647 if (OnNativeEmbedGestureEventV2_) {
5648 OnNativeEmbedGestureEventV2_(
5649 std::make_shared<NativeEmbeadTouchInfo>(embedId, touchEventInfo));
5650 }
5651 },
5652 TaskExecutor::TaskType::JS);
5653 }
5654
SetToken()5655 void WebDelegate::SetToken()
5656 {
5657 auto container = AceType::DynamicCast<Platform::AceContainer>(Container::Current());
5658 CHECK_NULL_VOID(container);
5659 auto token = container->GetToken();
5660 if (nweb_) {
5661 nweb_->SetToken(static_cast<void*>(token));
5662 }
5663 }
5664
OnOverScrollFlingVelocity(float xVelocity,float yVelocity,bool isFling)5665 void WebDelegate::OnOverScrollFlingVelocity(float xVelocity, float yVelocity, bool isFling)
5666 {
5667 auto webPattern = webPattern_.Upgrade();
5668 CHECK_NULL_VOID(webPattern);
5669 webPattern->OnOverScrollFlingVelocity(xVelocity, yVelocity, isFling);
5670 }
5671
OnScrollState(bool scrollState)5672 void WebDelegate::OnScrollState(bool scrollState)
5673 {
5674 auto webPattern = webPattern_.Upgrade();
5675 CHECK_NULL_VOID(webPattern);
5676 webPattern->OnScrollState(scrollState);
5677 }
5678
OnRootLayerChanged(int width,int height)5679 void WebDelegate::OnRootLayerChanged(int width, int height)
5680 {
5681 auto webPattern = webPattern_.Upgrade();
5682 CHECK_NULL_VOID(webPattern);
5683 webPattern->OnRootLayerChanged(width, height);
5684 }
5685
SetVirtualKeyBoardArg(int32_t width,int32_t height,double keyboard)5686 void WebDelegate::SetVirtualKeyBoardArg(int32_t width, int32_t height, double keyboard)
5687 {
5688 if (nweb_) {
5689 nweb_->SetVirtualKeyBoardArg(width, height, keyboard);
5690 }
5691 }
5692
ShouldVirtualKeyboardOverlay()5693 bool WebDelegate::ShouldVirtualKeyboardOverlay()
5694 {
5695 if (nweb_) {
5696 return nweb_->ShouldVirtualKeyboardOverlay();
5697 }
5698 return false;
5699 }
5700
FilterScrollEvent(const float x,const float y,const float xVelocity,const float yVelocity)5701 bool WebDelegate::FilterScrollEvent(const float x, const float y, const float xVelocity, const float yVelocity)
5702 {
5703 auto webPattern = webPattern_.Upgrade();
5704 CHECK_NULL_RETURN(webPattern, false);
5705 return webPattern->FilterScrollEvent(x, y, xVelocity, yVelocity);
5706 }
5707
ScrollBy(float deltaX,float deltaY)5708 void WebDelegate::ScrollBy(float deltaX, float deltaY)
5709 {
5710 CHECK_NULL_VOID(nweb_);
5711 nweb_->ScrollBy(deltaX, deltaY);
5712 }
5713
SetJavaScriptItems(const ScriptItems & scriptItems,const ScriptItemType & type)5714 void WebDelegate::SetJavaScriptItems(const ScriptItems& scriptItems, const ScriptItemType& type)
5715 {
5716 if (type == ScriptItemType::DOCUMENT_START) {
5717 onDocumentStartScriptItems_ = std::make_optional<ScriptItems>(scriptItems);
5718 } else {
5719 onDocumentEndScriptItems_ = std::make_optional<ScriptItems>(scriptItems);
5720 }
5721 }
5722
JavaScriptOnDocumentStart()5723 void WebDelegate::JavaScriptOnDocumentStart()
5724 {
5725 CHECK_NULL_VOID(nweb_);
5726 if (onDocumentStartScriptItems_.has_value()) {
5727 nweb_->JavaScriptOnDocumentStart(onDocumentStartScriptItems_.value());
5728 onDocumentStartScriptItems_ = std::nullopt;
5729 }
5730 }
5731
JavaScriptOnDocumentEnd()5732 void WebDelegate::JavaScriptOnDocumentEnd()
5733 {
5734 CHECK_NULL_VOID(nweb_);
5735 if (onDocumentEndScriptItems_.has_value()) {
5736 nweb_->JavaScriptOnDocumentEnd(onDocumentEndScriptItems_.value());
5737 onDocumentEndScriptItems_ = std::nullopt;
5738 }
5739 }
5740
ExecuteAction(int64_t accessibilityId,AceAction action)5741 void WebDelegate::ExecuteAction(int64_t accessibilityId, AceAction action)
5742 {
5743 if (!accessibilityState_) {
5744 return;
5745 }
5746 auto context = context_.Upgrade();
5747 CHECK_NULL_VOID(context);
5748 uint32_t nwebAction = static_cast<uint32_t>(action);
5749 context->GetTaskExecutor()->PostTask(
5750 [weak = WeakClaim(this), accessibilityId, nwebAction]() {
5751 auto delegate = weak.Upgrade();
5752 CHECK_NULL_VOID(delegate);
5753 CHECK_NULL_VOID(delegate->nweb_);
5754 delegate->nweb_->ExecuteAction(accessibilityId, nwebAction);
5755 },
5756 TaskExecutor::TaskType::PLATFORM);
5757 }
5758
SetAccessibilityState(bool state)5759 void WebDelegate::SetAccessibilityState(bool state)
5760 {
5761 if (state == accessibilityState_) {
5762 return;
5763 }
5764 accessibilityState_ = state;
5765 auto context = context_.Upgrade();
5766 CHECK_NULL_VOID(context);
5767 context->GetTaskExecutor()->PostTask(
5768 [weak = WeakClaim(this), state]() {
5769 auto delegate = weak.Upgrade();
5770 CHECK_NULL_VOID(delegate);
5771 CHECK_NULL_VOID(delegate->nweb_);
5772 delegate->nweb_->SetAccessibilityState(state);
5773 if (state) {
5774 auto accessibilityEventListenerImpl =
5775 std::make_shared<AccessibilityEventListenerImpl>(Container::CurrentId());
5776 CHECK_NULL_VOID(accessibilityEventListenerImpl);
5777 accessibilityEventListenerImpl->SetWebDelegate(weak);
5778 delegate->nweb_->PutAccessibilityIdGenerator(NG::UINode::GenerateAccessibilityId);
5779 delegate->nweb_->PutAccessibilityEventCallback(accessibilityEventListenerImpl);
5780 }
5781 },
5782 TaskExecutor::TaskType::PLATFORM);
5783 }
5784
GetFocusedAccessibilityNodeInfo(int64_t accessibilityId,bool isAccessibilityFocus,OHOS::NWeb::NWebAccessibilityNodeInfo & nodeInfo) const5785 bool WebDelegate::GetFocusedAccessibilityNodeInfo(
5786 int64_t accessibilityId, bool isAccessibilityFocus, OHOS::NWeb::NWebAccessibilityNodeInfo& nodeInfo) const
5787 {
5788 CHECK_NULL_RETURN(nweb_, false);
5789 if (!accessibilityState_) {
5790 return false;
5791 }
5792 return nweb_->GetFocusedAccessibilityNodeInfo(accessibilityId, isAccessibilityFocus, nodeInfo);
5793 }
5794
GetAccessibilityNodeInfoById(int64_t accessibilityId,OHOS::NWeb::NWebAccessibilityNodeInfo & nodeInfo) const5795 bool WebDelegate::GetAccessibilityNodeInfoById(
5796 int64_t accessibilityId, OHOS::NWeb::NWebAccessibilityNodeInfo& nodeInfo) const
5797 {
5798 CHECK_NULL_RETURN(nweb_, false);
5799 if (!accessibilityState_) {
5800 return false;
5801 }
5802 return nweb_->GetAccessibilityNodeInfoById(accessibilityId, nodeInfo);
5803 }
5804
GetAccessibilityNodeInfoByFocusMove(int64_t accessibilityId,int32_t direction,OHOS::NWeb::NWebAccessibilityNodeInfo & nodeInfo) const5805 bool WebDelegate::GetAccessibilityNodeInfoByFocusMove(
5806 int64_t accessibilityId, int32_t direction, OHOS::NWeb::NWebAccessibilityNodeInfo& nodeInfo) const
5807 {
5808 CHECK_NULL_RETURN(nweb_, false);
5809 if (!accessibilityState_) {
5810 return false;
5811 }
5812 return nweb_->GetAccessibilityNodeInfoByFocusMove(accessibilityId, direction, nodeInfo);
5813 }
5814
GetCopyOptionMode() const5815 OHOS::NWeb::NWebPreference::CopyOptionMode WebDelegate::GetCopyOptionMode() const
5816 {
5817 CHECK_NULL_RETURN(nweb_, OHOS::NWeb::NWebPreference::CopyOptionMode::CROSS_DEVICE);
5818 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_->GetPreference();
5819 CHECK_NULL_RETURN(setting, OHOS::NWeb::NWebPreference::CopyOptionMode::CROSS_DEVICE);
5820 auto copyOption = setting->GetCopyOptionMode();
5821 return copyOption;
5822 }
5823 } // namespace OHOS::Ace
5824