• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2024 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 "adapter/ohos/entrance/utils.h"
27 #include "base/json/json_util.h"
28 #include "base/log/ace_trace.h"
29 #include "base/log/log.h"
30 #include "base/memory/referenced.h"
31 #include "base/notification/eventhandler/interfaces/inner_api/event_handler.h"
32 #include "base/ressched/ressched_report.h"
33 #include "base/utils/utils.h"
34 #include "core/accessibility/accessibility_manager.h"
35 #include "core/components/container_modal/container_modal_constants.h"
36 #include "core/components/web/render_web.h"
37 #include "core/components/web/web_event.h"
38 #include "core/components/web/web_property.h"
39 #include "core/components_ng/pattern/web/web_pattern.h"
40 #include "core/pipeline_ng/pipeline_context.h"
41 #include "adapter/ohos/capability/html/span_to_html.h"
42 #ifdef ENABLE_ROSEN_BACKEND
43 #include "core/components_ng/render/adapter/rosen_render_context.h"
44 #endif
45 #include "core/common/ace_application_info.h"
46 #include "core/event/ace_event_helper.h"
47 #include "core/event/ace_events.h"
48 #include "core/event/back_end_event_manager.h"
49 #include "frameworks/bridge/js_frontend/frontend_delegate_impl.h"
50 #ifdef OHOS_STANDARD_SYSTEM
51 #include "application_env.h"
52 #include "iservice_registry.h"
53 #include "nweb_adapter_helper.h"
54 #include "nweb_handler.h"
55 #include "parameters.h"
56 #include "screen_manager/screen_types.h"
57 #include "system_ability_definition.h"
58 #include "third_party/icu/icu4c/source/common/unicode/ucnv.h"
59 #include "transaction/rs_interfaces.h"
60 #include "web_configuration_observer.h"
61 #include "web_javascript_execute_callback.h"
62 #include "web_javascript_result_callback.h"
63 
64 #include "core/components_ng/base/ui_node.h"
65 #include "frameworks/base/utils/system_properties.h"
66 #endif
67 
68 namespace OHOS::Ace {
69 
70 namespace {
71 
72 constexpr char WEB_METHOD_ROUTER_BACK[] = "routerBack";
73 constexpr char WEB_METHOD_UPDATEURL[] = "updateUrl";
74 constexpr char WEB_METHOD_CHANGE_PAGE_URL[] = "changePageUrl";
75 constexpr char WEB_METHOD_PAGE_PATH_INVALID[] = "pagePathInvalid";
76 constexpr char WEB_EVENT_PAGESTART[] = "onPageStarted";
77 constexpr char WEB_EVENT_PAGEFINISH[] = "onPageFinished";
78 constexpr char WEB_EVENT_PAGEERROR[] = "onPageError";
79 constexpr char WEB_EVENT_ONMESSAGE[] = "onMessage";
80 constexpr char WEB_EVENT_ROUTERPUSH[] = "routerPush";
81 
82 constexpr char WEB_CREATE[] = "web";
83 constexpr char NTC_PARAM_WEB[] = "web";
84 constexpr char NTC_PARAM_WIDTH[] = "width";
85 constexpr char NTC_PARAM_HEIGHT[] = "height";
86 constexpr char NTC_PARAM_LEFT[] = "left";
87 constexpr char NTC_PARAM_TOP[] = "top";
88 constexpr char NTC_ERROR[] = "create error";
89 constexpr char NTC_PARAM_SRC[] = "src";
90 constexpr char NTC_PARAM_ERROR_CODE[] = "errorCode";
91 constexpr char NTC_PARAM_URL[] = "url";
92 constexpr char NTC_PARAM_PAGE_URL[] = "pageUrl";
93 constexpr char NTC_PARAM_PAGE_INVALID[] = "pageInvalid";
94 constexpr char NTC_PARAM_DESCRIPTION[] = "description";
95 constexpr char WEB_ERROR_CODE_CREATEFAIL[] = "error-web-delegate-000001";
96 constexpr char WEB_ERROR_MSG_CREATEFAIL[] = "create web_delegate failed.";
97 
98 const std::string RESOURCE_VIDEO_CAPTURE = "TYPE_VIDEO_CAPTURE";
99 const std::string RESOURCE_AUDIO_CAPTURE = "TYPE_AUDIO_CAPTURE";
100 const std::string RESOURCE_PROTECTED_MEDIA_ID = "TYPE_PROTECTED_MEDIA_ID";
101 const std::string RESOURCE_MIDI_SYSEX = "TYPE_MIDI_SYSEX";
102 const std::string RESOURCE_CLIPBOARD_READ_WRITE = "TYPE_CLIPBOARD_READ_WRITE";
103 const std::string RESOURCE_SENSOR = "TYPE_SENSOR";
104 const std::string DEFAULT_CANONICAL_ENCODING_NAME = "UTF-8";
105 constexpr uint32_t DESTRUCT_DELAY_MILLISECONDS = 1000;
106 
107 constexpr uint32_t DRAG_DELAY_MILLISECONDS = 300;
108 constexpr uint32_t DELAY_MILLISECONDS_1000 = 1000;
109 constexpr uint32_t NO_NATIVE_FINGER_TYPE = 100;
110 const std::string DEFAULT_NATIVE_EMBED_ID = "0";
111 
112 const std::vector<std::string> CANONICALENCODINGNAMES = {
113     "Big5",         "EUC-JP",       "EUC-KR",       "GB18030",
114     "GBK",          "IBM866",       "ISO-2022-JP",  "ISO-8859-10",
115     "ISO-8859-13",  "ISO-8859-14",  "ISO-8859-15",  "ISO-8859-16",
116     "ISO-8859-1",   "ISO-8859-2",   "ISO-8859-3",   "ISO-8859-4",
117     "ISO-8859-5",   "ISO-8859-6",   "ISO-8859-7",   "ISO-8859-8",
118     "ISO-8859-8-I", "KOI8-R",       "KOI8-U",       "macintosh",
119     "Shift_JIS",    "UTF-8",        "windows-1250", "windows-1251",
120     "windows-1252", "windows-1253", "windows-1254", "windows-1255",
121     "windows-1256", "windows-1257", "windows-1258", "windows-874" };
122 
123 #define VISIBLERATIO_LENGTH 4
124 #define VISIBLERATIO_FLOAT_TO_INT 100
125 
IsDeviceTabletOr2in1()126 static bool IsDeviceTabletOr2in1()
127 {
128     return OHOS::system::GetDeviceType() == "tablet" || OHOS::system::GetDeviceType() == "2in1";
129 }
130 
GetWebOptimizationValue()131 static bool GetWebOptimizationValue()
132 {
133     return OHOS::system::GetBoolParameter("web.optimization", true);
134 }
135 } // namespace
136 
137 #define EGLCONFIG_VERSION 3
138 
SetPortHandle(std::string & handle)139 void WebMessagePortOhos::SetPortHandle(std::string& handle)
140 {
141     handle_ = handle;
142 }
143 
GetPortHandle()144 std::string WebMessagePortOhos::GetPortHandle()
145 {
146     return handle_;
147 }
148 
Close()149 void WebMessagePortOhos::Close()
150 {
151     auto delegate = webDelegate_.Upgrade();
152     if (!delegate) {
153         return;
154     }
155     delegate->ClosePort(handle_);
156 }
157 
PostMessage(std::string & data)158 void WebMessagePortOhos::PostMessage(std::string& data)
159 {
160     auto delegate = webDelegate_.Upgrade();
161     if (!delegate) {
162         return;
163     }
164     delegate->PostPortMessage(handle_, data);
165 }
166 
SetWebMessageCallback(std::function<void (const std::string &)> && callback)167 void WebMessagePortOhos::SetWebMessageCallback(std::function<void(const std::string&)>&& callback)
168 {
169     auto delegate = webDelegate_.Upgrade();
170     if (!delegate) {
171         return;
172     }
173     delegate->SetPortMessageCallback(handle_, std::move(callback));
174 }
175 
GetLineNumber()176 int ConsoleLogOhos::GetLineNumber()
177 {
178     if (message_) {
179         return message_->LineNumer();
180     }
181     return -1;
182 }
183 
GetLog()184 std::string ConsoleLogOhos::GetLog()
185 {
186     if (message_) {
187         return message_->Log();
188     }
189     return "";
190 }
191 
GetLogLevel()192 int ConsoleLogOhos::GetLogLevel()
193 {
194     if (message_) {
195         return message_->LogLevel();
196     }
197     return -1;
198 }
199 
GetSourceId()200 std::string ConsoleLogOhos::GetSourceId()
201 {
202     if (message_) {
203         return message_->SourceId();
204     }
205     return "";
206 }
207 
Confirm()208 void ResultOhos::Confirm()
209 {
210     if (result_) {
211         result_->Confirm();
212     }
213 }
214 
Confirm(const std::string & message)215 void ResultOhos::Confirm(const std::string& message)
216 {
217     if (result_) {
218         result_->Confirm(message);
219     }
220 }
221 
Cancel()222 void ResultOhos::Cancel()
223 {
224     if (result_) {
225         result_->Cancel();
226     }
227 }
228 
ExitFullScreen()229 void FullScreenExitHandlerOhos::ExitFullScreen()
230 {
231     auto delegate = webDelegate_.Upgrade();
232     CHECK_NULL_VOID(delegate);
233     CHECK_NULL_VOID(handler_);
234     if (Container::IsCurrentUseNewPipeline()) {
235         // notify chromium to exit fullscreen mode.
236         handler_->ExitFullScreen();
237         // notify web component in arkui to exit fullscreen mode.
238         delegate->ExitFullScreen();
239     }
240 }
241 
Confirm(std::string & userName,std::string & pwd)242 bool AuthResultOhos::Confirm(std::string& userName, std::string& pwd)
243 {
244     if (result_) {
245         return result_->Confirm(userName, pwd);
246     }
247     return false;
248 }
249 
IsHttpAuthInfoSaved()250 bool AuthResultOhos::IsHttpAuthInfoSaved()
251 {
252     if (result_) {
253         return result_->IsHttpAuthInfoSaved();
254     }
255     return false;
256 }
257 
Cancel()258 void AuthResultOhos::Cancel()
259 {
260     if (result_) {
261         result_->Cancel();
262     }
263 }
264 
HandleConfirm()265 void SslErrorResultOhos::HandleConfirm()
266 {
267     if (result_) {
268         result_->HandleConfirm();
269     }
270 }
271 
HandleCancel()272 void SslErrorResultOhos::HandleCancel()
273 {
274     if (result_) {
275         result_->HandleCancel();
276     }
277 }
278 
HandleConfirm()279 void AllSslErrorResultOhos::HandleConfirm()
280 {
281     if (result_) {
282         result_->HandleConfirm();
283     }
284 }
285 
HandleCancel()286 void AllSslErrorResultOhos::HandleCancel()
287 {
288     if (result_) {
289         result_->HandleCancel();
290     }
291 }
292 
HandleConfirm(const std::string & privateKeyFile,const std::string & certChainFile)293 void SslSelectCertResultOhos::HandleConfirm(const std::string& privateKeyFile, const std::string& certChainFile)
294 {
295     if (result_) {
296         result_->Confirm(privateKeyFile, certChainFile);
297     }
298 }
299 
HandleCancel()300 void SslSelectCertResultOhos::HandleCancel()
301 {
302     if (result_) {
303         result_->Cancel();
304     }
305 }
306 
HandleIgnore()307 void SslSelectCertResultOhos::HandleIgnore()
308 {
309     if (result_) {
310         result_->Ignore();
311     }
312 }
313 
GetTitle()314 std::string FileSelectorParamOhos::GetTitle()
315 {
316     if (param_) {
317         return param_->Title();
318     }
319     return "";
320 }
321 
GetMode()322 int FileSelectorParamOhos::GetMode()
323 {
324     if (param_) {
325         return param_->Mode();
326     }
327     return 0;
328 }
329 
GetDefaultFileName()330 std::string FileSelectorParamOhos::GetDefaultFileName()
331 {
332     if (param_) {
333         return param_->DefaultFilename();
334     }
335     return "";
336 }
337 
GetAcceptType()338 std::vector<std::string> FileSelectorParamOhos::GetAcceptType()
339 {
340     if (param_) {
341         return param_->AcceptType();
342     }
343     return std::vector<std::string>();
344 }
345 
IsCapture()346 bool FileSelectorParamOhos::IsCapture()
347 {
348     if (param_) {
349         return param_->IsCapture();
350     }
351     return false;
352 }
353 
HandleFileList(std::vector<std::string> & result)354 void FileSelectorResultOhos::HandleFileList(std::vector<std::string>& result)
355 {
356     if (callback_) {
357         callback_->OnReceiveValue(result);
358     }
359 }
360 
Deny() const361 void WebPermissionRequestOhos::Deny() const
362 {
363     if (request_) {
364         request_->Refuse();
365     }
366 }
367 
GetOrigin() const368 std::string WebPermissionRequestOhos::GetOrigin() const
369 {
370     if (request_) {
371         return request_->Origin();
372     }
373     return "";
374 }
375 
GetResources() const376 std::vector<std::string> WebPermissionRequestOhos::GetResources() const
377 {
378     std::vector<std::string> resources;
379     if (request_) {
380         uint32_t resourcesId = static_cast<uint32_t>(request_->ResourceAcessId());
381         if (resourcesId & OHOS::NWeb::NWebAccessRequest::Resources::VIDEO_CAPTURE) {
382             resources.push_back(RESOURCE_VIDEO_CAPTURE);
383         }
384         if (resourcesId & OHOS::NWeb::NWebAccessRequest::Resources::AUDIO_CAPTURE) {
385             resources.push_back(RESOURCE_AUDIO_CAPTURE);
386         }
387         if (resourcesId & OHOS::NWeb::NWebAccessRequest::Resources::PROTECTED_MEDIA_ID) {
388             resources.push_back(RESOURCE_PROTECTED_MEDIA_ID);
389         }
390         if (resourcesId & OHOS::NWeb::NWebAccessRequest::Resources::MIDI_SYSEX) {
391             resources.push_back(RESOURCE_MIDI_SYSEX);
392         }
393         if (resourcesId & OHOS::NWeb::NWebAccessRequest::Resources::CLIPBOARD_READ_WRITE) {
394             resources.push_back(RESOURCE_CLIPBOARD_READ_WRITE);
395         }
396         if (resourcesId & OHOS::NWeb::NWebAccessRequest::Resources::SENSORS) {
397             resources.push_back(RESOURCE_SENSOR);
398         }
399     }
400     return resources;
401 }
402 
Grant(std::vector<std::string> & resources) const403 void WebPermissionRequestOhos::Grant(std::vector<std::string>& resources) const
404 {
405     if (request_) {
406         uint32_t resourcesId = 0;
407         for (auto res : resources) {
408             if (res == RESOURCE_VIDEO_CAPTURE) {
409                 resourcesId |= OHOS::NWeb::NWebAccessRequest::Resources::VIDEO_CAPTURE;
410             } else if (res == RESOURCE_AUDIO_CAPTURE) {
411                 resourcesId |= OHOS::NWeb::NWebAccessRequest::Resources::AUDIO_CAPTURE;
412             } else if (res == RESOURCE_PROTECTED_MEDIA_ID) {
413                 resourcesId |= OHOS::NWeb::NWebAccessRequest::Resources::PROTECTED_MEDIA_ID;
414             } else if (res == RESOURCE_MIDI_SYSEX) {
415                 resourcesId |= OHOS::NWeb::NWebAccessRequest::Resources::MIDI_SYSEX;
416             } else if (res == RESOURCE_CLIPBOARD_READ_WRITE) {
417                 resourcesId |= OHOS::NWeb::NWebAccessRequest::Resources::CLIPBOARD_READ_WRITE;
418             } else if (res == RESOURCE_SENSOR) {
419                 resourcesId |= OHOS::NWeb::NWebAccessRequest::Resources::SENSORS;
420             }
421         }
422         request_->Agree(resourcesId);
423     }
424 }
425 
Deny() const426 void WebScreenCaptureRequestOhos::Deny() const
427 {
428     if (request_) {
429         request_->Refuse();
430     }
431 }
432 
GetOrigin() const433 std::string WebScreenCaptureRequestOhos::GetOrigin() const
434 {
435     if (request_) {
436         return request_->Origin();
437     }
438     return "";
439 }
440 
SetCaptureMode(int32_t mode)441 void WebScreenCaptureRequestOhos::SetCaptureMode(int32_t mode)
442 {
443     config_->SetMode(mode);
444 }
445 
SetSourceId(int32_t sourceId)446 void WebScreenCaptureRequestOhos::SetSourceId(int32_t sourceId)
447 {
448     config_->SetSourceId(sourceId);
449 }
450 
Grant() const451 void WebScreenCaptureRequestOhos::Grant() const
452 {
453     if (request_) {
454         request_->Agree(config_);
455     }
456 }
457 
GetXCoord() const458 int32_t ContextMenuParamOhos::GetXCoord() const
459 {
460     if (param_) {
461         return param_->GetXCoord();
462     }
463     return -1;
464 }
465 
GetYCoord() const466 int32_t ContextMenuParamOhos::GetYCoord() const
467 {
468     if (param_) {
469         return param_->GetYCoord();
470     }
471     return -1;
472 }
473 
GetLinkUrl() const474 std::string ContextMenuParamOhos::GetLinkUrl() const
475 {
476     if (param_) {
477         return param_->GetLinkUrl();
478     }
479     return "";
480 }
481 
GetUnfilteredLinkUrl() const482 std::string ContextMenuParamOhos::GetUnfilteredLinkUrl() const
483 {
484     if (param_) {
485         return param_->GetUnfilteredLinkUrl();
486     }
487     return "";
488 }
489 
GetSourceUrl() const490 std::string ContextMenuParamOhos::GetSourceUrl() const
491 {
492     if (param_) {
493         return param_->GetSourceUrl();
494     }
495     return "";
496 }
497 
HasImageContents() const498 bool ContextMenuParamOhos::HasImageContents() const
499 {
500     if (param_) {
501         return param_->HasImageContents();
502     }
503     return false;
504 }
505 
IsEditable() const506 bool ContextMenuParamOhos::IsEditable() const
507 {
508     if (param_) {
509         return param_->IsEditable();
510     }
511     return false;
512 }
513 
GetEditStateFlags() const514 int ContextMenuParamOhos::GetEditStateFlags() const
515 {
516     if (param_) {
517         return param_->GetEditStateFlags();
518     }
519     return OHOS::NWeb::NWebContextMenuParams::ContextMenuEditStateFlags::CM_ES_NONE;
520 }
521 
GetSourceType() const522 int ContextMenuParamOhos::GetSourceType() const
523 {
524     if (param_) {
525         return param_->GetSourceType();
526     }
527     return OHOS::NWeb::NWebContextMenuParams::ContextMenuSourceType::CM_ST_NONE;
528 }
529 
GetMediaType() const530 int ContextMenuParamOhos::GetMediaType() const
531 {
532     if (param_) {
533         return param_->GetMediaType();
534     }
535     return OHOS::NWeb::NWebContextMenuParams::ContextMenuMediaType::CM_MT_NONE;
536 }
537 
GetInputFieldType() const538 int ContextMenuParamOhos::GetInputFieldType() const
539 {
540     if (param_) {
541         return param_->GetInputFieldType();
542     }
543     return OHOS::NWeb::NWebContextMenuParams::ContextMenuInputFieldType::CM_IT_NONE;
544 }
545 
GetSelectionText() const546 std::string ContextMenuParamOhos::GetSelectionText() const
547 {
548     if (param_) {
549         return param_->GetSelectionText();
550     }
551     return "";
552 }
553 
GetImageRect(int32_t & x,int32_t & y,int32_t & width,int32_t & height) const554 void ContextMenuParamOhos::GetImageRect(int32_t& x, int32_t& y, int32_t& width, int32_t& height) const
555 {
556     if (param_) {
557         param_->GetImageRect(x, y, width, height);
558     }
559 }
560 
Cancel() const561 void ContextMenuResultOhos::Cancel() const
562 {
563     if (callback_) {
564         callback_->Cancel();
565     }
566 }
567 
CopyImage() const568 void ContextMenuResultOhos::CopyImage() const
569 {
570     if (callback_) {
571         callback_->Continue(CI_IMAGE_COPY, EF_NONE);
572     }
573 }
574 
Copy() const575 void ContextMenuResultOhos::Copy() const
576 {
577     if (callback_) {
578         callback_->Continue(CI_COPY, EF_NONE);
579     }
580 }
581 
Paste() const582 void ContextMenuResultOhos::Paste() const
583 {
584     if (callback_) {
585         callback_->Continue(CI_PASTE, EF_NONE);
586     }
587 }
588 
Cut() const589 void ContextMenuResultOhos::Cut() const
590 {
591     if (callback_) {
592         callback_->Continue(CI_CUT, EF_NONE);
593     }
594 }
595 
SelectAll() const596 void ContextMenuResultOhos::SelectAll() const
597 {
598     if (callback_) {
599         callback_->Continue(CI_SELECT_ALL, EF_NONE);
600     }
601 }
602 
SetWebController(int32_t id)603 void WebWindowNewHandlerOhos::SetWebController(int32_t id)
604 {
605     if (handler_) {
606         handler_->SetNWebHandlerById(id);
607     }
608 }
609 
IsFrist() const610 bool WebWindowNewHandlerOhos::IsFrist() const
611 {
612     if (handler_) {
613         return handler_->IsFrist();
614     }
615     return true;
616 }
617 
GetId() const618 int32_t WebWindowNewHandlerOhos::GetId() const
619 {
620     if (handler_) {
621         return handler_->GetId();
622     }
623     return -1;
624 }
625 
GetParentNWebId() const626 int32_t WebWindowNewHandlerOhos::GetParentNWebId() const
627 {
628     return parentNWebId_;
629 }
630 
Resend()631 void DataResubmittedOhos::Resend()
632 {
633     if (handler_) {
634         handler_->Resend();
635     }
636 }
637 
Cancel()638 void DataResubmittedOhos::Cancel()
639 {
640     if (handler_) {
641         handler_->Cancel();
642     }
643 }
644 
GetData()645 const void* FaviconReceivedOhos::GetData()
646 {
647     return data_;
648 }
649 
GetWidth()650 size_t FaviconReceivedOhos::GetWidth()
651 {
652     return width_;
653 }
654 
GetHeight()655 size_t FaviconReceivedOhos::GetHeight()
656 {
657     return height_;
658 }
659 
GetColorType()660 int FaviconReceivedOhos::GetColorType()
661 {
662     return static_cast<int>(colorType_);
663 }
664 
GetAlphaType()665 int FaviconReceivedOhos::GetAlphaType()
666 {
667     return static_cast<int>(alphaType_);
668 }
669 
NWebScreenLockCallbackImpl(const WeakPtr<PipelineBase> & context)670 NWebScreenLockCallbackImpl::NWebScreenLockCallbackImpl(const WeakPtr<PipelineBase>& context) : context_(context) {}
671 
Handle(bool key)672 void NWebScreenLockCallbackImpl::Handle(bool key)
673 {
674     TAG_LOGI(AceLogTag::ACE_WEB, "SetKeepScreenOn %{public}d", key);
675     auto weakContext = context_.Upgrade();
676     CHECK_NULL_VOID(weakContext);
677     auto window = weakContext->GetWindow();
678     CHECK_NULL_VOID(window);
679     window->SetKeepScreenOn(key);
680 }
681 
~WebDelegateObserver()682 WebDelegateObserver::~WebDelegateObserver() {}
683 
NotifyDestory()684 void WebDelegateObserver::NotifyDestory()
685 {
686     TAG_LOGI(AceLogTag::ACE_WEB, "NotifyDestory start");
687     if (delegate_) {
688         delegate_->UnRegisterScreenLockFunction();
689     }
690     auto context = context_.Upgrade();
691     if (!context) {
692         TAG_LOGD(AceLogTag::ACE_WEB, "NotifyDestory context is null, use EventHandler to destory");
693         auto currentHandler = OHOS::AppExecFwk::EventHandler::Current();
694         if (!currentHandler) {
695             TAG_LOGE(AceLogTag::ACE_WEB, "NWEB webdelegateObserver EventHandler currentHandler is null");
696             return;
697         }
698         currentHandler->PostTask(
699             [weak = WeakClaim(this), currentHandler = currentHandler]() {
700                 auto observer = weak.Upgrade();
701                 if (!observer) {
702                     TAG_LOGE(AceLogTag::ACE_WEB, "NotifyDestory EventHandler observer is null");
703                     return;
704                 }
705                 if (observer->delegate_) {
706                     TAG_LOGD(AceLogTag::ACE_WEB, "NotifyDestory EventHandler destorying delegate");
707                     observer->delegate_.Reset();
708                 }
709             },
710             DESTRUCT_DELAY_MILLISECONDS);
711         return;
712     }
713     auto taskExecutor = context->GetTaskExecutor();
714     if (!taskExecutor) {
715         TAG_LOGE(AceLogTag::ACE_WEB, "NotifyDestory TaskExecutor is null");
716         return;
717     }
718     taskExecutor->PostDelayedTask(
719         [weak = WeakClaim(this), taskExecutor = taskExecutor]() {
720             auto observer = weak.Upgrade();
721             if (!observer) {
722                 TAG_LOGE(AceLogTag::ACE_WEB, "NotifyDestory TaskExecutor observer is null");
723                 return;
724             }
725             if (observer->delegate_) {
726                 TAG_LOGD(AceLogTag::ACE_WEB, "NotifyDestory TaskExecutor destorying delegate");
727                 observer->delegate_.Reset();
728             }
729         },
730         TaskExecutor::TaskType::UI, DESTRUCT_DELAY_MILLISECONDS, "ArkUIWebNotifyDestory");
731 }
732 
UnRegisterScreenLockFunction()733 void WebDelegate::UnRegisterScreenLockFunction()
734 {
735     if (nweb_) {
736         nweb_->UnRegisterScreenLockFunction(instanceId_);
737     }
738 }
739 
OnAttachContext(const RefPtr<NG::PipelineContext> & context)740 void WebDelegateObserver::OnAttachContext(const RefPtr<NG::PipelineContext> &context)
741 {
742     context_ = context;
743 }
744 
OnDetachContext()745 void WebDelegateObserver::OnDetachContext()
746 {
747     context_ = nullptr;
748 }
749 
SetGestureEventResult(bool result)750 void GestureEventResultOhos::SetGestureEventResult(bool result)
751 {
752     if (result_) {
753         result_->SetGestureEventResult(result);
754         SetSendTask();
755         eventResult_ = result;
756     }
757 }
758 
OnAvoidAreaChanged(const OHOS::Rosen::AvoidArea avoidArea,OHOS::Rosen::AvoidAreaType type)759 void WebAvoidAreaChangedListener::OnAvoidAreaChanged(
760     const OHOS::Rosen::AvoidArea avoidArea, OHOS::Rosen::AvoidAreaType type)
761 {
762     if (auto delegate = webDelegate_.Upgrade()) {
763         delegate->OnAvoidAreaChanged(avoidArea, type);
764     }
765 }
766 
~WebDelegate()767 WebDelegate::~WebDelegate()
768 {
769     SetAccessibilityState(false);
770     OnNativeEmbedAllDestory();
771     ReleasePlatformResource();
772     if (IsDeviceTabletOr2in1() && GetWebOptimizationValue()) {
773         OHOS::Rosen::RSInterfaces::GetInstance().UnRegisterSurfaceOcclusionChangeCallback(surfaceNodeId_);
774     }
775     if (nweb_) {
776         nweb_->OnDestroy();
777     }
778     UnregisterSurfacePositionChangedCallback();
779     UnregisterAvoidAreaChangeListener();
780     UnRegisterConfigObserver();
781 }
782 
ReleasePlatformResource()783 void WebDelegate::ReleasePlatformResource()
784 {
785     Stop();
786     Release();
787 }
788 
Invoke(const std::string & origin,const bool & allow,const bool & retain)789 void WebGeolocationOhos::Invoke(const std::string& origin, const bool& allow, const bool& retain)
790 {
791     if (geolocationCallback_) {
792         geolocationCallback_->GeolocationCallbackInvoke(origin, allow, retain,
793             incognito_);
794     }
795 }
796 
Stop()797 void WebDelegate::Stop()
798 {
799     auto context = context_.Upgrade();
800     if (!context) {
801         return;
802     }
803     auto platformTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::PLATFORM);
804     if (platformTaskExecutor.IsRunOnCurrentThread()) {
805         UnregisterEvent();
806     } else {
807         platformTaskExecutor.PostTask([weak = WeakClaim(this)] {
808             auto delegate = weak.Upgrade();
809             if (delegate) {
810                 delegate->UnregisterEvent();
811             }
812         }, "ArkUIWebUnregisterEvent");
813     }
814 }
815 
UnregisterEvent()816 void WebDelegate::UnregisterEvent()
817 {
818     auto context = DynamicCast<PipelineContext>(context_.Upgrade());
819     if (!context) {
820         return;
821     }
822     auto resRegister = context->GetPlatformResRegister();
823     if (resRegister == nullptr) {
824         return;
825     }
826     resRegister->UnregisterEvent(MakeEventHash(WEB_EVENT_PAGESTART));
827     resRegister->UnregisterEvent(MakeEventHash(WEB_EVENT_PAGEFINISH));
828     resRegister->UnregisterEvent(MakeEventHash(WEB_EVENT_PAGEERROR));
829     resRegister->UnregisterEvent(MakeEventHash(WEB_EVENT_ROUTERPUSH));
830     resRegister->UnregisterEvent(MakeEventHash(WEB_EVENT_ONMESSAGE));
831 }
832 
SetRenderWeb(const WeakPtr<RenderWeb> & renderWeb)833 void WebDelegate::SetRenderWeb(const WeakPtr<RenderWeb>& renderWeb)
834 {
835     renderWeb_ = renderWeb;
836 }
837 
CreatePlatformResource(const Size & size,const Offset & position,const WeakPtr<PipelineContext> & context)838 void WebDelegate::CreatePlatformResource(
839     const Size& size, const Offset& position, const WeakPtr<PipelineContext>& context)
840 {
841     ReleasePlatformResource();
842     context_ = context;
843     CreatePluginResource(size, position, context);
844 
845     auto reloadCallback = [weak = WeakClaim(this)]() {
846         auto delegate = weak.Upgrade();
847         if (!delegate) {
848             return false;
849         }
850         delegate->Reload();
851         return true;
852     };
853     WebClient::GetInstance().RegisterReloadCallback(reloadCallback);
854 
855     auto updateUrlCallback = [weak = WeakClaim(this)](const std::string& url) {
856         auto delegate = weak.Upgrade();
857         if (!delegate) {
858             return false;
859         }
860         delegate->UpdateUrl(url);
861         return true;
862     };
863     WebClient::GetInstance().RegisterUpdageUrlCallback(updateUrlCallback);
864     InitWebEvent();
865 }
866 
LoadUrl(const std::string & url,const std::map<std::string,std::string> & httpHeaders)867 void WebDelegate::LoadUrl(const std::string& url, const std::map<std::string, std::string>& httpHeaders)
868 {
869     auto context = context_.Upgrade();
870     if (!context) {
871         return;
872     }
873     context->GetTaskExecutor()->PostTask(
874         [weak = WeakClaim(this), url, httpHeaders]() {
875             auto delegate = weak.Upgrade();
876             if (!delegate) {
877                 return;
878             }
879             if (delegate->nweb_) {
880                 delegate->nweb_->Load(
881                     const_cast<std::string&>(url), const_cast<std::map<std::string, std::string>&>(httpHeaders));
882             }
883         },
884         TaskExecutor::TaskType::PLATFORM, "ArkUIWebLoadUrl");
885 }
886 
887 #ifdef OHOS_STANDARD_SYSTEM
Backward()888 void WebDelegate::Backward()
889 {
890     auto context = context_.Upgrade();
891     if (!context) {
892         return;
893     }
894     context->GetTaskExecutor()->PostTask(
895         [weak = WeakClaim(this)]() {
896             auto delegate = weak.Upgrade();
897             if (!delegate) {
898                 return;
899             }
900             if (delegate->nweb_) {
901                 delegate->nweb_->NavigateBack();
902             }
903         },
904         TaskExecutor::TaskType::PLATFORM, "ArkUIWebNavigateBack");
905 }
906 
Forward()907 void WebDelegate::Forward()
908 {
909     auto context = context_.Upgrade();
910     if (!context) {
911         return;
912     }
913     context->GetTaskExecutor()->PostTask(
914         [weak = WeakClaim(this)]() {
915             auto delegate = weak.Upgrade();
916             if (!delegate) {
917                 return;
918             }
919             if (delegate->nweb_) {
920                 delegate->nweb_->NavigateForward();
921             }
922         },
923         TaskExecutor::TaskType::PLATFORM, "ArkUIWebNavigateForward");
924 }
925 
ClearHistory()926 void WebDelegate::ClearHistory()
927 {
928     auto context = context_.Upgrade();
929     if (!context) {
930         return;
931     }
932     context->GetTaskExecutor()->PostTask(
933         [weak = WeakClaim(this)]() {
934             auto delegate = weak.Upgrade();
935             if (!delegate) {
936                 return;
937             }
938             if (delegate->nweb_) {
939                 delegate->nweb_->DeleteNavigateHistory();
940             }
941         },
942         TaskExecutor::TaskType::PLATFORM, "ArkUIWebDeleteNavigateHistory");
943 }
944 
ClearSslCache()945 void WebDelegate::ClearSslCache()
946 {
947     auto context = context_.Upgrade();
948     if (!context) {
949         return;
950     }
951     context->GetTaskExecutor()->PostTask(
952         [weak = WeakClaim(this)]() {
953             auto delegate = weak.Upgrade();
954             if (!delegate) {
955                 return;
956             }
957             if (delegate->nweb_) {
958                 delegate->nweb_->ClearSslCache();
959             }
960         },
961         TaskExecutor::TaskType::PLATFORM, "ArkUIWebClearSslCache");
962 }
963 
ClearClientAuthenticationCache()964 void WebDelegate::ClearClientAuthenticationCache()
965 {
966     auto context = context_.Upgrade();
967     if (!context) {
968         return;
969     }
970     context->GetTaskExecutor()->PostTask(
971         [weak = WeakClaim(this)]() {
972             auto delegate = weak.Upgrade();
973             if (!delegate) {
974                 return;
975             }
976             if (delegate->nweb_) {
977                 delegate->nweb_->ClearClientAuthenticationCache();
978             }
979         },
980         TaskExecutor::TaskType::PLATFORM, "ArkUIWebClearClientAuthenticationCache");
981 }
982 
AccessStep(int32_t step)983 bool WebDelegate::AccessStep(int32_t step)
984 {
985     auto delegate = WeakClaim(this).Upgrade();
986     if (!delegate) {
987         return false;
988     }
989     if (delegate->nweb_) {
990         return delegate->nweb_->CanNavigateBackOrForward(step);
991     }
992     return false;
993 }
994 
BackOrForward(int32_t step)995 void WebDelegate::BackOrForward(int32_t step)
996 {
997     auto context = context_.Upgrade();
998     if (!context) {
999         return;
1000     }
1001 
1002     context->GetTaskExecutor()->PostTask(
1003         [weak = WeakClaim(this), step] {
1004             auto delegate = weak.Upgrade();
1005             if (!delegate) {
1006                 return;
1007             }
1008             if (delegate->nweb_) {
1009                 delegate->nweb_->NavigateBackOrForward(step);
1010             }
1011         },
1012         TaskExecutor::TaskType::PLATFORM, "ArkUIWebNavigateBackOrForward");
1013 }
1014 
AccessBackward()1015 bool WebDelegate::AccessBackward()
1016 {
1017     auto delegate = WeakClaim(this).Upgrade();
1018     if (!delegate) {
1019         return false;
1020     }
1021     if (delegate->nweb_) {
1022         return delegate->nweb_->IsNavigatebackwardAllowed();
1023     }
1024     return false;
1025 }
1026 
AccessForward()1027 bool WebDelegate::AccessForward()
1028 {
1029     auto delegate = WeakClaim(this).Upgrade();
1030     if (!delegate) {
1031         return false;
1032     }
1033     if (delegate->nweb_) {
1034         return delegate->nweb_->IsNavigateForwardAllowed();
1035     }
1036     return false;
1037 }
1038 
1039 #endif
1040 
ExecuteTypeScript(const std::string & jscode,const std::function<void (const std::string)> && callback)1041 void WebDelegate::ExecuteTypeScript(const std::string& jscode, const std::function<void(const std::string)>&& callback)
1042 {
1043     auto context = context_.Upgrade();
1044     if (!context) {
1045         return;
1046     }
1047     context->GetTaskExecutor()->PostTask(
1048         [weak = WeakClaim(this), jscode, callback]() {
1049             auto delegate = weak.Upgrade();
1050             if (!delegate) {
1051                 return;
1052             }
1053             if (delegate->nweb_) {
1054                 auto callbackImpl = std::make_shared<WebJavaScriptExecuteCallBack>(weak);
1055                 if (callbackImpl && callback) {
1056                     callbackImpl->SetCallBack([weak, func = std::move(callback)](std::string result) {
1057                         auto delegate = weak.Upgrade();
1058                         if (!delegate) {
1059                             return;
1060                         }
1061                         auto context = delegate->context_.Upgrade();
1062                         if (context) {
1063                             context->GetTaskExecutor()->PostTask(
1064                                 [callback = std::move(func), result]() { callback(result); },
1065                                 TaskExecutor::TaskType::JS, "ArkUIWebJavaScriptExecuteCallBack");
1066                         }
1067                     });
1068                 }
1069                 delegate->nweb_->ExecuteJavaScript(jscode, callbackImpl, false);
1070             }
1071         },
1072         TaskExecutor::TaskType::PLATFORM, "ArkUIWebExecuteJavaScript");
1073 }
1074 
LoadDataWithBaseUrl(const std::string & baseUrl,const std::string & data,const std::string & mimeType,const std::string & encoding,const std::string & historyUrl)1075 void WebDelegate::LoadDataWithBaseUrl(const std::string& baseUrl, const std::string& data, const std::string& mimeType,
1076     const std::string& encoding, const std::string& historyUrl)
1077 {
1078     auto context = context_.Upgrade();
1079     if (!context) {
1080         return;
1081     }
1082     context->GetTaskExecutor()->PostTask(
1083         [weak = WeakClaim(this), baseUrl, data, mimeType, encoding, historyUrl]() {
1084             auto delegate = weak.Upgrade();
1085             if (!delegate) {
1086                 return;
1087             }
1088             if (delegate->nweb_) {
1089                 if (baseUrl.empty() && historyUrl.empty()) {
1090                     delegate->nweb_->LoadWithData(data, mimeType, encoding);
1091                 } else {
1092                     delegate->nweb_->LoadWithDataAndBaseUrl(baseUrl, data, mimeType, encoding, historyUrl);
1093                 }
1094             }
1095         },
1096         TaskExecutor::TaskType::PLATFORM, "ArkUIWebLoadDataWithBaseUrl");
1097 }
1098 
LoadDataWithRichText()1099 bool WebDelegate::LoadDataWithRichText()
1100 {
1101     auto context = context_.Upgrade();
1102     if (!context) {
1103         return false;
1104     }
1105 #ifdef NG_BUILD
1106     auto webPattern = webPattern_.Upgrade();
1107     CHECK_NULL_RETURN(webPattern, false);
1108     auto webData = webPattern->GetWebData();
1109     CHECK_NULL_RETURN(webData, false);
1110     const std::string& data = webData.value();
1111     if (data.empty()) {
1112         return false;
1113     }
1114 
1115     context->GetTaskExecutor()->PostTask(
1116         [weak = WeakClaim(this), data]() {
1117             auto delegate = weak.Upgrade();
1118             if (!delegate) {
1119                 return;
1120             }
1121             if (delegate->nweb_) {
1122                 delegate->nweb_->LoadWithDataAndBaseUrl("resource://rawfile", data, "", "", "");
1123             }
1124         },
1125         TaskExecutor::TaskType::PLATFORM, "ArkUIWebLoadDataWithRichText");
1126     return true;
1127 #else
1128     if (Container::IsCurrentUseNewPipeline()) {
1129         auto webPattern = webPattern_.Upgrade();
1130         CHECK_NULL_RETURN(webPattern, false);
1131         auto webData = webPattern->GetWebData();
1132         CHECK_NULL_RETURN(webData, false);
1133         const std::string& data = webData.value();
1134         if (data.empty()) {
1135             return false;
1136         }
1137 
1138         context->GetTaskExecutor()->PostTask(
1139             [weak = WeakClaim(this), data]() {
1140                 auto delegate = weak.Upgrade();
1141                 if (!delegate) {
1142                     return;
1143                 }
1144                 if (delegate->nweb_) {
1145                     delegate->nweb_->LoadWithDataAndBaseUrl("resource://rawfile", data, "", "", "");
1146                 }
1147             },
1148             TaskExecutor::TaskType::PLATFORM, "ArkUIWebLoadDataWithRichText");
1149         return true;
1150     }
1151 
1152     auto webCom = webComponent_.Upgrade();
1153     CHECK_NULL_RETURN(webCom, false);
1154     if (webCom->GetData().empty()) {
1155         return false;
1156     }
1157     const std::string& data = webCom->GetData();
1158     context->GetTaskExecutor()->PostTask(
1159         [weak = WeakClaim(this), data]() {
1160             auto delegate = weak.Upgrade();
1161             if (!delegate) {
1162                 return;
1163             }
1164             if (delegate->nweb_) {
1165                 delegate->nweb_->LoadWithDataAndBaseUrl("resource://rawfile", data, "", "", "");
1166             }
1167         },
1168         TaskExecutor::TaskType::PLATFORM, "ArkUIWebLoadDataWithRichText");
1169     return true;
1170 #endif
1171 }
1172 
Refresh()1173 void WebDelegate::Refresh()
1174 {
1175     auto context = context_.Upgrade();
1176     if (!context) {
1177         return;
1178     }
1179     context->GetTaskExecutor()->PostTask(
1180         [weak = WeakClaim(this)]() {
1181             auto delegate = weak.Upgrade();
1182             if (!delegate) {
1183                 return;
1184             }
1185             if (delegate->nweb_) {
1186                 delegate->nweb_->Reload();
1187             }
1188         },
1189         TaskExecutor::TaskType::PLATFORM, "ArkUIWebRefresh");
1190 }
1191 
StopLoading()1192 void WebDelegate::StopLoading()
1193 {
1194     auto context = context_.Upgrade();
1195     if (!context) {
1196         return;
1197     }
1198     context->GetTaskExecutor()->PostTask(
1199         [weak = WeakClaim(this)]() {
1200             auto delegate = weak.Upgrade();
1201             if (!delegate) {
1202                 return;
1203             }
1204             if (delegate->nweb_) {
1205                 delegate->nweb_->Stop();
1206             }
1207         },
1208         TaskExecutor::TaskType::PLATFORM, "ArkUIWebStopLoading");
1209 }
1210 
AddJavascriptInterface(const std::string & objectName,const std::vector<std::string> & methodList)1211 void WebDelegate::AddJavascriptInterface(const std::string& objectName, const std::vector<std::string>& methodList)
1212 {
1213     auto context = context_.Upgrade();
1214     if (!context) {
1215         return;
1216     }
1217     context->GetTaskExecutor()->PostTask(
1218         [weak = WeakClaim(this), objectName, methodList]() {
1219             auto delegate = weak.Upgrade();
1220             if (!delegate) {
1221                 return;
1222             }
1223             if (delegate->nweb_) {
1224                 // Async methods list is empty
1225                 std::vector<std::string> asyncMethodList;
1226                 std::string permission;
1227                 // webcontroller not support object, so the object_id param
1228                 // assign error code
1229                 delegate->nweb_->RegisterArkJSfunctionV2(
1230                     objectName, methodList, asyncMethodList,
1231                     static_cast<int32_t>(JavaScriptObjIdErrorCode::WEBCONTROLLERERROR),
1232                     permission);
1233             }
1234         },
1235         TaskExecutor::TaskType::PLATFORM, "ArkUIWebAddJsInterface");
1236 }
RemoveJavascriptInterface(const std::string & objectName,const std::vector<std::string> & methodList)1237 void WebDelegate::RemoveJavascriptInterface(const std::string& objectName, const std::vector<std::string>& methodList)
1238 {
1239     auto context = context_.Upgrade();
1240     if (!context) {
1241         return;
1242     }
1243     context->GetTaskExecutor()->PostTask(
1244         [weak = WeakClaim(this), objectName, methodList]() {
1245             auto delegate = weak.Upgrade();
1246             if (!delegate) {
1247                 return;
1248             }
1249             if (delegate->nweb_) {
1250                 delegate->nweb_->UnregisterArkJSfunction(objectName, methodList);
1251             }
1252         },
1253         TaskExecutor::TaskType::PLATFORM, "ArkUIWebRemoveJsInterface");
1254 }
1255 
SetWebViewJavaScriptResultCallBack(const WebController::JavaScriptCallBackImpl && javaScriptCallBackImpl)1256 void WebDelegate::SetWebViewJavaScriptResultCallBack(
1257     const WebController::JavaScriptCallBackImpl&& javaScriptCallBackImpl)
1258 {
1259     auto context = context_.Upgrade();
1260     if (!context) {
1261         return;
1262     }
1263 
1264     context->GetTaskExecutor()->PostTask(
1265         [weak = WeakClaim(this), javaScriptCallBackImpl]() {
1266             auto delegate = weak.Upgrade();
1267             if (delegate == nullptr || delegate->nweb_ == nullptr) {
1268                 return;
1269             }
1270             auto webJSResultCallBack = std::make_shared<WebJavaScriptResultCallBack>(weak);
1271             if (webJSResultCallBack) {
1272                 webJSResultCallBack->SetJavaScriptCallBack(std::move(javaScriptCallBackImpl));
1273                 delegate->nweb_->SetNWebJavaScriptResultCallBack(webJSResultCallBack);
1274             }
1275         },
1276         TaskExecutor::TaskType::PLATFORM, "ArkUIWebSetJsResultCallBack");
1277 }
1278 
CreateWebMessagePorts(std::vector<RefPtr<WebMessagePort>> & ports)1279 void WebDelegate::CreateWebMessagePorts(std::vector<RefPtr<WebMessagePort>>& ports)
1280 {
1281     if (nweb_) {
1282         std::vector<std::string> portStr = nweb_->CreateWebMessagePorts();
1283         RefPtr<WebMessagePort> port0 = AceType::MakeRefPtr<WebMessagePortOhos>(WeakClaim(this));
1284         RefPtr<WebMessagePort> port1 = AceType::MakeRefPtr<WebMessagePortOhos>(WeakClaim(this));
1285         port0->SetPortHandle(portStr[0]);
1286         port1->SetPortHandle(portStr[1]);
1287         ports.push_back(port0);
1288         ports.push_back(port1);
1289     }
1290 }
1291 
PostWebMessage(std::string & message,std::vector<RefPtr<WebMessagePort>> & ports,std::string & uri)1292 void WebDelegate::PostWebMessage(std::string& message, std::vector<RefPtr<WebMessagePort>>& ports, std::string& uri)
1293 {
1294     if (nweb_) {
1295         std::vector<std::string> sendPorts;
1296         for (RefPtr<WebMessagePort> port : ports) {
1297             sendPorts.push_back(port->GetPortHandle());
1298         }
1299         nweb_->PostWebMessage(message, sendPorts, uri);
1300     }
1301 }
1302 
ClosePort(std::string & port)1303 void WebDelegate::ClosePort(std::string& port)
1304 {
1305     if (nweb_) {
1306         nweb_->ClosePort(port);
1307     }
1308 }
1309 
PostPortMessage(std::string & port,std::string & data)1310 void WebDelegate::PostPortMessage(std::string& port, std::string& data)
1311 {
1312     if (nweb_) {
1313         auto webMsg = std::make_shared<OHOS::NWeb::NWebMessage>(NWebValue::Type::NONE);
1314         webMsg->SetType(NWebValue::Type::STRING);
1315         webMsg->SetString(data);
1316         nweb_->PostPortMessage(port, webMsg);
1317     }
1318 }
1319 
SetPortMessageCallback(std::string & port,std::function<void (const std::string &)> && callback)1320 void WebDelegate::SetPortMessageCallback(std::string& port, std::function<void(const std::string&)>&& callback)
1321 {
1322     if (nweb_) {
1323         auto callbackImpl = std::make_shared<WebMessageValueCallBackImpl>(WeakClaim(this));
1324         if (callbackImpl && callback) {
1325             callbackImpl->SetCallBack([weak = WeakClaim(this), func = std::move(callback)](std::string result) {
1326                 auto delegate = weak.Upgrade();
1327                 if (!delegate) {
1328                     return;
1329                 }
1330                 auto context = delegate->context_.Upgrade();
1331                 if (context) {
1332                     context->GetTaskExecutor()->PostTask(
1333                         [callback = std::move(func), result]() { callback(result); },
1334                         TaskExecutor::TaskType::JS, "ArkUIWebSetPortMessageCallback");
1335                 }
1336             });
1337         }
1338         nweb_->SetPortMessageCallback(port, callbackImpl);
1339     }
1340 }
1341 
RequestFocus(OHOS::NWeb::NWebFocusSource source)1342 bool WebDelegate::RequestFocus(OHOS::NWeb::NWebFocusSource source)
1343 {
1344     auto context = context_.Upgrade();
1345     CHECK_NULL_RETURN(context, false);
1346     bool result = false;
1347     context->GetTaskExecutor()->PostSyncTask(
1348         [weak = WeakClaim(this), &result, source]() {
1349             auto delegate = weak.Upgrade();
1350             CHECK_NULL_VOID(delegate);
1351 
1352             if (Container::IsCurrentUseNewPipeline()) {
1353                 auto webPattern = delegate->webPattern_.Upgrade();
1354                 CHECK_NULL_VOID(webPattern);
1355                 if (webPattern->IsFocus()) {
1356                     result = true;
1357                     return;
1358                 }
1359                 auto eventHub = webPattern->GetWebEventHub();
1360                 CHECK_NULL_VOID(eventHub);
1361                 auto focusHub = eventHub->GetOrCreateFocusHub();
1362                 CHECK_NULL_VOID(focusHub);
1363                 if (source == OHOS::NWeb::NWebFocusSource::FOCUS_SOURCE_NAVIGATION &&
1364                     webPattern->IsDefaultFocusNodeExist() && !focusHub->IsDefaultFocus()) {
1365                     TAG_LOGI(AceLogTag::ACE_WEB, "there are other default focusNodes, web don't focus on navigation");
1366                     result = false;
1367                     return;
1368                 }
1369 
1370                 auto host = webPattern->GetHost();
1371                 CHECK_NULL_VOID(host);
1372                 if (host->IsOnMainTree()) {
1373                     focusHub->RequestFocus();
1374                     result = false;
1375                 }
1376                 return;
1377             }
1378 
1379             auto webCom = delegate->webComponent_.Upgrade();
1380             CHECK_NULL_VOID(webCom);
1381             result = webCom->RequestFocus();
1382         },
1383         TaskExecutor::TaskType::PLATFORM, "ArkUIWebRequestFocus");
1384     return result;
1385 }
1386 
SearchAllAsync(const std::string & searchStr)1387 void WebDelegate::SearchAllAsync(const std::string& searchStr)
1388 {
1389     auto context = context_.Upgrade();
1390     if (!context) {
1391         return;
1392     }
1393     context->GetTaskExecutor()->PostTask(
1394         [weak = WeakClaim(this), searchStr]() {
1395             auto delegate = weak.Upgrade();
1396             if (!delegate) {
1397                 return;
1398             }
1399             if (delegate->nweb_) {
1400                 delegate->nweb_->FindAllAsync(searchStr);
1401             }
1402         },
1403         TaskExecutor::TaskType::PLATFORM, "ArkUIWebSearchAllAsync");
1404 }
1405 
ClearMatches()1406 void WebDelegate::ClearMatches()
1407 {
1408     auto context = context_.Upgrade();
1409     if (!context) {
1410         return;
1411     }
1412     context->GetTaskExecutor()->PostTask(
1413         [weak = WeakClaim(this)]() {
1414             auto delegate = weak.Upgrade();
1415             if (!delegate) {
1416                 return;
1417             }
1418             if (delegate->nweb_) {
1419                 delegate->nweb_->ClearMatches();
1420             }
1421         },
1422         TaskExecutor::TaskType::PLATFORM, "ArkUIWebClearMatches");
1423 }
1424 
SearchNext(bool forward)1425 void WebDelegate::SearchNext(bool forward)
1426 {
1427     auto context = context_.Upgrade();
1428     if (!context) {
1429         return;
1430     }
1431     context->GetTaskExecutor()->PostTask(
1432         [weak = WeakClaim(this), forward]() {
1433             auto delegate = weak.Upgrade();
1434             if (!delegate) {
1435                 return;
1436             }
1437             if (delegate->nweb_) {
1438                 delegate->nweb_->FindNext(forward);
1439             }
1440         },
1441         TaskExecutor::TaskType::PLATFORM, "ArkUIWebSearchNext");
1442 }
1443 
ConverToWebHitTestType(int hitType)1444 int WebDelegate::ConverToWebHitTestType(int hitType)
1445 {
1446     WebHitTestType webHitType;
1447     switch (hitType) {
1448         case OHOS::NWeb::HitTestResult::UNKNOWN_TYPE:
1449             webHitType = WebHitTestType::UNKNOWN;
1450             break;
1451         case OHOS::NWeb::HitTestResult::ANCHOR_TYPE:
1452             webHitType = WebHitTestType::HTTP;
1453             break;
1454         case OHOS::NWeb::HitTestResult::PHONE_TYPE:
1455             webHitType = WebHitTestType::PHONE;
1456             break;
1457         case OHOS::NWeb::HitTestResult::GEO_TYPE:
1458             webHitType = WebHitTestType::MAP;
1459             break;
1460         case OHOS::NWeb::HitTestResult::EMAIL_TYPE:
1461             webHitType = WebHitTestType::EMAIL;
1462             break;
1463         case OHOS::NWeb::HitTestResult::IMAGE_TYPE:
1464             webHitType = WebHitTestType::IMG;
1465             break;
1466         case OHOS::NWeb::HitTestResult::IMAGE_ANCHOR_TYPE:
1467             webHitType = WebHitTestType::HTTP_IMG;
1468             break;
1469         case OHOS::NWeb::HitTestResult::SRC_ANCHOR_TYPE:
1470             webHitType = WebHitTestType::HTTP;
1471             break;
1472         case OHOS::NWeb::HitTestResult::SRC_IMAGE_ANCHOR_TYPE:
1473             webHitType = WebHitTestType::HTTP_IMG;
1474             break;
1475         case OHOS::NWeb::HitTestResult::EDIT_TEXT_TYPE:
1476             webHitType = WebHitTestType::EDIT;
1477             break;
1478         default:
1479             webHitType = WebHitTestType::UNKNOWN;
1480             break;
1481     }
1482     return static_cast<int>(webHitType);
1483 }
1484 
GetHitTestResult()1485 int WebDelegate::GetHitTestResult()
1486 {
1487     if (nweb_) {
1488         std::shared_ptr<OHOS::NWeb::HitTestResult> nwebResult = nweb_->GetHitTestResult();
1489         if (nwebResult) {
1490             return ConverToWebHitTestType(nwebResult->GetType());
1491         }
1492         return ConverToWebHitTestType(OHOS::NWeb::HitTestResult::UNKNOWN_TYPE);
1493     }
1494     return static_cast<int>(WebHitTestType::UNKNOWN);
1495 }
1496 
GetHitTestValue(HitTestResult & result)1497 void WebDelegate::GetHitTestValue(HitTestResult& result)
1498 {
1499     if (nweb_) {
1500         std::shared_ptr<OHOS::NWeb::HitTestResult> nwebResult = nweb_->GetHitTestResult();
1501         if (nwebResult) {
1502             result.SetExtraData(nwebResult->GetExtra());
1503             result.SetHitType(ConverToWebHitTestType(nwebResult->GetType()));
1504         } else {
1505             result.SetHitType(ConverToWebHitTestType(OHOS::NWeb::HitTestResult::UNKNOWN_TYPE));
1506         }
1507     }
1508 }
1509 
GetPageHeight()1510 int WebDelegate::GetPageHeight()
1511 {
1512     if (nweb_) {
1513         return nweb_->ContentHeight();
1514     }
1515     return 0;
1516 }
1517 
GetWebId()1518 int WebDelegate::GetWebId()
1519 {
1520     if (nweb_) {
1521         return nweb_->GetWebId();
1522     }
1523     return -1;
1524 }
1525 
GetTitle()1526 std::string WebDelegate::GetTitle()
1527 {
1528     if (nweb_) {
1529         return nweb_->Title();
1530     }
1531     return "";
1532 }
1533 
GetDefaultUserAgent()1534 std::string WebDelegate::GetDefaultUserAgent()
1535 {
1536     if (!nweb_) {
1537         return "";
1538     }
1539     std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_->GetPreference();
1540     if (!setting) {
1541         return "";
1542     }
1543     return setting->DefaultUserAgent();
1544 }
1545 
SaveCookieSync()1546 bool WebDelegate::SaveCookieSync()
1547 {
1548     if (cookieManager_) {
1549         return cookieManager_->Store();
1550     }
1551     return false;
1552 }
1553 
SetCookie(const std::string & url,const std::string & value,bool incognitoMode)1554 bool WebDelegate::SetCookie(const std::string& url,
1555                             const std::string& value,
1556                             bool incognitoMode)
1557 {
1558     if (cookieManager_) {
1559         return cookieManager_->SetCookie(url, value, incognitoMode);
1560     }
1561     return false;
1562 }
1563 
GetCookie(const std::string & url,bool incognitoMode) const1564 std::string WebDelegate::GetCookie(const std::string& url,
1565                                    bool incognitoMode) const
1566 {
1567     if (cookieManager_) {
1568         bool isValid = true;
1569         return cookieManager_->ReturnCookie(url, isValid, incognitoMode);
1570     }
1571     return "";
1572 }
1573 
DeleteEntirelyCookie(bool incognitoMode)1574 void WebDelegate::DeleteEntirelyCookie(bool incognitoMode)
1575 {
1576     if (cookieManager_) {
1577         cookieManager_->DeleteCookieEntirely(nullptr, incognitoMode);
1578     }
1579 }
1580 
CreatePluginResource(const Size & size,const Offset & position,const WeakPtr<PipelineContext> & context)1581 void WebDelegate::CreatePluginResource(
1582     const Size& size, const Offset& position, const WeakPtr<PipelineContext>& context)
1583 {
1584     state_ = State::CREATING;
1585     auto webCom = webComponent_.Upgrade();
1586     if (!webCom) {
1587         state_ = State::CREATEFAILED;
1588         OnError(NTC_ERROR, "fail to call WebDelegate::Create due to webComponent is null");
1589         return;
1590     }
1591 
1592     auto pipelineContext = context.Upgrade();
1593     if (!pipelineContext) {
1594         state_ = State::CREATEFAILED;
1595         OnError(NTC_ERROR, "fail to call WebDelegate::Create due to context is null");
1596         return;
1597     }
1598     context_ = context;
1599     auto platformTaskExecutor =
1600         SingleTaskExecutor::Make(pipelineContext->GetTaskExecutor(), TaskExecutor::TaskType::PLATFORM);
1601     auto resRegister = pipelineContext->GetPlatformResRegister();
1602     auto weakRes = AceType::WeakClaim(AceType::RawPtr(resRegister));
1603     platformTaskExecutor.PostTask([weakWeb = AceType::WeakClaim(this), weakRes, size, position] {
1604         auto webDelegate = weakWeb.Upgrade();
1605         if (webDelegate == nullptr) {
1606             return;
1607         }
1608         auto webCom = webDelegate->webComponent_.Upgrade();
1609         if (!webCom) {
1610             webDelegate->OnError(NTC_ERROR, "fail to call WebDelegate::SetSrc PostTask");
1611             return;
1612         }
1613         auto resRegister = weakRes.Upgrade();
1614         if (!resRegister) {
1615             if (webDelegate->onError_) {
1616                 webDelegate->onError_(WEB_ERROR_CODE_CREATEFAIL, WEB_ERROR_MSG_CREATEFAIL);
1617             }
1618             return;
1619         }
1620         auto context = webDelegate->context_.Upgrade();
1621         if (!context) {
1622             return;
1623         }
1624 
1625         std::string pageUrl;
1626         int32_t pageId;
1627         OHOS::Ace::Framework::DelegateClient::GetInstance().GetWebPageUrl(pageUrl, pageId);
1628 
1629         std::stringstream paramStream;
1630         paramStream << NTC_PARAM_WEB << WEB_PARAM_EQUALS << webDelegate->id_ << WEB_PARAM_AND << NTC_PARAM_WIDTH
1631                     << WEB_PARAM_EQUALS << size.Width() * context->GetViewScale() << WEB_PARAM_AND << NTC_PARAM_HEIGHT
1632                     << WEB_PARAM_EQUALS << size.Height() * context->GetViewScale() << WEB_PARAM_AND << NTC_PARAM_LEFT
1633                     << WEB_PARAM_EQUALS << position.GetX() * context->GetViewScale() << WEB_PARAM_AND << NTC_PARAM_TOP
1634                     << WEB_PARAM_EQUALS << position.GetY() * context->GetViewScale() << WEB_PARAM_AND << NTC_PARAM_SRC
1635                     << WEB_PARAM_EQUALS << webCom->GetSrc() << WEB_PARAM_AND << NTC_PARAM_PAGE_URL << WEB_PARAM_EQUALS
1636                     << pageUrl;
1637 
1638         std::string param = paramStream.str();
1639         webDelegate->id_ = resRegister->CreateResource(WEB_CREATE, param);
1640         if (webDelegate->id_ == WEB_INVALID_ID) {
1641             if (webDelegate->onError_) {
1642                 webDelegate->onError_(WEB_ERROR_CODE_CREATEFAIL, WEB_ERROR_MSG_CREATEFAIL);
1643             }
1644             return;
1645         }
1646         webDelegate->state_ = State::CREATED;
1647         webDelegate->hash_ = webDelegate->MakeResourceHash();
1648         webDelegate->RegisterWebEvent();
1649         webDelegate->BindRouterBackMethod();
1650         webDelegate->BindPopPageSuccessMethod();
1651         webDelegate->BindIsPagePathInvalidMethod();
1652     }, "ArkUIWebCreatePluginResource");
1653 }
1654 
InitWebEvent()1655 void WebDelegate::InitWebEvent()
1656 {
1657     auto webCom = webComponent_.Upgrade();
1658     if (!webCom) {
1659         state_ = State::CREATEFAILED;
1660         OnError(NTC_ERROR, "fail to call WebDelegate::Create due to webComponent is null");
1661         return;
1662     }
1663     auto context = DynamicCast<PipelineContext>(context_.Upgrade());
1664     if (!context) {
1665         state_ = State::CREATEFAILED;
1666         OnError(NTC_ERROR, "fail to call WebDelegate::Create due to webComponent is null");
1667         return;
1668     }
1669     CHECK_NULL_VOID(context);
1670     if (!webCom->GetPageStartedEventId().IsEmpty()) {
1671         onPageStarted_ = AceAsyncEvent<void(const std::string&)>::Create(webCom->GetPageStartedEventId(), context);
1672     }
1673     if (!webCom->GetPageFinishedEventId().IsEmpty()) {
1674         onPageFinished_ = AceAsyncEvent<void(const std::string&)>::Create(webCom->GetPageFinishedEventId(), context);
1675     }
1676     if (!webCom->GetPageErrorEventId().IsEmpty()) {
1677         onPageError_ = AceAsyncEvent<void(const std::string&)>::Create(webCom->GetPageErrorEventId(), context);
1678     }
1679     if (!webCom->GetMessageEventId().IsEmpty()) {
1680         onMessage_ = AceAsyncEvent<void(const std::string&)>::Create(webCom->GetMessageEventId(), context);
1681     }
1682 }
1683 
1684 #ifdef OHOS_STANDARD_SYSTEM
ShowWebView()1685 void WebDelegate::ShowWebView()
1686 {
1687     if (window_) {
1688         window_->Show();
1689     }
1690 
1691     OnActive();
1692     OnWebviewShow();
1693 }
1694 
HideWebView()1695 void WebDelegate::HideWebView()
1696 {
1697     if (window_) {
1698         window_->Hide();
1699     }
1700 
1701     OnInactive();
1702     OnWebviewHide();
1703 }
1704 
InitOHOSWeb(const RefPtr<PipelineBase> & context,const RefPtr<NG::RenderSurface> & surface)1705 void WebDelegate::InitOHOSWeb(const RefPtr<PipelineBase>& context, const RefPtr<NG::RenderSurface>& surface)
1706 {
1707 #ifdef ENABLE_ROSEN_BACKEND
1708     CHECK_NULL_VOID(context);
1709     auto rosenRenderSurface = DynamicCast<NG::RosenRenderSurface>(surface);
1710     if (!rosenRenderSurface) {
1711         if (PrepareInitOHOSWeb(context)) {
1712             if (!isCreateWebView_) {
1713 #ifndef ENABLE_ROSEN_BACKEND
1714                 InitWebViewWithWindow();
1715                 isCreateWebView_ = true;
1716 #endif
1717             }
1718         }
1719         return;
1720     }
1721     if (renderMode_ == static_cast<int32_t>(RenderMode::SYNC_RENDER)) {
1722         renderSurface_ = rosenRenderSurface;
1723     }
1724     SetSurface(rosenRenderSurface->GetSurface());
1725     InitOHOSWeb(context);
1726 #endif
1727 }
1728 
PrepareInitOHOSWeb(const WeakPtr<PipelineBase> & context)1729 bool WebDelegate::PrepareInitOHOSWeb(const WeakPtr<PipelineBase>& context)
1730 {
1731     ACE_SCOPED_TRACE("PrepareInitOHOSWeb");
1732 
1733     state_ = State::CREATING;
1734     // obtain hap data path
1735     auto container = Container::Current();
1736     if (container == nullptr) {
1737         return false;
1738     }
1739     const std::string& bundlePath = container->GetBundlePath();
1740     const std::string& filesDataPath = container->GetFilesDataPath();
1741     std::string baseDir = "base";
1742     std::size_t baseIndex = filesDataPath.find(baseDir);
1743     if (baseIndex == std::string::npos) {
1744         return false;
1745     }
1746     std::string dataPath = filesDataPath.substr(0, baseIndex + baseDir.length());
1747     bundlePath_ = bundlePath;
1748     bundleDataPath_ = dataPath;
1749     hapPath_ = container->GetWebHapPath();
1750     // get app temp dir
1751     tempDir_ = container->GetTempDir();
1752     // load webview so
1753     OHOS::NWeb::NWebHelper::Instance().SetBundlePath(bundlePath_);
1754     if (!OHOS::NWeb::NWebHelper::Instance().Init()) {
1755         return false;
1756     }
1757     auto webCom = webComponent_.Upgrade();
1758     auto webPattern = webPattern_.Upgrade();
1759     auto eventHub = webPattern ? webPattern->GetWebEventHub() : nullptr;
1760     auto useNewPipe = Container::IsCurrentUseNewPipeline();
1761     if (useNewPipe && !webPattern && !eventHub) {
1762         return false;
1763     }
1764     if (!useNewPipe && !webCom) {
1765         return false;
1766     }
1767     incognitoMode_ =
1768         useNewPipe ? webPattern->GetIncognitoMode() : webCom->GetIncognitoMode();
1769     auto sharedRenderProcessToken =
1770         useNewPipe ? webPattern->GetSharedRenderProcessToken() : webCom->GetSharedRenderProcessToken();
1771     sharedRenderProcessToken_ = sharedRenderProcessToken ? sharedRenderProcessToken.value() : "";
1772     context_ = context;
1773     RegisterSurfacePositionChangedCallback();
1774     auto pipelineContext = context.Upgrade();
1775     if (!pipelineContext) {
1776         return false;
1777     }
1778     state_ = State::CREATED;
1779 
1780     SetWebCallBack();
1781     if (!pipelineContext->GetIsDeclarative()) {
1782         RegisterOHOSWebEventAndMethord();
1783     } else {
1784         auto oldContext = DynamicCast<PipelineContext>(pipelineContext);
1785 
1786         onPageFinishedV2_ = useNewPipe ? eventHub->GetOnPageFinishedEvent()
1787                                        : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1788                                            webCom->GetPageFinishedEventId(), oldContext);
1789         onPageStartedV2_ = useNewPipe ? eventHub->GetOnPageStartedEvent()
1790                                       : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1791                                           webCom->GetPageStartedEventId(), oldContext);
1792         onTitleReceiveV2_ = useNewPipe ? eventHub->GetOnTitleReceiveEvent()
1793                                        : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1794                                            webCom->GetTitleReceiveEventId(), oldContext);
1795         onFullScreenExitV2_ = useNewPipe ? eventHub->GetOnFullScreenExitEvent()
1796                                          : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1797                                              webCom->GetOnFullScreenExitEventId(), oldContext);
1798         onGeolocationHideV2_ = useNewPipe ? eventHub->GetOnGeolocationHideEvent()
1799                                           : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1800                                               webCom->GetGeolocationHideEventId(), oldContext);
1801         onGeolocationShowV2_ = useNewPipe ? eventHub->GetOnGeolocationShowEvent()
1802                                           : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1803                                               webCom->GetGeolocationShowEventId(), oldContext);
1804         onErrorReceiveV2_ = useNewPipe ? eventHub->GetOnErrorReceiveEvent()
1805                                        : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1806                                            webCom->GetPageErrorEventId(), oldContext);
1807         onHttpErrorReceiveV2_ = useNewPipe ? eventHub->GetOnHttpErrorReceiveEvent()
1808                                            : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1809                                                webCom->GetHttpErrorEventId(), oldContext);
1810         onRequestFocusV2_ = useNewPipe ? eventHub->GetOnRequestFocusEvent()
1811                                        : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1812                                            webCom->GetRequestFocusEventId(), oldContext);
1813         onDownloadStartV2_ = useNewPipe ? eventHub->GetOnDownloadStartEvent()
1814                                         : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1815                                             webCom->GetDownloadStartEventId(), oldContext);
1816         onRenderExitedV2_ = useNewPipe ? eventHub->GetOnRenderExitedEvent()
1817                                        : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1818                                            webCom->GetRenderExitedId(), oldContext);
1819         onRefreshAccessedHistoryV2_ = useNewPipe ? eventHub->GetOnRefreshAccessedHistoryEvent()
1820                                                  : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1821                                                      webCom->GetRefreshAccessedHistoryId(), oldContext);
1822         onResourceLoadV2_ = useNewPipe ? eventHub->GetOnResourceLoadEvent()
1823                                        : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1824                                            webCom->GetResourceLoadId(), oldContext);
1825         onScaleChangeV2_ = useNewPipe ? eventHub->GetOnScaleChangeEvent()
1826                                       : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1827                                           webCom->GetScaleChangeId(), oldContext);
1828         onPermissionRequestV2_ = useNewPipe ? eventHub->GetOnPermissionRequestEvent()
1829                                             : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1830                                                 webCom->GetPermissionRequestEventId(), oldContext);
1831         onSearchResultReceiveV2_ = useNewPipe ? eventHub->GetOnSearchResultReceiveEvent()
1832                                               : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1833                                                   webCom->GetSearchResultReceiveEventId(), oldContext);
1834         onScrollV2_ = useNewPipe ? eventHub->GetOnScrollEvent()
1835                                  : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1836                                      webCom->GetScrollId(), oldContext);
1837         onWindowExitV2_ = useNewPipe ? eventHub->GetOnWindowExitEvent()
1838                                      : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1839                                          webCom->GetWindowExitEventId(), oldContext);
1840         onPageVisibleV2_ = useNewPipe ? eventHub->GetOnPageVisibleEvent() : nullptr;
1841         onTouchIconUrlV2_ = useNewPipe ? eventHub->GetOnTouchIconUrlEvent() : nullptr;
1842         onAudioStateChangedV2_ = GetAudioStateChangedCallback(useNewPipe, eventHub);
1843         onFirstContentfulPaintV2_ = useNewPipe ? eventHub->GetOnFirstContentfulPaintEvent() : nullptr;
1844         OnFirstMeaningfulPaintV2_ = useNewPipe ? eventHub->GetOnFirstMeaningfulPaintEvent() : nullptr;
1845         OnLargestContentfulPaintV2_ = useNewPipe ? eventHub->GetOnLargestContentfulPaintEvent() : nullptr;
1846         onSafeBrowsingCheckResultV2_ = useNewPipe ? eventHub->GetOnSafeBrowsingCheckResultEvent() : nullptr;
1847         onOverScrollV2_ = useNewPipe ? eventHub->GetOnOverScrollEvent()
1848                                      : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1849                                          webCom->GetOverScrollId(), oldContext);
1850         onScreenCaptureRequestV2_ = useNewPipe ? eventHub->GetOnScreenCaptureRequestEvent() : nullptr;
1851         onNavigationEntryCommittedV2_ = useNewPipe ? eventHub->GetOnNavigationEntryCommittedEvent() : nullptr;
1852         OnNativeEmbedAllDestoryV2_ = useNewPipe ? eventHub->GetOnNativeEmbedLifecycleChangeEvent() : nullptr;
1853         OnNativeEmbedLifecycleChangeV2_ = useNewPipe ? eventHub->GetOnNativeEmbedLifecycleChangeEvent()
1854                                             : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1855                                                 webCom->GetNativeEmbedLifecycleChangeId(), oldContext);
1856         OnNativeEmbedVisibilityChangeV2_ = useNewPipe ? eventHub->GetOnNativeEmbedVisibilityChangeEvent()
1857                                             : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1858                                                 webCom->GetNativeEmbedVisibilityChangeId(), oldContext);
1859         OnNativeEmbedGestureEventV2_ = useNewPipe ? eventHub->GetOnNativeEmbedGestureEvent()
1860                                             : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1861                                                 webCom->GetNativeEmbedGestureEventId(), oldContext);
1862         onIntelligentTrackingPreventionResultV2_ = useNewPipe ?
1863             eventHub->GetOnIntelligentTrackingPreventionResultEvent() : nullptr;
1864         onRenderProcessNotRespondingV2_ = useNewPipe
1865                                               ? eventHub->GetOnRenderProcessNotRespondingEvent()
1866                                               : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::
1867                                                 Create(webCom->GetRenderProcessNotRespondingId(), oldContext);
1868         onRenderProcessRespondingV2_ = useNewPipe ? eventHub->GetOnRenderProcessRespondingEvent()
1869                                                   : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::
1870                                                 Create(webCom->GetRenderProcessRespondingId(), oldContext);
1871         onViewportFitChangedV2_ = useNewPipe ? eventHub->GetOnViewportFitChangedEvent()
1872                                        : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1873                                            webCom->GetViewportFitChangedId(), oldContext);
1874         onAdsBlockedV2_ = useNewPipe ? eventHub->GetOnAdsBlockedEvent()
1875                                      : AceAsyncEvent<void(const std::shared_ptr<BaseEventInfo>&)>::Create(
1876                                          webCom->GetAdsBlockedEventId(), oldContext);
1877         onInterceptKeyboardAttachV2_ = useNewPipe ? eventHub->GetOnInterceptKeyboardAttachEvent()
1878                                                   : nullptr;
1879     }
1880     return true;
1881 }
1882 
OnSurfaceCreated(const sptr<OHOS::Surface> & surface)1883 void WebSurfaceCallback::OnSurfaceCreated(const sptr<OHOS::Surface>& surface) {}
1884 
OnSurfaceChanged(const sptr<OHOS::Surface> & surface,int32_t width,int32_t height)1885 void WebSurfaceCallback::OnSurfaceChanged(const sptr<OHOS::Surface>& surface, int32_t width, int32_t height)
1886 {
1887     auto delegate = delegate_.Upgrade();
1888     if (!delegate) {
1889         return;
1890     }
1891     delegate->Resize((double)width, (double)height);
1892 }
1893 
OnSurfaceDestroyed()1894 void WebSurfaceCallback::OnSurfaceDestroyed() {}
1895 
GLGetConfig(int version,EGLDisplay eglDisplay)1896 EGLConfig WebDelegate::GLGetConfig(int version, EGLDisplay eglDisplay)
1897 {
1898     int attribList[] = { EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8,
1899         EGL_ALPHA_SIZE, 8, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_NONE };
1900     EGLConfig configs = NULL;
1901     int configsNum;
1902     if (!eglChooseConfig(eglDisplay, attribList, &configs, 1, &configsNum)) {
1903         return NULL;
1904     }
1905     return configs;
1906 }
1907 
GLContextInit(void * window)1908 void WebDelegate::GLContextInit(void* window)
1909 {
1910     if (!window) {
1911         return;
1912     }
1913     mEglWindow = static_cast<EGLNativeWindowType>(window);
1914 
1915     // 1. create sharedcontext
1916     mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
1917     if (mEGLDisplay == EGL_NO_DISPLAY) {
1918         return;
1919     }
1920 
1921     EGLint eglMajVers, eglMinVers;
1922     if (!eglInitialize(mEGLDisplay, &eglMajVers, &eglMinVers)) {
1923         mEGLDisplay = EGL_NO_DISPLAY;
1924         return;
1925     }
1926 
1927     mEGLConfig = GLGetConfig(EGLCONFIG_VERSION, mEGLDisplay);
1928     if (mEGLConfig == nullptr) {
1929         return;
1930     }
1931 
1932     // 2. Create EGL Surface from Native Window
1933     mEGLSurface = eglCreateWindowSurface(mEGLDisplay, mEGLConfig, mEglWindow, nullptr);
1934     if (mEGLSurface == nullptr) {
1935         return;
1936     }
1937 
1938     // 3. Create EGLContext from
1939     int attrib3_list[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
1940 
1941     mEGLContext = eglCreateContext(mEGLDisplay, mEGLConfig, mSharedEGLContext, attrib3_list);
1942 
1943     if (!eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext)) {
1944         return;
1945     }
1946 
1947     glViewport(offset_.GetX(), offset_.GetY(), drawSize_.Width(), drawSize_.Height());
1948     glClearColor(1.0, 1.0, 1.0, 1.0);
1949     glClear(GL_COLOR_BUFFER_BIT);
1950 
1951     glFlush();
1952     glFinish();
1953     eglSwapBuffers(mEGLDisplay, mEGLSurface);
1954 
1955     eglDestroySurface(mEGLDisplay, mEGLSurface);
1956     eglDestroyContext(mEGLDisplay, mEGLContext);
1957 }
1958 
InitWebSurfaceDelegate(const WeakPtr<PipelineBase> & context)1959 bool WebDelegate::InitWebSurfaceDelegate(const WeakPtr<PipelineBase>& context)
1960 {
1961     auto pipelineContext = context.Upgrade();
1962     if (!pipelineContext) {
1963         return false;
1964     }
1965     uint32_t windowId = pipelineContext->GetWindowId();
1966     surfaceDelegate_ = new OHOS::SurfaceDelegate(windowId);
1967     if (surfaceDelegate_ == nullptr) {
1968         return false;
1969     }
1970     surfaceCallback_ = new WebSurfaceCallback(AceType::WeakClaim(this));
1971     if (surfaceCallback_ == nullptr) {
1972         return false;
1973     }
1974     surfaceDelegate_->AddSurfaceCallback(surfaceCallback_);
1975     surfaceDelegate_->CreateSurface();
1976     SetBoundsOrResize(drawSize_, offset_);
1977     needResizeAtFirst_ = true;
1978     auto aNativeSurface = surfaceDelegate_->GetNativeWindow();
1979     if (aNativeSurface == nullptr) {
1980         return false;
1981     }
1982     GLContextInit(aNativeSurface);
1983     surfaceInfo_.window = aNativeSurface;
1984     return true;
1985 }
1986 
InitOHOSWeb(const WeakPtr<PipelineBase> & context)1987 void WebDelegate::InitOHOSWeb(const WeakPtr<PipelineBase>& context)
1988 {
1989     if (!PrepareInitOHOSWeb(context)) {
1990         return;
1991     }
1992     if (!isCreateWebView_) {
1993         isCreateWebView_ = true;
1994         if (isEnhanceSurface_) {
1995             if (!InitWebSurfaceDelegate(context)) {
1996                 return;
1997             }
1998             InitWebViewWithSurface();
1999         } else {
2000 #ifdef ENABLE_ROSEN_BACKEND
2001             InitWebViewWithSurface();
2002 #else
2003             InitWebViewWithWindow();
2004 #endif
2005         }
2006     }
2007 }
RegisterOHOSWebEventAndMethord()2008 void WebDelegate::RegisterOHOSWebEventAndMethord()
2009 {
2010     auto reloadCallback = [weak = WeakClaim(this)]() {
2011         auto delegate = weak.Upgrade();
2012         if (!delegate) {
2013             return false;
2014         }
2015         delegate->Reload();
2016         return true;
2017     };
2018     WebClient::GetInstance().RegisterReloadCallback(reloadCallback);
2019 
2020     auto webCom = webComponent_.Upgrade();
2021     CHECK_NULL_VOID(webCom);
2022     auto context = DynamicCast<PipelineContext>(context_.Upgrade());
2023     CHECK_NULL_VOID(context);
2024     if (!webCom->GetPageStartedEventId().IsEmpty()) {
2025         onPageStarted_ = AceAsyncEvent<void(const std::string&)>::Create(webCom->GetPageStartedEventId(), context);
2026     }
2027     if (!webCom->GetPageFinishedEventId().IsEmpty()) {
2028         onPageFinished_ = AceAsyncEvent<void(const std::string&)>::Create(webCom->GetPageFinishedEventId(), context);
2029     }
2030     if (!webCom->GetPageErrorEventId().IsEmpty()) {
2031         onPageError_ = AceAsyncEvent<void(const std::string&)>::Create(webCom->GetPageErrorEventId(), context);
2032     }
2033 }
2034 
NotifyPopupWindowResult(bool result)2035 void WebDelegate::NotifyPopupWindowResult(bool result)
2036 {
2037     if (parentNWebId_ != -1) {
2038         std::shared_ptr<OHOS::NWeb::NWeb> parentNWeb = OHOS::NWeb::NWebHelper::Instance().GetNWeb(parentNWebId_);
2039         if (parentNWeb) {
2040             parentNWeb->NotifyPopupWindowResult(result);
2041         }
2042     }
2043 }
2044 
RunSetWebIdAndHapPathCallback()2045 void WebDelegate::RunSetWebIdAndHapPathCallback()
2046 {
2047     CHECK_NULL_VOID(nweb_);
2048     auto webId = nweb_->GetWebId();
2049 
2050 #ifdef NG_BUILD
2051     auto pattern = webPattern_.Upgrade();
2052     CHECK_NULL_VOID(pattern);
2053     auto setWebIdCallback = pattern->GetSetWebIdCallback();
2054     CHECK_NULL_VOID(setWebIdCallback);
2055     setWebIdCallback(webId);
2056     if (!hapPath_.empty()) {
2057         auto setHapPathCallback = pattern->GetSetHapPathCallback();
2058         CHECK_NULL_VOID(setHapPathCallback);
2059         setHapPathCallback(hapPath_);
2060     }
2061     auto onControllerAttachedCallback = pattern->GetOnControllerAttachedCallback();
2062     if (onControllerAttachedCallback) {
2063         onControllerAttachedCallback();
2064     }
2065     NotifyPopupWindowResult(true);
2066     return;
2067 #else
2068     if (Container::IsCurrentUseNewPipeline()) {
2069         auto pattern = webPattern_.Upgrade();
2070         CHECK_NULL_VOID(pattern);
2071         auto setWebIdCallback = pattern->GetSetWebIdCallback();
2072         CHECK_NULL_VOID(setWebIdCallback);
2073         setWebIdCallback(webId);
2074         if (!hapPath_.empty()) {
2075             auto setHapPathCallback = pattern->GetSetHapPathCallback();
2076             CHECK_NULL_VOID(setHapPathCallback);
2077             setHapPathCallback(hapPath_);
2078         }
2079         auto onControllerAttachedCallback = pattern->GetOnControllerAttachedCallback();
2080         if (onControllerAttachedCallback) {
2081             onControllerAttachedCallback();
2082         }
2083         NotifyPopupWindowResult(true);
2084         return;
2085     }
2086     auto webCom = webComponent_.Upgrade();
2087     CHECK_NULL_VOID(webCom);
2088     auto setWebIdCallback = webCom->GetSetWebIdCallback();
2089     CHECK_NULL_VOID(setWebIdCallback);
2090     setWebIdCallback(webId);
2091     if (!hapPath_.empty()) {
2092         auto setHapPathCallback = webCom->GetSetHapPathCallback();
2093         CHECK_NULL_VOID(setHapPathCallback);
2094         setHapPathCallback(hapPath_);
2095     }
2096     NotifyPopupWindowResult(true);
2097 #endif
2098 }
2099 
RunJsProxyCallback()2100 void WebDelegate::RunJsProxyCallback()
2101 {
2102 #ifdef NG_BUILD
2103     auto pattern = webPattern_.Upgrade();
2104     CHECK_NULL_VOID(pattern);
2105     pattern->CallJsProxyCallback();
2106     return;
2107 #else
2108     if (Container::IsCurrentUseNewPipeline()) {
2109         auto pattern = webPattern_.Upgrade();
2110         CHECK_NULL_VOID(pattern);
2111         pattern->CallJsProxyCallback();
2112         return;
2113     }
2114     auto webCom = webComponent_.Upgrade();
2115     CHECK_NULL_VOID(webCom);
2116     webCom->CallJsProxyCallback();
2117 #endif
2118 }
2119 
RegisterConfigObserver()2120 void WebDelegate::RegisterConfigObserver()
2121 {
2122     auto context = context_.Upgrade();
2123     if (!context) {
2124         return;
2125     }
2126     context->GetTaskExecutor()->PostTask(
2127         [weak = WeakClaim(this)]() {
2128             auto delegate = weak.Upgrade();
2129             CHECK_NULL_VOID(delegate);
2130             CHECK_NULL_VOID(delegate->nweb_);
2131             auto abilityContext = OHOS::AbilityRuntime::Context::GetApplicationContext();
2132             CHECK_NULL_VOID(abilityContext);
2133             delegate->configChangeObserver_ = std::make_shared<WebConfigurationObserver>(delegate);
2134             if (delegate->configChangeObserver_) {
2135                 abilityContext->RegisterEnvironmentCallback(delegate->configChangeObserver_);
2136             }
2137         },
2138         TaskExecutor::TaskType::PLATFORM, "ArkUIWebAddConfigObserver");
2139 }
2140 
UnRegisterConfigObserver()2141 void WebDelegate::UnRegisterConfigObserver()
2142 {
2143     auto context = context_.Upgrade();
2144     if (!context) {
2145         return;
2146     }
2147     context->GetTaskExecutor()->PostTask(
2148         [weak = WeakClaim(this)]() {
2149             auto delegate = weak.Upgrade();
2150             CHECK_NULL_VOID(delegate);
2151             CHECK_NULL_VOID(delegate->nweb_);
2152             CHECK_NULL_VOID(delegate->configChangeObserver_);
2153             auto abilityContext = OHOS::AbilityRuntime::Context::GetApplicationContext();
2154             CHECK_NULL_VOID(abilityContext);
2155             abilityContext->UnregisterEnvironmentCallback(delegate->configChangeObserver_);
2156             delegate->configChangeObserver_.reset();
2157         },
2158         TaskExecutor::TaskType::PLATFORM, "ArkUIWebRemoveConfigObserver");
2159 }
2160 
SetWebCallBack()2161 void WebDelegate::SetWebCallBack()
2162 {
2163     RefPtr<WebController> webController;
2164     if (Container::IsCurrentUseNewPipeline()) {
2165         auto pattern = webPattern_.Upgrade();
2166         webController = pattern ? pattern->GetWebController() : nullptr;
2167     } else {
2168         auto webCom = webComponent_.Upgrade();
2169         webController = webCom ? webCom->GetController() : nullptr;
2170     }
2171     if (webController) {
2172         auto context = context_.Upgrade();
2173         if (!context) {
2174             return;
2175         }
2176         auto uiTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::UI);
2177         webController->SetLoadUrlImpl([weak = WeakClaim(this), uiTaskExecutor](
2178                                           std::string url, const std::map<std::string, std::string>& httpHeaders) {
2179             uiTaskExecutor.PostTask([weak, url, httpHeaders]() {
2180                 auto delegate = weak.Upgrade();
2181                 if (delegate) {
2182                     delegate->LoadUrl(url, httpHeaders);
2183                 }
2184             }, "ArkUIWebControllerLoadUrl");
2185         });
2186         webController->SetBackwardImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2187             uiTaskExecutor.PostTask([weak]() {
2188                 auto delegate = weak.Upgrade();
2189                 if (delegate) {
2190                     delegate->Backward();
2191                 }
2192             }, "ArkUIWebBackward");
2193         });
2194         webController->SetForwardImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2195             uiTaskExecutor.PostTask([weak]() {
2196                 auto delegate = weak.Upgrade();
2197                 if (delegate) {
2198                     delegate->Forward();
2199                 }
2200             }, "ArkUIWebForward");
2201         });
2202         webController->SetClearHistoryImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2203             uiTaskExecutor.PostTask([weak]() {
2204                 auto delegate = weak.Upgrade();
2205                 if (delegate) {
2206                     delegate->ClearHistory();
2207                 }
2208             }, "ArkUIWebClearHistory");
2209         });
2210         webController->SetClearSslCacheImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2211             uiTaskExecutor.PostTask([weak]() {
2212                 auto delegate = weak.Upgrade();
2213                 if (delegate) {
2214                     delegate->ClearSslCache();
2215                 }
2216             }, "ArkUIWebControllerClearSslCache");
2217         });
2218         webController->SetClearClientAuthenticationCacheImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2219             uiTaskExecutor.PostTask([weak]() {
2220                 auto delegate = weak.Upgrade();
2221                 if (delegate) {
2222                     delegate->ClearClientAuthenticationCache();
2223                 }
2224             }, "ArkUIWebControllerClearClientAuthnCache");
2225         });
2226         webController->SetAccessStepImpl([weak = WeakClaim(this)](int32_t step) {
2227             auto delegate = weak.Upgrade();
2228             if (delegate) {
2229                 return delegate->AccessStep(step);
2230             }
2231             return false;
2232         });
2233         webController->SetBackOrForwardImpl([weak = WeakClaim(this)](int32_t step) {
2234             auto delegate = weak.Upgrade();
2235             if (delegate) {
2236                 delegate->BackOrForward(step);
2237             }
2238         });
2239         webController->SetAccessBackwardImpl([weak = WeakClaim(this)]() {
2240             auto delegate = weak.Upgrade();
2241             if (delegate) {
2242                 return delegate->AccessBackward();
2243             }
2244             return false;
2245         });
2246         webController->SetAccessForwardImpl([weak = WeakClaim(this)]() {
2247             auto delegate = weak.Upgrade();
2248             if (delegate) {
2249                 return delegate->AccessForward();
2250             }
2251             return false;
2252         });
2253         webController->SetExecuteTypeScriptImpl([weak = WeakClaim(this), uiTaskExecutor](std::string jscode,
2254                                                     std::function<void(const std::string)>&& callback) {
2255             uiTaskExecutor.PostTask([weak, jscode, callback]() {
2256                 auto delegate = weak.Upgrade();
2257                 if (delegate) {
2258                     delegate->ExecuteTypeScript(jscode, std::move(callback));
2259                 }
2260             }, "ArkUIWebExecuteTypeScript");
2261         });
2262         webController->SetLoadDataWithBaseUrlImpl(
2263             [weak = WeakClaim(this), uiTaskExecutor](std::string baseUrl, std::string data, std::string mimeType,
2264                 std::string encoding, std::string historyUrl) {
2265                 uiTaskExecutor.PostTask([weak, baseUrl, data, mimeType, encoding, historyUrl]() {
2266                     auto delegate = weak.Upgrade();
2267                     if (delegate) {
2268                         delegate->LoadDataWithBaseUrl(baseUrl, data, mimeType, encoding, historyUrl);
2269                     }
2270                 }, "ArkUIWebControllerLoadDataWithBaseUrl");
2271             });
2272         webController->SetRefreshImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2273             uiTaskExecutor.PostTask([weak]() {
2274                 auto delegate = weak.Upgrade();
2275                 if (delegate) {
2276                     delegate->Refresh();
2277                 }
2278             }, "ArkUIWebControllerRefresh");
2279         });
2280         webController->SetStopLoadingImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2281             uiTaskExecutor.PostTask([weak]() {
2282                 auto delegate = weak.Upgrade();
2283                 if (delegate) {
2284                     delegate->StopLoading();
2285                 }
2286             }, "ArkUIWebControllerStopLoading");
2287         });
2288         webController->SetGetHitTestResultImpl([weak = WeakClaim(this)]() {
2289             auto delegate = weak.Upgrade();
2290             if (delegate) {
2291                 return delegate->GetHitTestResult();
2292             }
2293             return 0;
2294         });
2295         webController->SetGetHitTestValueImpl([weak = WeakClaim(this)](HitTestResult& result) {
2296             auto delegate = weak.Upgrade();
2297             if (delegate) {
2298                 delegate->GetHitTestValue(result);
2299             }
2300         });
2301         webController->SetGetPageHeightImpl([weak = WeakClaim(this)]() {
2302             auto delegate = weak.Upgrade();
2303             if (delegate) {
2304                 return delegate->GetPageHeight();
2305             }
2306             return 0;
2307         });
2308         webController->SetGetWebIdImpl([weak = WeakClaim(this)]() {
2309             auto delegate = weak.Upgrade();
2310             if (delegate) {
2311                 return delegate->GetWebId();
2312             }
2313             return -1;
2314         });
2315         webController->SetGetTitleImpl([weak = WeakClaim(this)]() {
2316             auto delegate = weak.Upgrade();
2317             if (delegate) {
2318                 return delegate->GetTitle();
2319             }
2320             return std::string();
2321         });
2322         webController->SetCreateMsgPortsImpl([weak = WeakClaim(this)](std::vector<RefPtr<WebMessagePort>>& ports) {
2323             auto delegate = weak.Upgrade();
2324             if (delegate) {
2325                 delegate->CreateWebMessagePorts(ports);
2326             }
2327         });
2328         webController->SetPostWebMessageImpl([weak = WeakClaim(this)](std::string& message,
2329                                                  std::vector<RefPtr<WebMessagePort>>& ports, std::string& uri) {
2330             auto delegate = weak.Upgrade();
2331             if (delegate) {
2332                 delegate->PostWebMessage(message, ports, uri);
2333             }
2334         });
2335         webController->SetGetDefaultUserAgentImpl([weak = WeakClaim(this)]() {
2336             auto delegate = weak.Upgrade();
2337             if (delegate) {
2338                 return delegate->GetDefaultUserAgent();
2339             }
2340             return std::string();
2341         });
2342         webController->SetSaveCookieSyncImpl([weak = WeakClaim(this)]() {
2343             auto delegate = weak.Upgrade();
2344             if (delegate) {
2345                 return delegate->SaveCookieSync();
2346             }
2347             return false;
2348         });
2349         webController->SetSetCookieImpl([weak = WeakClaim(this)](const std::string& url, const std::string& value) {
2350             auto delegate = weak.Upgrade();
2351             if (delegate) {
2352                 return delegate->SetCookie(url, value, delegate->incognitoMode_);
2353             }
2354             return false;
2355         });
2356         webController->SetGetCookieImpl([weak = WeakClaim(this)](const std::string& url) {
2357             auto delegate = weak.Upgrade();
2358             if (delegate) {
2359                 return delegate->GetCookie(url, delegate->incognitoMode_);
2360             }
2361             return std::string();
2362         });
2363         webController->SetDeleteEntirelyCookieImpl([weak = WeakClaim(this)]() {
2364             auto delegate = weak.Upgrade();
2365             if (delegate) {
2366                 delegate->DeleteEntirelyCookie(delegate->incognitoMode_);
2367             }
2368         });
2369         webController->SetWebViewJavaScriptResultCallBackImpl(
2370             [weak = WeakClaim(this), uiTaskExecutor](WebController::JavaScriptCallBackImpl&& javaScriptCallBackImpl) {
2371                 uiTaskExecutor.PostTask([weak, javaScriptCallBackImpl]() {
2372                     auto delegate = weak.Upgrade();
2373                     if (delegate) {
2374                         delegate->SetWebViewJavaScriptResultCallBack(std::move(javaScriptCallBackImpl));
2375                     }
2376                 }, "ArkUIWebControllerSetJsResultCallBack");
2377             });
2378         webController->SetAddJavascriptInterfaceImpl([weak = WeakClaim(this), uiTaskExecutor](std::string objectName,
2379                                                          const std::vector<std::string>& methodList) {
2380             uiTaskExecutor.PostTask([weak, objectName, methodList]() {
2381                 auto delegate = weak.Upgrade();
2382                 if (delegate) {
2383                     delegate->AddJavascriptInterface(objectName, methodList);
2384                 }
2385             }, "ArkUIWebControllerAddJsInterface");
2386         });
2387         webController->LoadInitJavascriptInterface();
2388         webController->SetRemoveJavascriptInterfaceImpl([weak = WeakClaim(this), uiTaskExecutor](std::string objectName,
2389                                                             const std::vector<std::string>& methodList) {
2390             uiTaskExecutor.PostTask([weak, objectName, methodList]() {
2391                 auto delegate = weak.Upgrade();
2392                 if (delegate) {
2393                     delegate->RemoveJavascriptInterface(objectName, methodList);
2394                 }
2395             }, "ArkUIWebControllerRemoveJsInterface");
2396         });
2397         webController->SetOnInactiveImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2398             uiTaskExecutor.PostTask([weak]() {
2399                 auto delegate = weak.Upgrade();
2400                 if (delegate) {
2401                     delegate->OnInactive();
2402                 }
2403             }, "ArkUIWebInactiveCallback");
2404         });
2405         webController->SetOnActiveImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2406             uiTaskExecutor.PostTask([weak]() {
2407                 auto delegate = weak.Upgrade();
2408                 if (delegate) {
2409                     delegate->OnActive();
2410                 }
2411             }, "ArkUIWebActiveCallback");
2412         });
2413         webController->SetZoomImpl([weak = WeakClaim(this), uiTaskExecutor](float factor) {
2414             uiTaskExecutor.PostTask([weak, factor]() {
2415                 auto delegate = weak.Upgrade();
2416                 if (delegate) {
2417                     delegate->Zoom(factor);
2418                 }
2419             }, "ArkUIWebSetZoomFactor");
2420         });
2421         webController->SetZoomInImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2422             bool result = false;
2423             uiTaskExecutor.PostSyncTask([weak, &result]() {
2424                 auto delegate = weak.Upgrade();
2425                 if (delegate) {
2426                     result = delegate->ZoomIn();
2427                 }
2428             }, "ArkUIWebControllerZoomIn");
2429             return result;
2430         });
2431         webController->SetZoomOutImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2432             bool result = false;
2433             uiTaskExecutor.PostSyncTask([weak, &result]() {
2434                 auto delegate = weak.Upgrade();
2435                 if (delegate) {
2436                     result = delegate->ZoomOut();
2437                 }
2438             }, "ArkUIWebControllerZoomOut");
2439             return result;
2440         });
2441         webController->SetRequestFocusImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2442             uiTaskExecutor.PostTask([weak]() {
2443                 auto delegate = weak.Upgrade();
2444                 if (delegate) {
2445                     delegate->RequestFocus();
2446                 }
2447             }, "ArkUIWebControllerRequestFocus");
2448         });
2449 
2450         webController->SetSearchAllAsyncImpl([weak = WeakClaim(this), uiTaskExecutor](const std::string& searchStr) {
2451             uiTaskExecutor.PostTask([weak, searchStr]() {
2452                 auto delegate = weak.Upgrade();
2453                 if (delegate) {
2454                     delegate->SearchAllAsync(searchStr);
2455                 }
2456             }, "ArkUIWebControllerSearchAllAsync");
2457         });
2458         webController->SetClearMatchesImpl([weak = WeakClaim(this), uiTaskExecutor]() {
2459             uiTaskExecutor.PostTask([weak]() {
2460                 auto delegate = weak.Upgrade();
2461                 if (delegate) {
2462                     delegate->ClearMatches();
2463                 }
2464             }, "ArkUIWebControllerClearMatches");
2465         });
2466         webController->SetSearchNextImpl([weak = WeakClaim(this), uiTaskExecutor](bool forward) {
2467             uiTaskExecutor.PostTask([weak, forward]() {
2468                 auto delegate = weak.Upgrade();
2469                 if (delegate) {
2470                     delegate->SearchNext(forward);
2471                 }
2472             }, "ArkUIWebControllerSearchNext");
2473         });
2474         webController->SetGetUrlImpl([weak = WeakClaim(this)]() {
2475             auto delegate = weak.Upgrade();
2476             if (delegate) {
2477                 return delegate->GetUrl();
2478             }
2479             return std::string();
2480         });
2481     } else {
2482         TAG_LOGW(AceLogTag::ACE_WEB, "web controller is nullptr");
2483     }
2484 }
2485 
InitWebViewWithWindow()2486 void WebDelegate::InitWebViewWithWindow()
2487 {
2488     auto context = context_.Upgrade();
2489     CHECK_NULL_VOID(context);
2490     context->GetTaskExecutor()->PostTask(
2491         [weak = WeakClaim(this)]() {
2492             auto delegate = weak.Upgrade();
2493             if (!delegate) {
2494                 return;
2495             }
2496             std::shared_ptr<OHOS::NWeb::NWebEngineInitArgsImpl> initArgs =
2497                 std::make_shared<OHOS::NWeb::NWebEngineInitArgsImpl>();
2498             std::string app_path = GetDataPath();
2499             if (!app_path.empty()) {
2500                 initArgs->AddArg(std::string("--user-data-dir=").append(app_path));
2501             }
2502 
2503             delegate->window_ = delegate->CreateWindow();
2504             if (!delegate->window_) {
2505                 return;
2506             }
2507 
2508             initArgs->SetSharedRenderProcessToken(delegate->sharedRenderProcessToken_);
2509             delegate->nweb_ =
2510                 OHOS::NWeb::NWebAdapterHelper::Instance().CreateNWeb(
2511                     delegate->window_.GetRefPtr(), initArgs,
2512                     delegate->incognitoMode_);
2513             if (delegate->nweb_ == nullptr) {
2514                 delegate->window_ = nullptr;
2515                 return;
2516             }
2517             delegate->JavaScriptOnDocumentStart();
2518             delegate->JavaScriptOnDocumentEnd();
2519             delegate->cookieManager_ = OHOS::NWeb::NWebHelper::Instance().GetCookieManager();
2520             if (delegate->cookieManager_ == nullptr) {
2521                 return;
2522             }
2523             auto webviewClient = std::make_shared<WebClientImpl>();
2524             webviewClient->SetWebDelegate(weak);
2525             delegate->nweb_->SetNWebHandler(webviewClient);
2526 
2527             // Set downloadListenerImpl
2528             auto downloadListenerImpl = std::make_shared<DownloadListenerImpl>();
2529             downloadListenerImpl->SetWebDelegate(weak);
2530             delegate->nweb_->PutDownloadCallback(downloadListenerImpl);
2531 
2532             auto findListenerImpl = std::make_shared<FindListenerImpl>();
2533             findListenerImpl->SetWebDelegate(weak);
2534             delegate->nweb_->PutFindCallback(findListenerImpl);
2535 
2536             auto spanstringConvertHtmlImpl = std::make_shared<SpanstringConvertHtmlImpl>(Container::CurrentId());
2537             spanstringConvertHtmlImpl->SetWebDelegate(weak);
2538             delegate->nweb_->PutSpanstringConvertHtmlCallback(spanstringConvertHtmlImpl);
2539 
2540             std::optional<std::string> src;
2541             auto isNewPipe = Container::IsCurrentUseNewPipeline();
2542             delegate->UpdateSettting(isNewPipe);
2543             if (isNewPipe) {
2544                 auto webPattern = delegate->webPattern_.Upgrade();
2545                 if (webPattern) {
2546                     src = webPattern->GetWebSrc();
2547                 }
2548             } else {
2549                 auto webCom = delegate->webComponent_.Upgrade();
2550                 if (webCom) {
2551                     src = webCom->GetSrc();
2552                 }
2553             }
2554             if (src) {
2555                 delegate->nweb_->Load(src.value());
2556             }
2557             delegate->window_->Show();
2558         },
2559         TaskExecutor::TaskType::PLATFORM, "ArkUIWebInitWebViewWithWindow");
2560 }
2561 
UpdateSettting(bool useNewPipe)2562 void WebDelegate::UpdateSettting(bool useNewPipe)
2563 {
2564     CHECK_NULL_VOID(nweb_);
2565     auto setting = nweb_->GetPreference();
2566     CHECK_NULL_VOID(setting);
2567 #ifdef NG_BUILD
2568     auto webPattern = webPattern_.Upgrade();
2569     CHECK_NULL_VOID(webPattern);
2570     setting->PutDomStorageEnabled(webPattern->GetDomStorageAccessEnabledValue(false));
2571     setting->PutJavaScriptEnabled(webPattern->GetJsEnabledValue(true));
2572     setting->PutEnableRawFileAccess(webPattern->GetFileAccessEnabledValue(true));
2573     setting->PutEnableContentAccess(true);
2574     setting->PutLoadImageFromNetworkDisabled(!webPattern->GetOnLineImageAccessEnabledValue(true));
2575     setting->PutImageLoadingAllowed(webPattern->GetImageAccessEnabledValue(true));
2576     setting->PutAccessModeForSecureOriginLoadFromInsecure(static_cast<OHOS::NWeb::NWebPreference::AccessMode>(
2577         webPattern->GetMixedModeValue(MixedModeContent::MIXED_CONTENT_NEVER_ALLOW)));
2578     setting->PutZoomingFunctionEnabled(webPattern->GetZoomAccessEnabledValue(true));
2579     setting->PutGeolocationAllowed(webPattern->GetGeolocationAccessEnabledValue(true));
2580     setting->PutCacheMode(
2581         static_cast<OHOS::NWeb::NWebPreference::CacheModeFlag>(webPattern->GetCacheModeValue(WebCacheMode::DEFAULT)));
2582     setting->PutLoadWithOverviewMode(webPattern->GetOverviewModeAccessEnabledValue(true));
2583     setting->PutEnableRawFileAccessFromFileURLs(webPattern->GetFileFromUrlAccessEnabledValue(true));
2584     setting->PutDatabaseAllowed(webPattern->GetDatabaseAccessEnabledValue(false));
2585     setting->PutZoomingForTextFactor(webPattern->GetTextZoomRatioValue(DEFAULT_TEXT_ZOOM_RATIO));
2586     setting->PutWebDebuggingAccess(webPattern->GetWebDebuggingAccessEnabledValue(false));
2587     setting->PutMediaPlayGestureAccess(webPattern->GetMediaPlayGestureAccessValue(true));
2588     return;
2589 #else
2590     if (useNewPipe) {
2591         auto webPattern = webPattern_.Upgrade();
2592         CHECK_NULL_VOID(webPattern);
2593         setting->PutDomStorageEnabled(webPattern->GetDomStorageAccessEnabledValue(false));
2594         setting->PutJavaScriptEnabled(webPattern->GetJsEnabledValue(true));
2595         setting->PutEnableRawFileAccess(webPattern->GetFileAccessEnabledValue(true));
2596         setting->PutEnableContentAccess(true);
2597         setting->PutLoadImageFromNetworkDisabled(!webPattern->GetOnLineImageAccessEnabledValue(true));
2598         setting->PutImageLoadingAllowed(webPattern->GetImageAccessEnabledValue(true));
2599         setting->PutAccessModeForSecureOriginLoadFromInsecure(static_cast<OHOS::NWeb::NWebPreference::AccessMode>(
2600             webPattern->GetMixedModeValue(MixedModeContent::MIXED_CONTENT_NEVER_ALLOW)));
2601         setting->PutZoomingFunctionEnabled(webPattern->GetZoomAccessEnabledValue(true));
2602         setting->PutGeolocationAllowed(webPattern->GetGeolocationAccessEnabledValue(true));
2603         setting->PutCacheMode(static_cast<OHOS::NWeb::NWebPreference::CacheModeFlag>(
2604             webPattern->GetCacheModeValue(WebCacheMode::DEFAULT)));
2605         setting->PutLoadWithOverviewMode(webPattern->GetOverviewModeAccessEnabledValue(true));
2606         setting->PutEnableRawFileAccessFromFileURLs(webPattern->GetFileFromUrlAccessEnabledValue(true));
2607         setting->PutDatabaseAllowed(webPattern->GetDatabaseAccessEnabledValue(false));
2608         setting->PutZoomingForTextFactor(webPattern->GetTextZoomRatioValue(DEFAULT_TEXT_ZOOM_RATIO));
2609         setting->PutWebDebuggingAccess(webPattern->GetWebDebuggingAccessEnabledValue(false));
2610         setting->PutMediaPlayGestureAccess(webPattern->GetMediaPlayGestureAccessValue(true));
2611         return;
2612     }
2613     auto component = webComponent_.Upgrade();
2614     CHECK_NULL_VOID(component);
2615     setting->PutDomStorageEnabled(component->GetDomStorageAccessEnabled());
2616     setting->PutJavaScriptEnabled(component->GetJsEnabled());
2617     setting->PutEnableRawFileAccess(component->GetFileAccessEnabled());
2618     setting->PutEnableContentAccess(component->GetContentAccessEnabled());
2619     setting->PutLoadImageFromNetworkDisabled(component->GetOnLineImageAccessEnabled());
2620     setting->PutImageLoadingAllowed(component->GetImageAccessEnabled());
2621     setting->PutAccessModeForSecureOriginLoadFromInsecure(
2622         static_cast<OHOS::NWeb::NWebPreference::AccessMode>(component->GetMixedMode()));
2623     setting->PutZoomingFunctionEnabled(component->GetZoomAccessEnabled());
2624     setting->PutGeolocationAllowed(component->GetGeolocationAccessEnabled());
2625     setting->PutCacheMode(static_cast<OHOS::NWeb::NWebPreference::CacheModeFlag>(component->GetCacheMode()));
2626     setting->PutLoadWithOverviewMode(component->GetOverviewModeAccessEnabled());
2627     setting->PutEnableRawFileAccessFromFileURLs(component->GetFileFromUrlAccessEnabled());
2628     setting->PutDatabaseAllowed(component->GetDatabaseAccessEnabled());
2629     setting->PutZoomingForTextFactor(component->GetTextZoomRatio());
2630     setting->PutWebDebuggingAccess(component->GetWebDebuggingAccessEnabled());
2631     setting->PutMediaPlayGestureAccess(component->IsMediaPlayGestureAccess());
2632 #endif
2633 }
2634 
GetCustomScheme()2635 std::string WebDelegate::GetCustomScheme()
2636 {
2637     std::string customScheme;
2638     if (Container::IsCurrentUseNewPipeline()) {
2639         auto webPattern = webPattern_.Upgrade();
2640         if (webPattern) {
2641             auto webData = webPattern->GetCustomScheme();
2642             if (webData) {
2643                 customScheme = webData.value();
2644             }
2645         }
2646     } else {
2647         auto webCom = webComponent_.Upgrade();
2648         if (webCom) {
2649             customScheme = webCom->GetCustomScheme();
2650         }
2651     }
2652     return customScheme;
2653 }
2654 
SurfaceOcclusionCallback(float visibleRatio)2655 void WebDelegate::SurfaceOcclusionCallback(float visibleRatio)
2656 {
2657     TAG_LOGI(AceLogTag::ACE_WEB,
2658         "SurfaceOcclusion changed, occlusionPoints:%{public}f, surfacenode id: %{public}" PRIu64 "", visibleRatio,
2659         surfaceNodeId_);
2660     if (fabs(visibleRatio_ - visibleRatio) <= FLT_EPSILON || (fabs(visibleRatio) > FLT_EPSILON && visibleRatio < 0.0) ||
2661         (fabs(visibleRatio - 1.0) > FLT_EPSILON && visibleRatio > 1.0)) {
2662         TAG_LOGE(AceLogTag::ACE_WEB, "visibleRatio is ilegal or not changed.");
2663         return;
2664     }
2665     visibleRatio_ = visibleRatio;
2666 
2667     if (fabs(visibleRatio_) > FLT_EPSILON && visibleRatio_ > 0.0) {
2668         CHECK_NULL_VOID(nweb_);
2669         nweb_->OnUnoccluded();
2670         if (fabs(visibleRatio_ - lowerFrameRateVisibleRatio_) <= FLT_EPSILON ||
2671             visibleRatio_ < lowerFrameRateVisibleRatio_) {
2672             nweb_->SetEnableLowerFrameRate(true);
2673         } else {
2674             nweb_->SetEnableLowerFrameRate(false);
2675         }
2676     } else {
2677         auto context = context_.Upgrade();
2678         CHECK_NULL_VOID(context);
2679         CHECK_NULL_VOID(context->GetTaskExecutor());
2680         context->GetTaskExecutor()->PostDelayedTask(
2681             [weak = WeakClaim(this)]() {
2682                 auto delegate = weak.Upgrade();
2683                 CHECK_NULL_VOID(delegate);
2684                 if (fabs(delegate->visibleRatio_) <= FLT_EPSILON) {
2685                     TAG_LOGI(AceLogTag::ACE_WEB, "the web is still all occluded");
2686                     CHECK_NULL_VOID(delegate->nweb_);
2687                     delegate->nweb_->OnOccluded();
2688                 }
2689             },
2690             TaskExecutor::TaskType::UI, delayTime_, "ArkUIWebOccluded");
2691     }
2692 }
2693 
ratioStrToFloat(const std::string & str)2694 void WebDelegate::ratioStrToFloat(const std::string& str)
2695 {
2696     // LowerFrameRateConfig format x.xx, len is 4, [0.00, 1.00]
2697     if (str.size() != VISIBLERATIO_LENGTH) {
2698         TAG_LOGE(AceLogTag::ACE_WEB, "visibleRatio lenth is over 4.");
2699         return;
2700     }
2701     auto dotCount = std::count(str.begin(), str.end(), '.');
2702     if (dotCount != 1) {
2703         TAG_LOGE(AceLogTag::ACE_WEB, "visibleRatio does not have dot.");
2704         return;
2705     }
2706     auto pos = str.find('.', 0);
2707     if (pos != 1) {
2708         TAG_LOGE(AceLogTag::ACE_WEB, "visibleRatio dot position is wrong.");
2709         return;
2710     }
2711     auto notDigitCount = std::count_if(str.begin(), str.end(), [](char c) { return !isdigit(c) && c != '.'; });
2712     if (notDigitCount > 0) {
2713         TAG_LOGE(AceLogTag::ACE_WEB, "visibleRatio dot count is over 1.");
2714         return;
2715     }
2716     float f = std::stof(str);
2717     int i = f * VISIBLERATIO_FLOAT_TO_INT;
2718     if (i >= 0 && i <= VISIBLERATIO_FLOAT_TO_INT) {
2719         TAG_LOGI(AceLogTag::ACE_WEB, "visibleRatio check success.");
2720         lowerFrameRateVisibleRatio_ = f;
2721     }
2722 }
2723 
RegisterSurfaceOcclusionChangeFun()2724 void WebDelegate::RegisterSurfaceOcclusionChangeFun()
2725 {
2726     if (!GetWebOptimizationValue()) {
2727         TAG_LOGI(AceLogTag::ACE_WEB, "web optimization is close.");
2728         return;
2729     }
2730     if (!IsDeviceTabletOr2in1()) {
2731         TAG_LOGI(AceLogTag::ACE_WEB, "device type does not satisfy.");
2732         return;
2733     }
2734     std::string visibleAreaRatio =
2735         OHOS::NWeb::NWebAdapterHelper::Instance().ParsePerfConfig("LowerFrameRateConfig", "visibleAreaRatio");
2736     ratioStrToFloat(visibleAreaRatio);
2737     std::vector<float> partitionPoints;
2738     TAG_LOGI(AceLogTag::ACE_WEB, "max visible rate to lower frame rate:%{public}f", lowerFrameRateVisibleRatio_);
2739     if ((int)(lowerFrameRateVisibleRatio_ * VISIBLERATIO_FLOAT_TO_INT) == 0) {
2740         partitionPoints = { 0 };
2741     } else {
2742         partitionPoints = { 0, lowerFrameRateVisibleRatio_ };
2743     }
2744     auto ret = OHOS::Rosen::RSInterfaces::GetInstance().RegisterSurfaceOcclusionChangeCallback(
2745         surfaceNodeId_,
2746         [weak = WeakClaim(this)](float visibleRatio) {
2747             auto delegate = weak.Upgrade();
2748             CHECK_NULL_VOID(delegate);
2749             auto context = delegate->context_.Upgrade();
2750             CHECK_NULL_VOID(context);
2751             context->GetTaskExecutor()->PostTask(
2752                 [weakDelegate = weak, webVisibleRatio = visibleRatio]() {
2753                     auto delegate = weakDelegate.Upgrade();
2754                     CHECK_NULL_VOID(delegate);
2755                     delegate->SurfaceOcclusionCallback(webVisibleRatio);
2756                 },
2757                 TaskExecutor::TaskType::UI, "ArkUIWebOcclusionChange");
2758         },
2759         partitionPoints);
2760     if (ret != Rosen::StatusCode::SUCCESS) {
2761         TAG_LOGW(AceLogTag::ACE_WEB,
2762             "RegisterSurfaceOcclusionChangeCallback failed, surfacenode id:%{public}" PRIu64 ""
2763             ", ret: %{public}" PRIu32 "",
2764             surfaceNodeId_, ret);
2765         return;
2766     }
2767     TAG_LOGI(AceLogTag::ACE_WEB,
2768             "RegisterSurfaceOcclusionChangeCallback succeed, surfacenode id:%{public}" PRIu64 ""
2769             ", ret: %{public}" PRIu32 "",
2770             surfaceNodeId_, ret);
2771 }
2772 
RegisterAvoidAreaChangeListener()2773 void WebDelegate::RegisterAvoidAreaChangeListener()
2774 {
2775     constexpr static int32_t PLATFORM_VERSION_TEN = 10;
2776     auto container = AceType::DynamicCast<Platform::AceContainer>(Container::GetContainer(instanceId_));
2777     CHECK_NULL_VOID(container);
2778     auto pipeline = container->GetPipelineContext();
2779     if (pipeline && pipeline->GetMinPlatformVersion() >= PLATFORM_VERSION_TEN &&
2780         (pipeline->GetIsAppWindow() || container->IsUIExtensionWindow())) {
2781         if (avoidAreaChangedListener_) return;
2782 
2783         systemSafeArea_ = container->GetViewSafeAreaByType(OHOS::Rosen::AvoidAreaType::TYPE_SYSTEM);
2784         cutoutSafeArea_ = container->GetViewSafeAreaByType(OHOS::Rosen::AvoidAreaType::TYPE_CUTOUT);
2785         navigationIndicatorSafeArea_ =
2786             container->GetViewSafeAreaByType(OHOS::Rosen::AvoidAreaType::TYPE_NAVIGATION_INDICATOR);
2787         OnSafeInsetsChange();
2788 
2789         avoidAreaChangedListener_ = new WebAvoidAreaChangedListener(AceType::WeakClaim(this));
2790         OHOS::Rosen::WMError regCode = container->RegisterAvoidAreaChangeListener(avoidAreaChangedListener_);
2791         TAG_LOGI(AceLogTag::ACE_WEB, "RegisterAvoidAreaChangeListener result:%{public}d", (int) regCode);
2792     } else {
2793         TAG_LOGI(AceLogTag::ACE_WEB, "CANNOT RegisterAvoidAreaChangeListener");
2794     }
2795 }
2796 
2797 class NWebAutoFillCallbackImpl : public OHOS::NWeb::NWebMessageValueCallback {
2798 public:
NWebAutoFillCallbackImpl(const WeakPtr<WebDelegate> & delegate)2799     NWebAutoFillCallbackImpl(const WeakPtr<WebDelegate>& delegate) : delegate_(delegate) {}
2800     ~NWebAutoFillCallbackImpl() = default;
2801 
OnReceiveValue(std::shared_ptr<NWebMessage> result)2802     void OnReceiveValue(std::shared_ptr<NWebMessage> result) override
2803     {
2804         TAG_LOGI(AceLogTag::ACE_AUTO_FILL, "called");
2805         auto delegate = delegate_.Upgrade();
2806         CHECK_NULL_VOID(delegate);
2807         bool ret = delegate->HandleAutoFillEvent(result);
2808         result->SetType(NWebValue::Type::BOOLEAN);
2809         result->SetBoolean(ret);
2810     }
2811 
2812 private:
2813     WeakPtr<WebDelegate> delegate_;
2814 };
2815 
UnregisterAvoidAreaChangeListener()2816 void WebDelegate::UnregisterAvoidAreaChangeListener()
2817 {
2818     constexpr static int32_t PLATFORM_VERSION_TEN = 10;
2819     auto container = AceType::DynamicCast<Platform::AceContainer>(Container::GetContainer(instanceId_));
2820     CHECK_NULL_VOID(container);
2821     auto pipeline = container->GetPipelineContext();
2822     if (pipeline && pipeline->GetMinPlatformVersion() >= PLATFORM_VERSION_TEN &&
2823         (pipeline->GetIsAppWindow() || container->IsUIExtensionWindow())) {
2824         if (!avoidAreaChangedListener_) return;
2825         OHOS::Rosen::WMError regCode = container->UnregisterAvoidAreaChangeListener(avoidAreaChangedListener_);
2826         avoidAreaChangedListener_ = nullptr;
2827         TAG_LOGI(AceLogTag::ACE_WEB, "UnregisterAvoidAreaChangeListener result:%{public}d", (int) regCode);
2828     } else {
2829         TAG_LOGI(AceLogTag::ACE_WEB, "CANNOT UnregisterAvoidAreaChangeListener");
2830     }
2831 }
2832 
InitWebViewWithSurface()2833 void WebDelegate::InitWebViewWithSurface()
2834 {
2835     auto context = context_.Upgrade();
2836     CHECK_NULL_VOID(context);
2837     auto window = context->GetWindow();
2838     CHECK_NULL_VOID(window);
2839     rosenWindowId_ = window->GetWindowId();
2840     context->GetTaskExecutor()->PostTask(
2841         [weak = WeakClaim(this), context = context_, renderMode = renderMode_, layoutMode = layoutMode_]() {
2842             auto delegate = weak.Upgrade();
2843             CHECK_NULL_VOID(delegate);
2844             std::shared_ptr<OHOS::NWeb::NWebEngineInitArgsImpl> initArgs =
2845                 std::make_shared<OHOS::NWeb::NWebEngineInitArgsImpl>();
2846             initArgs->AddArg(std::string("--user-data-dir=").append(delegate->bundleDataPath_));
2847             initArgs->AddArg(std::string("--bundle-installation-dir=").append(delegate->bundlePath_));
2848             initArgs->AddArg(std::string("--lang=").append(AceApplicationInfo::GetInstance().GetLanguage() +
2849                     "-" + AceApplicationInfo::GetInstance().GetCountryOrRegion()));
2850             initArgs->AddArg(std::string("--user-api-version=").append(
2851                 std::to_string(AceApplicationInfo::GetInstance().GetApiTargetVersion())));
2852             bool isEnhanceSurface = delegate->isEnhanceSurface_;
2853             initArgs->SetIsEnhanceSurface(isEnhanceSurface);
2854             initArgs->SetIsPopup(delegate->isPopup_);
2855             initArgs->SetSharedRenderProcessToken(delegate->sharedRenderProcessToken_);
2856 
2857             if (!delegate->hapPath_.empty()) {
2858                 initArgs->AddArg(std::string("--user-hap-path=").append(delegate->hapPath_));
2859             }
2860 
2861             if (!delegate->tempDir_.empty()) {
2862                 initArgs->AddArg(std::string("--ohos-temp-dir=").append(delegate->tempDir_));
2863             }
2864 
2865             std::string customScheme = delegate->GetCustomScheme();
2866             if (!customScheme.empty()) {
2867                 initArgs->AddArg(std::string("--ohos-custom-scheme=").append(customScheme));
2868             }
2869             initArgs->AddArg(std::string("--init-background-color=")
2870                 .append(std::to_string(delegate->backgroundColor_)));
2871             if (delegate->richtextData_) {
2872                 // Created a richtext component
2873                 initArgs->AddArg(std::string("--init-richtext-data=").append(delegate->richtextData_.value()));
2874             }
2875             if (isEnhanceSurface) {
2876                 TAG_LOGD(AceLogTag::ACE_WEB, "Create webview with isEnhanceSurface");
2877                 delegate->nweb_ = OHOS::NWeb::NWebAdapterHelper::Instance().CreateNWeb(
2878                     (void *)(&delegate->surfaceInfo_),
2879                     initArgs,
2880                     delegate->drawSize_.Width(),
2881                     delegate->drawSize_.Height(),
2882                     delegate->incognitoMode_);
2883                 delegate->JavaScriptOnDocumentStart();
2884                 delegate->JavaScriptOnDocumentEnd();
2885             } else {
2886 #ifdef ENABLE_ROSEN_BACKEND
2887                 wptr<Surface> surfaceWeak(delegate->surface_);
2888                 sptr<Surface> surface = surfaceWeak.promote();
2889                 CHECK_NULL_VOID(surface);
2890                 delegate->nweb_ = OHOS::NWeb::NWebAdapterHelper::Instance().CreateNWeb(
2891                     surface,
2892                     initArgs,
2893                     delegate->drawSize_.Width(),
2894                     delegate->drawSize_.Height(),
2895                     delegate->incognitoMode_);
2896                 delegate->JavaScriptOnDocumentStart();
2897                 delegate->JavaScriptOnDocumentEnd();
2898 #endif
2899             }
2900             CHECK_NULL_VOID(delegate->nweb_);
2901             delegate->cookieManager_ = OHOS::NWeb::NWebHelper::Instance().GetCookieManager();
2902             CHECK_NULL_VOID(delegate->cookieManager_);
2903             auto nweb_handler = std::make_shared<WebClientImpl>();
2904             nweb_handler->SetWebDelegate(weak);
2905             auto downloadListenerImpl = std::make_shared<DownloadListenerImpl>();
2906             downloadListenerImpl->SetWebDelegate(weak);
2907             delegate->nweb_->SetNWebHandler(nweb_handler);
2908             delegate->nweb_->PutDownloadCallback(downloadListenerImpl);
2909 #ifdef OHOS_STANDARD_SYSTEM
2910             auto screenLockCallback = std::make_shared<NWebScreenLockCallbackImpl>(context);
2911             delegate->nweb_->RegisterScreenLockFunction(Container::CurrentId(), screenLockCallback);
2912             auto autoFillCallback = std::make_shared<NWebAutoFillCallbackImpl>(weak);
2913             delegate->nweb_->SetAutofillCallback(autoFillCallback);
2914 #endif
2915             auto findListenerImpl = std::make_shared<FindListenerImpl>();
2916             findListenerImpl->SetWebDelegate(weak);
2917             delegate->nweb_->PutFindCallback(findListenerImpl);
2918             delegate->UpdateSettting(Container::IsCurrentUseNewPipeline());
2919             delegate->RunSetWebIdAndHapPathCallback();
2920             delegate->RunJsProxyCallback();
2921             auto releaseSurfaceListenerImpl = std::make_shared<ReleaseSurfaceImpl>();
2922             releaseSurfaceListenerImpl->SetSurfaceDelegate(delegate->GetSurfaceDelegateClient());
2923             releaseSurfaceListenerImpl->SetWebDelegate(weak);
2924             delegate->nweb_->PutReleaseSurfaceCallback(releaseSurfaceListenerImpl);
2925             auto upgradeContext = context.Upgrade();
2926             CHECK_NULL_VOID(upgradeContext);
2927             auto window_id = upgradeContext->GetWindowId();
2928             delegate->nweb_->SetWindowId(window_id);
2929             delegate->SetToken();
2930             delegate->RegisterSurfaceOcclusionChangeFun();
2931             delegate->RegisterAvoidAreaChangeListener();
2932             delegate->nweb_->SetDrawMode(renderMode);
2933             delegate->nweb_->SetFitContentMode(layoutMode);
2934             delegate->RegisterConfigObserver();
2935             auto spanstringConvertHtmlImpl = std::make_shared<SpanstringConvertHtmlImpl>(Container::CurrentId());
2936             spanstringConvertHtmlImpl->SetWebDelegate(weak);
2937             delegate->nweb_->PutSpanstringConvertHtmlCallback(spanstringConvertHtmlImpl);
2938         },
2939         TaskExecutor::TaskType::PLATFORM, "ArkUIWebInitWebViewWithSurface");
2940 }
2941 
SetKeepScreenOn(bool key)2942 void WebDelegate::SetKeepScreenOn(bool key)
2943 {
2944     auto context = context_.Upgrade();
2945     CHECK_NULL_VOID(context);
2946     auto window = context->GetWindow();
2947     CHECK_NULL_VOID(window);
2948     window->SetKeepScreenOn(key);
2949 }
2950 
UpdateUserAgent(const std::string & userAgent)2951 void WebDelegate::UpdateUserAgent(const std::string& userAgent)
2952 {
2953     auto context = context_.Upgrade();
2954     if (!context) {
2955         return;
2956     }
2957     context->GetTaskExecutor()->PostTask(
2958         [weak = WeakClaim(this), userAgent]() {
2959             auto delegate = weak.Upgrade();
2960             if (delegate && delegate->nweb_) {
2961                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
2962                 CHECK_NULL_VOID(setting);
2963                 setting->PutUserAgent(userAgent);
2964             }
2965         },
2966         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateUserAgent");
2967 }
2968 
UpdateBackgroundColor(const int backgroundColor)2969 void WebDelegate::UpdateBackgroundColor(const int backgroundColor)
2970 {
2971     auto context = context_.Upgrade();
2972     if (!context) {
2973         return;
2974     }
2975     context->GetTaskExecutor()->PostTask(
2976         [weak = WeakClaim(this), backgroundColor]() {
2977             auto delegate = weak.Upgrade();
2978             if (delegate && delegate->nweb_) {
2979                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
2980                 delegate->nweb_->PutBackgroundColor(backgroundColor);
2981             }
2982         },
2983         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateBackgroundColor");
2984 }
2985 
UpdateInitialScale(float scale)2986 void WebDelegate::UpdateInitialScale(float scale)
2987 {
2988     auto context = context_.Upgrade();
2989     if (!context) {
2990         return;
2991     }
2992     context->GetTaskExecutor()->PostTask(
2993         [weak = WeakClaim(this), scale]() {
2994             auto delegate = weak.Upgrade();
2995             if (delegate && delegate->nweb_) {
2996                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
2997                 delegate->nweb_->InitialScale(scale);
2998             }
2999         },
3000         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateInitialScale");
3001 }
3002 
SetSurfaceDensity(const double & density)3003 void WebDelegate::SetSurfaceDensity(const double& density)
3004 {
3005     auto context = context_.Upgrade();
3006     if (!context) {
3007         return;
3008     }
3009     context->GetTaskExecutor()->PostTask(
3010         [weak = WeakClaim(this), density]() {
3011             auto delegate = weak.Upgrade();
3012             if (delegate && delegate->nweb_) {
3013                 delegate->nweb_->SetSurfaceDensity(density);
3014             }
3015         },
3016         TaskExecutor::TaskType::PLATFORM, "ArkUIWebSetSurfaceDensity");
3017 }
3018 
UpdateLayoutMode(WebLayoutMode mode)3019 void WebDelegate::UpdateLayoutMode(WebLayoutMode mode)
3020 {
3021     auto context = context_.Upgrade();
3022     if (!context) {
3023         return;
3024     }
3025     context->GetTaskExecutor()->PostTask(
3026         [weak = WeakClaim(this), mode]() {
3027             auto delegate = weak.Upgrade();
3028             if (delegate && delegate->nweb_) {
3029                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3030                 delegate->nweb_->SetFitContentMode(static_cast<int32_t>(mode));
3031             }
3032         },
3033         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateLayoutMode");
3034 }
3035 
Resize(const double & width,const double & height,bool isKeyboard)3036 void WebDelegate::Resize(const double& width, const double& height, bool isKeyboard)
3037 {
3038     if (width <= 0 || height <= 0) {
3039         return;
3040     }
3041 
3042     if ((resizeWidth_ == width) && (resizeHeight_ == height)) {
3043         return;
3044     }
3045     resizeWidth_ = width;
3046     resizeHeight_ = height;
3047     auto context = context_.Upgrade();
3048     if (!context) {
3049         return;
3050     }
3051     context->GetTaskExecutor()->PostTask(
3052         [weak = WeakClaim(this), width, height, isKeyboard]() {
3053             auto delegate = weak.Upgrade();
3054             if (delegate && delegate->nweb_ && !delegate->window_) {
3055                 // Sur need int value, greater than this value in case show black line.
3056                 delegate->nweb_->Resize(std::ceil(width), std::ceil(height), isKeyboard);
3057                 double offsetX = 0;
3058                 double offsetY = 0;
3059                 delegate->UpdateScreenOffSet(offsetX, offsetY);
3060                 delegate->nweb_->SetScreenOffSet(offsetX, offsetY);
3061             }
3062         },
3063         TaskExecutor::TaskType::PLATFORM, "ArkUIWebResize");
3064     auto webPattern = webPattern_.Upgrade();
3065     CHECK_NULL_VOID(webPattern);
3066     webPattern->DestroyAnalyzerOverlay();
3067 }
3068 
UpdateJavaScriptEnabled(const bool & isJsEnabled)3069 void WebDelegate::UpdateJavaScriptEnabled(const bool& isJsEnabled)
3070 {
3071     auto context = context_.Upgrade();
3072     if (!context) {
3073         return;
3074     }
3075     context->GetTaskExecutor()->PostTask(
3076         [weak = WeakClaim(this), isJsEnabled]() {
3077             auto delegate = weak.Upgrade();
3078             if (delegate && delegate->nweb_) {
3079                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3080                 CHECK_NULL_VOID(setting);
3081                 setting->PutJavaScriptEnabled(isJsEnabled);
3082             }
3083         },
3084         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateJavaScriptEnabled");
3085 }
3086 
UpdateAllowFileAccess(const bool & isFileAccessEnabled)3087 void WebDelegate::UpdateAllowFileAccess(const bool& isFileAccessEnabled)
3088 {
3089     auto context = context_.Upgrade();
3090     if (!context) {
3091         return;
3092     }
3093     context->GetTaskExecutor()->PostTask(
3094         [weak = WeakClaim(this), isFileAccessEnabled]() {
3095             auto delegate = weak.Upgrade();
3096             if (delegate && delegate->nweb_) {
3097                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3098                 CHECK_NULL_VOID(setting);
3099                 setting->PutEnableRawFileAccess(isFileAccessEnabled);
3100             }
3101         },
3102         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateAllowFileAccess");
3103 }
3104 
UpdateBlockNetworkImage(const bool & onLineImageAccessEnabled)3105 void WebDelegate::UpdateBlockNetworkImage(const bool& onLineImageAccessEnabled)
3106 {
3107     auto context = context_.Upgrade();
3108     if (!context) {
3109         return;
3110     }
3111     context->GetTaskExecutor()->PostTask(
3112         [weak = WeakClaim(this), onLineImageAccessEnabled]() {
3113             auto delegate = weak.Upgrade();
3114             if (delegate && delegate->nweb_) {
3115                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3116                 CHECK_NULL_VOID(setting);
3117                 setting->PutLoadImageFromNetworkDisabled(onLineImageAccessEnabled);
3118             }
3119         },
3120         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateBlockNetworkImage");
3121 }
3122 
UpdateLoadsImagesAutomatically(const bool & isImageAccessEnabled)3123 void WebDelegate::UpdateLoadsImagesAutomatically(const bool& isImageAccessEnabled)
3124 {
3125     auto context = context_.Upgrade();
3126     if (!context) {
3127         return;
3128     }
3129     context->GetTaskExecutor()->PostTask(
3130         [weak = WeakClaim(this), isImageAccessEnabled]() {
3131             auto delegate = weak.Upgrade();
3132             if (delegate && delegate->nweb_) {
3133                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3134                 CHECK_NULL_VOID(setting);
3135                 setting->PutImageLoadingAllowed(isImageAccessEnabled);
3136             }
3137         },
3138         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateLoadImageAccessEnabled");
3139 }
3140 
UpdateMixedContentMode(const MixedModeContent & mixedMode)3141 void WebDelegate::UpdateMixedContentMode(const MixedModeContent& mixedMode)
3142 {
3143     auto context = context_.Upgrade();
3144     if (!context) {
3145         return;
3146     }
3147     context->GetTaskExecutor()->PostTask(
3148         [weak = WeakClaim(this), mixedMode]() {
3149             auto delegate = weak.Upgrade();
3150             if (delegate && delegate->nweb_) {
3151                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3152                 CHECK_NULL_VOID(setting);
3153                 setting->PutAccessModeForSecureOriginLoadFromInsecure(
3154                     static_cast<OHOS::NWeb::NWebPreference::AccessMode>(mixedMode));
3155             }
3156         },
3157         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateMixedContentMode");
3158 }
3159 
UpdateSupportZoom(const bool & isZoomAccessEnabled)3160 void WebDelegate::UpdateSupportZoom(const bool& isZoomAccessEnabled)
3161 {
3162     auto context = context_.Upgrade();
3163     if (!context) {
3164         return;
3165     }
3166     context->GetTaskExecutor()->PostTask(
3167         [weak = WeakClaim(this), isZoomAccessEnabled]() {
3168             auto delegate = weak.Upgrade();
3169             if (delegate && delegate->nweb_) {
3170                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3171                 CHECK_NULL_VOID(setting);
3172                 setting->PutZoomingFunctionEnabled(isZoomAccessEnabled);
3173             }
3174         },
3175         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateSupportZoom");
3176 }
UpdateDomStorageEnabled(const bool & isDomStorageAccessEnabled)3177 void WebDelegate::UpdateDomStorageEnabled(const bool& isDomStorageAccessEnabled)
3178 {
3179     auto context = context_.Upgrade();
3180     if (!context) {
3181         return;
3182     }
3183     context->GetTaskExecutor()->PostTask(
3184         [weak = WeakClaim(this), isDomStorageAccessEnabled]() {
3185             auto delegate = weak.Upgrade();
3186             if (delegate && delegate->nweb_) {
3187                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3188                 CHECK_NULL_VOID(setting);
3189                 setting->PutDomStorageEnabled(isDomStorageAccessEnabled);
3190             }
3191         },
3192         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateDomStorageEnabled");
3193 }
UpdateGeolocationEnabled(const bool & isGeolocationAccessEnabled)3194 void WebDelegate::UpdateGeolocationEnabled(const bool& isGeolocationAccessEnabled)
3195 {
3196     auto context = context_.Upgrade();
3197     if (!context) {
3198         return;
3199     }
3200     context->GetTaskExecutor()->PostTask(
3201         [weak = WeakClaim(this), isGeolocationAccessEnabled]() {
3202             auto delegate = weak.Upgrade();
3203             if (delegate && delegate->nweb_) {
3204                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3205                 CHECK_NULL_VOID(setting);
3206                 setting->PutGeolocationAllowed(isGeolocationAccessEnabled);
3207             }
3208         },
3209         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateGeolocationEnabled");
3210 }
3211 
UpdateCacheMode(const WebCacheMode & mode)3212 void WebDelegate::UpdateCacheMode(const WebCacheMode& mode)
3213 {
3214     auto context = context_.Upgrade();
3215     if (!context) {
3216         return;
3217     }
3218 
3219     context->GetTaskExecutor()->PostTask(
3220         [weak = WeakClaim(this), mode]() {
3221             auto delegate = weak.Upgrade();
3222             if (delegate && delegate->nweb_) {
3223                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3224                 CHECK_NULL_VOID(setting);
3225                 setting->PutCacheMode(static_cast<OHOS::NWeb::NWebPreference::CacheModeFlag>(mode));
3226             }
3227         },
3228         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateCacheMode");
3229 }
3230 
GetNweb()3231 std::shared_ptr<OHOS::NWeb::NWeb> WebDelegate::GetNweb()
3232 {
3233     return nweb_;
3234 }
3235 
GetForceDarkMode()3236 bool WebDelegate::GetForceDarkMode()
3237 {
3238     return forceDarkMode_;
3239 }
3240 
UpdateDarkMode(const WebDarkMode & mode)3241 void WebDelegate::UpdateDarkMode(const WebDarkMode& mode)
3242 {
3243     auto context = context_.Upgrade();
3244     if (!context) {
3245         return;
3246     }
3247 
3248     current_dark_mode_ = mode;
3249     context->GetTaskExecutor()->PostTask(
3250         [weak = WeakClaim(this), mode]() {
3251             auto delegate = weak.Upgrade();
3252             CHECK_NULL_VOID(delegate);
3253             CHECK_NULL_VOID(delegate->nweb_);
3254             std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3255             CHECK_NULL_VOID(setting);
3256 
3257             if (mode == WebDarkMode::On) {
3258                 setting->PutDarkSchemeEnabled(true);
3259                 if (delegate->forceDarkMode_) {
3260                     setting->PutForceDarkModeEnabled(true);
3261                 }
3262             } else if (mode == WebDarkMode::Off) {
3263                 setting->PutDarkSchemeEnabled(false);
3264                 setting->PutForceDarkModeEnabled(false);
3265             } else if (mode == WebDarkMode::Auto) {
3266                 delegate->UpdateDarkModeAuto(delegate, setting);
3267             }
3268         },
3269         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateDarkMode");
3270 }
3271 
UpdateDarkModeAuto(RefPtr<WebDelegate> delegate,std::shared_ptr<OHOS::NWeb::NWebPreference> setting)3272 void WebDelegate::UpdateDarkModeAuto(RefPtr<WebDelegate> delegate, std::shared_ptr<OHOS::NWeb::NWebPreference> setting)
3273 {
3274     CHECK_NULL_VOID(setting);
3275     auto abilityContext = OHOS::AbilityRuntime::Context::GetApplicationContext();
3276     CHECK_NULL_VOID(abilityContext);
3277     auto appConfig = abilityContext->GetConfiguration();
3278     CHECK_NULL_VOID(appConfig);
3279     auto colorMode = appConfig->GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE);
3280     if (colorMode == "dark") {
3281         setting->PutDarkSchemeEnabled(true);
3282         if (delegate->GetForceDarkMode()) {
3283             setting->PutForceDarkModeEnabled(true);
3284         }
3285     }
3286     if (colorMode == "light") {
3287         setting->PutDarkSchemeEnabled(false);
3288         setting->PutForceDarkModeEnabled(false);
3289     }
3290 }
3291 
UpdateForceDarkAccess(const bool & access)3292 void WebDelegate::UpdateForceDarkAccess(const bool& access)
3293 {
3294     auto context = context_.Upgrade();
3295     if (!context) {
3296         return;
3297     }
3298     context->GetTaskExecutor()->PostTask(
3299         [weak = WeakClaim(this), access]() {
3300             auto delegate = weak.Upgrade();
3301             CHECK_NULL_VOID(delegate);
3302             CHECK_NULL_VOID(delegate->nweb_);
3303             std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3304             CHECK_NULL_VOID(setting);
3305             delegate->forceDarkMode_ = access;
3306             if (setting->DarkSchemeEnabled()) {
3307                 setting->PutForceDarkModeEnabled(access);
3308             } else {
3309                 setting->PutForceDarkModeEnabled(false);
3310             }
3311         },
3312         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateForceDarkAccess");
3313 }
3314 
UpdateAudioResumeInterval(const int32_t & resumeInterval)3315 void WebDelegate::UpdateAudioResumeInterval(const int32_t& resumeInterval)
3316 {
3317     auto context = context_.Upgrade();
3318     if (!context) {
3319         return;
3320     }
3321     context->GetTaskExecutor()->PostTask(
3322         [weak = WeakClaim(this), resumeInterval]() {
3323             auto delegate = weak.Upgrade();
3324             CHECK_NULL_VOID(delegate);
3325             CHECK_NULL_VOID(delegate->nweb_);
3326             delegate->nweb_->SetAudioResumeInterval(resumeInterval);
3327         },
3328         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateAudioResumeInterval");
3329 }
3330 
UpdateAudioExclusive(const bool & audioExclusive)3331 void WebDelegate::UpdateAudioExclusive(const bool& audioExclusive)
3332 {
3333     auto context = context_.Upgrade();
3334     if (!context) {
3335         return;
3336     }
3337     context->GetTaskExecutor()->PostTask(
3338         [weak = WeakClaim(this), audioExclusive]() {
3339             auto delegate = weak.Upgrade();
3340             CHECK_NULL_VOID(delegate);
3341             CHECK_NULL_VOID(delegate->nweb_);
3342             delegate->nweb_->SetAudioExclusive(audioExclusive);
3343         },
3344         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateAudioExclusive");
3345 }
3346 
UpdateOverviewModeEnabled(const bool & isOverviewModeAccessEnabled)3347 void WebDelegate::UpdateOverviewModeEnabled(const bool& isOverviewModeAccessEnabled)
3348 {
3349     auto context = context_.Upgrade();
3350     if (!context) {
3351         return;
3352     }
3353     context->GetTaskExecutor()->PostTask(
3354         [weak = WeakClaim(this), isOverviewModeAccessEnabled]() {
3355             auto delegate = weak.Upgrade();
3356             if (delegate && delegate->nweb_) {
3357                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3358                 CHECK_NULL_VOID(setting);
3359                 setting->PutLoadWithOverviewMode(isOverviewModeAccessEnabled);
3360             }
3361         },
3362         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateOverviewModeEnabled");
3363 }
3364 
UpdateFileFromUrlEnabled(const bool & isFileFromUrlAccessEnabled)3365 void WebDelegate::UpdateFileFromUrlEnabled(const bool& isFileFromUrlAccessEnabled)
3366 {
3367     auto context = context_.Upgrade();
3368     if (!context) {
3369         return;
3370     }
3371     context->GetTaskExecutor()->PostTask(
3372         [weak = WeakClaim(this), isFileFromUrlAccessEnabled]() {
3373             auto delegate = weak.Upgrade();
3374             if (delegate && delegate->nweb_) {
3375                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3376                 CHECK_NULL_VOID(setting);
3377                 setting->PutEnableRawFileAccessFromFileURLs(isFileFromUrlAccessEnabled);
3378             }
3379         },
3380         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateFileFromUrlEnabled");
3381 }
3382 
UpdateDatabaseEnabled(const bool & isDatabaseAccessEnabled)3383 void WebDelegate::UpdateDatabaseEnabled(const bool& isDatabaseAccessEnabled)
3384 {
3385     auto context = context_.Upgrade();
3386     if (!context) {
3387         return;
3388     }
3389     context->GetTaskExecutor()->PostTask(
3390         [weak = WeakClaim(this), isDatabaseAccessEnabled]() {
3391             auto delegate = weak.Upgrade();
3392             if (delegate && delegate->nweb_) {
3393                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3394                 CHECK_NULL_VOID(setting);
3395                 setting->PutDatabaseAllowed(isDatabaseAccessEnabled);
3396             }
3397         },
3398         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateDatabaseEnabled");
3399 }
3400 
UpdateTextZoomRatio(const int32_t & textZoomRatioNum)3401 void WebDelegate::UpdateTextZoomRatio(const int32_t& textZoomRatioNum)
3402 {
3403     auto context = context_.Upgrade();
3404     if (!context) {
3405         return;
3406     }
3407     context->GetTaskExecutor()->PostTask(
3408         [weak = WeakClaim(this), textZoomRatioNum]() {
3409             auto delegate = weak.Upgrade();
3410             if (delegate && delegate->nweb_) {
3411                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3412                 CHECK_NULL_VOID(setting);
3413                 setting->PutZoomingForTextFactor(textZoomRatioNum);
3414             }
3415         },
3416         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateTextZoomRatio");
3417 }
3418 
UpdateWebDebuggingAccess(bool isWebDebuggingAccessEnabled)3419 void WebDelegate::UpdateWebDebuggingAccess(bool isWebDebuggingAccessEnabled)
3420 {
3421     auto context = context_.Upgrade();
3422     if (!context) {
3423         return;
3424     }
3425     context->GetTaskExecutor()->PostTask(
3426         [weak = WeakClaim(this), isWebDebuggingAccessEnabled]() {
3427             auto delegate = weak.Upgrade();
3428             if (delegate && delegate->nweb_) {
3429                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3430                 CHECK_NULL_VOID(setting);
3431                 setting->PutWebDebuggingAccess(isWebDebuggingAccessEnabled);
3432             }
3433         },
3434         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateDebuggingAccess");
3435 }
3436 
UpdatePinchSmoothModeEnabled(bool isPinchSmoothModeEnabled)3437 void WebDelegate::UpdatePinchSmoothModeEnabled(bool isPinchSmoothModeEnabled)
3438 {
3439     auto context = context_.Upgrade();
3440     if (!context) {
3441         return;
3442     }
3443     context->GetTaskExecutor()->PostTask(
3444         [weak = WeakClaim(this), isPinchSmoothModeEnabled]() {
3445             auto delegate = weak.Upgrade();
3446             if (delegate && delegate->nweb_) {
3447                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3448                 CHECK_NULL_VOID(setting);
3449                 setting->PutPinchSmoothMode(isPinchSmoothModeEnabled);
3450             }
3451         },
3452         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdatePinchSmoothModeEnabled");
3453 }
3454 
UpdateMediaPlayGestureAccess(bool isNeedGestureAccess)3455 void WebDelegate::UpdateMediaPlayGestureAccess(bool isNeedGestureAccess)
3456 {
3457     auto context = context_.Upgrade();
3458     if (!context) {
3459         return;
3460     }
3461     context->GetTaskExecutor()->PostTask(
3462         [weak = WeakClaim(this), isNeedGestureAccess]() {
3463             auto delegate = weak.Upgrade();
3464             if (delegate && delegate->nweb_) {
3465                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3466                 if (setting) {
3467                     setting->PutMediaPlayGestureAccess(isNeedGestureAccess);
3468                 }
3469             }
3470         },
3471         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateMediaPlayGestureAccess");
3472 }
3473 
UpdateMultiWindowAccess(bool isMultiWindowAccessEnabled)3474 void WebDelegate::UpdateMultiWindowAccess(bool isMultiWindowAccessEnabled)
3475 {
3476     auto context = context_.Upgrade();
3477     if (!context) {
3478         return;
3479     }
3480     context->GetTaskExecutor()->PostTask(
3481         [weak = WeakClaim(this), isMultiWindowAccessEnabled]() {
3482             auto delegate = weak.Upgrade();
3483             if (delegate && delegate->nweb_) {
3484                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3485                 CHECK_NULL_VOID(setting);
3486                 setting->PutMultiWindowAccess(isMultiWindowAccessEnabled);
3487             }
3488         },
3489         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateMultiWindowAccess");
3490 }
3491 
UpdateAllowWindowOpenMethod(bool isAllowWindowOpenMethod)3492 void WebDelegate::UpdateAllowWindowOpenMethod(bool isAllowWindowOpenMethod)
3493 {
3494     auto context = context_.Upgrade();
3495     if (!context) {
3496         return;
3497     }
3498     context->GetTaskExecutor()->PostTask(
3499         [weak = WeakClaim(this), isAllowWindowOpenMethod]() {
3500             auto delegate = weak.Upgrade();
3501             if (delegate && delegate->nweb_) {
3502                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3503                 CHECK_NULL_VOID(setting);
3504                 setting->PutIsCreateWindowsByJavaScriptAllowed(isAllowWindowOpenMethod);
3505             }
3506         },
3507         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateAllowWindowOpen");
3508 }
3509 
UpdateWebCursiveFont(const std::string & cursiveFontFamily)3510 void WebDelegate::UpdateWebCursiveFont(const std::string& cursiveFontFamily)
3511 {
3512     auto context = context_.Upgrade();
3513     if (!context) {
3514         return;
3515     }
3516     context->GetTaskExecutor()->PostTask(
3517         [weak = WeakClaim(this), cursiveFontFamily]() {
3518             auto delegate = weak.Upgrade();
3519             if (delegate && delegate->nweb_) {
3520                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3521                 if (setting) {
3522                     setting->PutCursiveFontFamilyName(cursiveFontFamily);
3523                 }
3524             }
3525         },
3526         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateWebCursiveFont");
3527 }
3528 
UpdateWebFantasyFont(const std::string & fantasyFontFamily)3529 void WebDelegate::UpdateWebFantasyFont(const std::string& fantasyFontFamily)
3530 {
3531     auto context = context_.Upgrade();
3532     if (!context) {
3533         return;
3534     }
3535     context->GetTaskExecutor()->PostTask(
3536         [weak = WeakClaim(this), fantasyFontFamily]() {
3537             auto delegate = weak.Upgrade();
3538             if (delegate && delegate->nweb_) {
3539                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3540                 if (setting) {
3541                     setting->PutFantasyFontFamilyName(fantasyFontFamily);
3542                 }
3543             }
3544         },
3545         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateWebFantasyFont");
3546 }
3547 
UpdateWebFixedFont(const std::string & fixedFontFamily)3548 void WebDelegate::UpdateWebFixedFont(const std::string& fixedFontFamily)
3549 {
3550     auto context = context_.Upgrade();
3551     if (!context) {
3552         return;
3553     }
3554     context->GetTaskExecutor()->PostTask(
3555         [weak = WeakClaim(this), fixedFontFamily]() {
3556             auto delegate = weak.Upgrade();
3557             if (delegate && delegate->nweb_) {
3558                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3559                 if (setting) {
3560                     setting->PutFixedFontFamilyName(fixedFontFamily);
3561                 }
3562             }
3563         },
3564         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateWebFixedFont");
3565 }
3566 
UpdateWebSansSerifFont(const std::string & sansSerifFontFamily)3567 void WebDelegate::UpdateWebSansSerifFont(const std::string& sansSerifFontFamily)
3568 {
3569     auto context = context_.Upgrade();
3570     if (!context) {
3571         return;
3572     }
3573     context->GetTaskExecutor()->PostTask(
3574         [weak = WeakClaim(this), sansSerifFontFamily]() {
3575             auto delegate = weak.Upgrade();
3576             if (delegate && delegate->nweb_) {
3577                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3578                 if (setting) {
3579                     setting->PutSansSerifFontFamilyName(sansSerifFontFamily);
3580                 }
3581             }
3582         },
3583         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateWebSansSerifFont");
3584 }
3585 
UpdateWebSerifFont(const std::string & serifFontFamily)3586 void WebDelegate::UpdateWebSerifFont(const std::string& serifFontFamily)
3587 {
3588     auto context = context_.Upgrade();
3589     if (!context) {
3590         return;
3591     }
3592     context->GetTaskExecutor()->PostTask(
3593         [weak = WeakClaim(this), serifFontFamily]() {
3594             auto delegate = weak.Upgrade();
3595             if (delegate && delegate->nweb_) {
3596                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3597                 if (setting) {
3598                     setting->PutSerifFontFamilyName(serifFontFamily);
3599                 }
3600             }
3601         },
3602         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateWebSerifFont");
3603 }
3604 
UpdateWebStandardFont(const std::string & standardFontFamily)3605 void WebDelegate::UpdateWebStandardFont(const std::string& standardFontFamily)
3606 {
3607     auto context = context_.Upgrade();
3608     if (!context) {
3609         return;
3610     }
3611     context->GetTaskExecutor()->PostTask(
3612         [weak = WeakClaim(this), standardFontFamily]() {
3613             auto delegate = weak.Upgrade();
3614             if (delegate && delegate->nweb_) {
3615                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3616                 if (setting) {
3617                     setting->PutStandardFontFamilyName(standardFontFamily);
3618                 }
3619             }
3620         },
3621         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateWebStandardFont");
3622 }
3623 
UpdateDefaultFixedFontSize(int32_t defaultFixedFontSize)3624 void WebDelegate::UpdateDefaultFixedFontSize(int32_t defaultFixedFontSize)
3625 {
3626     auto context = context_.Upgrade();
3627     if (!context) {
3628         return;
3629     }
3630     context->GetTaskExecutor()->PostTask(
3631         [weak = WeakClaim(this), defaultFixedFontSize]() {
3632             auto delegate = weak.Upgrade();
3633             if (delegate && delegate->nweb_) {
3634                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3635                 if (setting) {
3636                     setting->PutDefaultFixedFontSize(defaultFixedFontSize);
3637                 }
3638             }
3639         },
3640         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateDefaultFixedFontSize");
3641 }
3642 
OnConfigurationUpdated(const OHOS::AppExecFwk::Configuration & configuration)3643 void WebDelegate::OnConfigurationUpdated(const OHOS::AppExecFwk::Configuration& configuration)
3644 {
3645     auto context = context_.Upgrade();
3646     CHECK_NULL_VOID(context);
3647 
3648     auto executor = context->GetTaskExecutor();
3649     CHECK_NULL_VOID(executor);
3650 
3651     std::string colorMode = configuration.GetItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE);
3652     std::string themeTag = configuration.GetItem(OHOS::AAFwk::GlobalConfigurationKey::THEME);
3653     uint8_t themeFlags = static_cast<uint8_t>(OHOS::NWeb::SystemThemeFlags::NONE);
3654     if (!themeTag.empty()) {
3655         std::unique_ptr<JsonValue> json = JsonUtil::ParseJsonString(themeTag);
3656         if (json->GetInt("fonts")) {
3657             themeFlags |= static_cast<uint8_t>(OHOS::NWeb::SystemThemeFlags::THEME_FONT);
3658             TAG_LOGI(AceLogTag::ACE_WEB, "OnConfigurationUpdated fonts:%{public}s", themeTag.c_str());
3659         }
3660     }
3661 
3662     executor->PostTask(
3663         [weak = WeakClaim(this), colorMode, themeFlags, dark_mode = current_dark_mode_]() {
3664             auto delegate = weak.Upgrade();
3665             CHECK_NULL_VOID(delegate);
3666             auto nweb = delegate->GetNweb();
3667             CHECK_NULL_VOID(nweb);
3668 
3669             std::shared_ptr<NWebSystemConfigurationImpl> configuration =
3670                     std::make_shared<NWebSystemConfigurationImpl>(themeFlags);
3671             nweb->OnConfigurationUpdated(configuration);
3672 
3673             auto setting = nweb->GetPreference();
3674             CHECK_NULL_VOID(setting);
3675             bool auto_dark_mode = (dark_mode == WebDarkMode::Auto);
3676             if (auto_dark_mode && colorMode == "dark") {
3677                 setting->PutDarkSchemeEnabled(true);
3678                 if (delegate->GetForceDarkMode()) {
3679                     setting->PutForceDarkModeEnabled(true);
3680                 }
3681             } else if (auto_dark_mode && colorMode == "light") {
3682                 setting->PutDarkSchemeEnabled(false);
3683                 setting->PutForceDarkModeEnabled(false);
3684             }
3685         },
3686         TaskExecutor::TaskType::PLATFORM, "ArkUIWebConfigurationUpdated");
3687 }
3688 
UpdateDefaultFontSize(int32_t defaultFontSize)3689 void WebDelegate::UpdateDefaultFontSize(int32_t defaultFontSize)
3690 {
3691     auto context = context_.Upgrade();
3692     if (!context) {
3693         return;
3694     }
3695     context->GetTaskExecutor()->PostTask(
3696         [weak = WeakClaim(this), defaultFontSize]() {
3697             auto delegate = weak.Upgrade();
3698             if (delegate && delegate->nweb_) {
3699                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3700                 if (setting) {
3701                     setting->PutDefaultFontSize(defaultFontSize);
3702                 }
3703             }
3704         },
3705         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateDefaultFontSize");
3706 }
3707 
UpdateMinFontSize(int32_t minFontSize)3708 void WebDelegate::UpdateMinFontSize(int32_t minFontSize)
3709 {
3710     auto context = context_.Upgrade();
3711     if (!context) {
3712         return;
3713     }
3714     context->GetTaskExecutor()->PostTask(
3715         [weak = WeakClaim(this), minFontSize]() {
3716             auto delegate = weak.Upgrade();
3717             if (delegate && delegate->nweb_) {
3718                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3719                 if (setting) {
3720                     setting->PutFontSizeLowerLimit(minFontSize);
3721                 }
3722             }
3723         },
3724         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateMinFontSize");
3725 }
3726 
UpdateMinLogicalFontSize(int32_t minLogicalFontSize)3727 void WebDelegate::UpdateMinLogicalFontSize(int32_t minLogicalFontSize)
3728 {
3729     auto context = context_.Upgrade();
3730     if (!context) {
3731         return;
3732     }
3733     context->GetTaskExecutor()->PostTask(
3734         [weak = WeakClaim(this), minLogicalFontSize]() {
3735             auto delegate = weak.Upgrade();
3736             if (delegate && delegate->nweb_) {
3737                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3738                 if (setting) {
3739                     setting->PutLogicalFontSizeLowerLimit(minLogicalFontSize);
3740                 }
3741             }
3742         },
3743         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateMinLogicalFontSize");
3744 }
3745 
UpdateBlockNetwork(bool isNetworkBlocked)3746 void WebDelegate::UpdateBlockNetwork(bool isNetworkBlocked)
3747 {
3748     auto context = context_.Upgrade();
3749     if (!context) {
3750         return;
3751     }
3752     context->GetTaskExecutor()->PostTask(
3753         [weak = WeakClaim(this), isNetworkBlocked]() {
3754             auto delegate = weak.Upgrade();
3755             if (delegate && delegate->nweb_) {
3756                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3757                 if (setting) {
3758                     setting->PutBlockNetwork(isNetworkBlocked);
3759                 }
3760             }
3761         },
3762         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateBlockNetwork");
3763 }
3764 
UpdateHorizontalScrollBarAccess(bool isHorizontalScrollBarAccessEnabled)3765 void WebDelegate::UpdateHorizontalScrollBarAccess(bool isHorizontalScrollBarAccessEnabled)
3766 {
3767     auto context = context_.Upgrade();
3768     if (!context) {
3769         return;
3770     }
3771     context->GetTaskExecutor()->PostTask(
3772         [weak = WeakClaim(this), isHorizontalScrollBarAccessEnabled]() {
3773             auto delegate = weak.Upgrade();
3774             if (delegate && delegate->nweb_) {
3775                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3776                 if (setting) {
3777                     setting->PutHorizontalScrollBarAccess(isHorizontalScrollBarAccessEnabled);
3778                 }
3779             }
3780         },
3781         TaskExecutor::TaskType::PLATFORM, "ArkUIWebPutHorizontalScrollBarAccess");
3782 }
3783 
UpdateVerticalScrollBarAccess(bool isVerticalScrollBarAccessEnabled)3784 void WebDelegate::UpdateVerticalScrollBarAccess(bool isVerticalScrollBarAccessEnabled)
3785 {
3786     auto context = context_.Upgrade();
3787     if (!context) {
3788         return;
3789     }
3790     context->GetTaskExecutor()->PostTask(
3791         [weak = WeakClaim(this), isVerticalScrollBarAccessEnabled]() {
3792             auto delegate = weak.Upgrade();
3793             if (delegate && delegate->nweb_) {
3794                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3795                 if (setting) {
3796                     setting->PutVerticalScrollBarAccess(isVerticalScrollBarAccessEnabled);
3797                 }
3798             }
3799         },
3800         TaskExecutor::TaskType::PLATFORM, "ArkUIWebPutVerticalScrollBarAccess");
3801 }
3802 
UpdateOverlayScrollbarEnabled(bool isEnabled)3803 void WebDelegate::UpdateOverlayScrollbarEnabled(bool isEnabled)
3804 {
3805     auto context = context_.Upgrade();
3806     if (!context) {
3807         return;
3808     }
3809     context->GetTaskExecutor()->PostTask(
3810         [weak = WeakClaim(this), isEnabled]() {
3811             auto delegate = weak.Upgrade();
3812             if (delegate && delegate->nweb_) {
3813                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3814                 if (setting) {
3815                     setting->PutOverlayScrollbarEnabled(isEnabled);
3816                 }
3817             }
3818         },
3819         TaskExecutor::TaskType::PLATFORM, "ArkUIWebPutOverlayScrollbarEnabled");
3820 }
3821 
UpdateNativeEmbedModeEnabled(bool isEmbedModeEnabled)3822 void WebDelegate::UpdateNativeEmbedModeEnabled(bool isEmbedModeEnabled)
3823 {
3824     auto context = context_.Upgrade();
3825     if (!context) {
3826         return;
3827     }
3828     isEmbedModeEnabled_ = isEmbedModeEnabled;
3829     context->GetTaskExecutor()->PostTask(
3830         [weak = WeakClaim(this), isEmbedModeEnabled]() {
3831             auto delegate = weak.Upgrade();
3832             if (delegate && delegate->nweb_) {
3833                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3834                 if (setting) {
3835                     setting->SetNativeEmbedMode(isEmbedModeEnabled);
3836                 }
3837             }
3838         },
3839         TaskExecutor::TaskType::PLATFORM, "ArkUIWebSetNativeEmbedMode");
3840 }
3841 
UpdateNativeEmbedRuleTag(const std::string & tag)3842 void WebDelegate::UpdateNativeEmbedRuleTag(const std::string& tag)
3843 {
3844     auto context = context_.Upgrade();
3845     if (!context) {
3846         return;
3847     }
3848     tag_ = tag;
3849     if (tag_.empty() || tag_type_.empty()) {
3850         return;
3851     }
3852 
3853     context->GetTaskExecutor()->PostTask(
3854         [weak = WeakClaim(this)]() {
3855             auto delegate = weak.Upgrade();
3856             if (delegate && delegate->nweb_) {
3857                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3858                 if (setting) {
3859                     setting->RegisterNativeEmbedRule(delegate->tag_, delegate->tag_type_);
3860                 }
3861             }
3862         },
3863         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateNativeEmbedRuleTag");
3864 }
3865 
UpdateNativeEmbedRuleType(const std::string & type)3866 void WebDelegate::UpdateNativeEmbedRuleType(const std::string& type)
3867 {
3868     auto context = context_.Upgrade();
3869     if (!context) {
3870         return;
3871     }
3872     tag_type_ = type;
3873     if (tag_.empty() || tag_type_.empty()) {
3874         return;
3875     }
3876     context->GetTaskExecutor()->PostTask(
3877         [weak = WeakClaim(this)]() {
3878             auto delegate = weak.Upgrade();
3879             if (delegate && delegate->nweb_) {
3880                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3881                 if (setting) {
3882                     setting->RegisterNativeEmbedRule(delegate->tag_, delegate->tag_type_);
3883                 }
3884             }
3885         },
3886         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateNativeEmbedRuleType");
3887 }
3888 
UpdateScrollBarColor(const std::string & colorValue)3889 void WebDelegate::UpdateScrollBarColor(const std::string& colorValue)
3890 {
3891     auto context = context_.Upgrade();
3892     if (!context) {
3893         return;
3894     }
3895 
3896     auto pipeline = PipelineContext::GetCurrentContext();
3897     if (pipeline == nullptr) {
3898         return;
3899     }
3900 
3901     auto themeManager = pipeline->GetThemeManager();
3902     if (themeManager == nullptr) {
3903         return;
3904     }
3905 
3906     auto themeConstants = themeManager->GetThemeConstants();
3907     if (themeConstants == nullptr) {
3908         return;
3909     }
3910     Color color = themeConstants->GetColorByName(colorValue);
3911     uint32_t colorContent = color.GetValue();
3912     context->GetTaskExecutor()->PostTask(
3913         [weak = WeakClaim(this), colorContent]() {
3914             auto delegate = weak.Upgrade();
3915             if (delegate && delegate->nweb_) {
3916                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
3917                 if (setting) {
3918                     setting->PutScrollBarColor(colorContent);
3919                 }
3920             }
3921         },
3922         TaskExecutor::TaskType::PLATFORM, "ArkUIWebPutScrollBarColor");
3923 }
3924 
LoadUrl()3925 void WebDelegate::LoadUrl()
3926 {
3927     auto context = context_.Upgrade();
3928     CHECK_NULL_VOID(context);
3929     context->GetTaskExecutor()->PostTask(
3930         [weak = WeakClaim(this)]() {
3931             auto delegate = weak.Upgrade();
3932             if (delegate && delegate->nweb_) {
3933                 std::optional<std::string> src;
3934                 if (Container::IsCurrentUseNewPipeline()) {
3935                     auto webPattern = delegate->webPattern_.Upgrade();
3936                     if (webPattern) {
3937                         src = webPattern->GetWebSrc();
3938                     }
3939                 } else {
3940                     auto webCom = delegate->webComponent_.Upgrade();
3941                     if (webCom) {
3942                         src = webCom->GetSrc();
3943                     }
3944                 }
3945                 CHECK_NULL_VOID(src);
3946                 delegate->nweb_->Load(src.value());
3947             }
3948         },
3949         TaskExecutor::TaskType::PLATFORM, "ArkUIWebLoadSrcUrl");
3950 }
3951 
OnInactive()3952 void WebDelegate::OnInactive()
3953 {
3954     TAG_LOGI(AceLogTag::ACE_WEB, "WebDelegate::OnInactive, webId:%{public}d", GetWebId());
3955     auto context = context_.Upgrade();
3956     if (!context) {
3957         return;
3958     }
3959     context->GetTaskExecutor()->PostTask(
3960         [weak = WeakClaim(this)]() {
3961             auto delegate = weak.Upgrade();
3962             if (!delegate) {
3963                 return;
3964             }
3965             if (delegate->nweb_) {
3966                 delegate->nweb_->OnPause();
3967             }
3968         },
3969         TaskExecutor::TaskType::PLATFORM, "ArkUIWebOnInactive");
3970 }
3971 
OnActive()3972 void WebDelegate::OnActive()
3973 {
3974     TAG_LOGI(AceLogTag::ACE_WEB, "WebDelegate::OnActive, webId:%{public}d", GetWebId());
3975     auto context = context_.Upgrade();
3976     if (!context) {
3977         return;
3978     }
3979     context->GetTaskExecutor()->PostTask(
3980         [weak = WeakClaim(this)]() {
3981             auto delegate = weak.Upgrade();
3982             if (!delegate) {
3983                 return;
3984             }
3985             if (delegate->nweb_) {
3986                 delegate->nweb_->OnContinue();
3987             }
3988         },
3989         TaskExecutor::TaskType::PLATFORM, "ArkUIWebOnActive");
3990 }
3991 
OnWebviewHide()3992 void WebDelegate::OnWebviewHide()
3993 {
3994     auto context = context_.Upgrade();
3995     if (!context) {
3996         return;
3997     }
3998     context->GetTaskExecutor()->PostTask(
3999         [weak = WeakClaim(this)]() {
4000             auto delegate = weak.Upgrade();
4001             if (!delegate) {
4002                 return;
4003             }
4004             if (delegate->nweb_) {
4005                 delegate->nweb_->OnWebviewHide();
4006             }
4007         },
4008         TaskExecutor::TaskType::PLATFORM, "ArkUIWebOnWebviewHide");
4009 }
4010 
OnWebviewShow()4011 void WebDelegate::OnWebviewShow()
4012 {
4013     auto context = context_.Upgrade();
4014     if (!context) {
4015         return;
4016     }
4017     context->GetTaskExecutor()->PostTask(
4018         [weak = WeakClaim(this)]() {
4019             auto delegate = weak.Upgrade();
4020             if (!delegate) {
4021                 return;
4022             }
4023             if (delegate->nweb_) {
4024                 delegate->nweb_->OnWebviewShow();
4025             }
4026         },
4027         TaskExecutor::TaskType::PLATFORM, "ArkUIWebOnWebviewShow");
4028 }
4029 
OnRenderToForeground()4030 void WebDelegate::OnRenderToForeground()
4031 {
4032     TAG_LOGI(AceLogTag::ACE_WEB, "WebDelegate::OnRenderToForeground");
4033     auto context = context_.Upgrade();
4034     if (!context) {
4035         return;
4036     }
4037     context->GetTaskExecutor()->PostTask(
4038         [weak = WeakClaim(this)]() {
4039             auto delegate = weak.Upgrade();
4040             if (!delegate) {
4041                 return;
4042             }
4043             if (delegate->nweb_) {
4044                 TAG_LOGD(AceLogTag::ACE_WEB, "delegate->nweb_->OnRenderToForeground");
4045                 delegate->nweb_->OnRenderToForeground();
4046             }
4047         },
4048         TaskExecutor::TaskType::PLATFORM, "ArkUIWebOnRenderToForeground");
4049 }
4050 
OnRenderToBackground()4051 void WebDelegate::OnRenderToBackground()
4052 {
4053     TAG_LOGI(AceLogTag::ACE_WEB, "WebDelegate::OnRenderToBackground");
4054     auto context = context_.Upgrade();
4055     if (!context) {
4056         return;
4057     }
4058     context->GetTaskExecutor()->PostTask(
4059         [weak = WeakClaim(this)]() {
4060             auto delegate = weak.Upgrade();
4061             if (!delegate) {
4062                 return;
4063             }
4064             if (delegate->nweb_) {
4065                 TAG_LOGD(AceLogTag::ACE_WEB, "delegate->nweb_->OnRenderToBackground");
4066                 delegate->nweb_->OnRenderToBackground();
4067             }
4068         },
4069         TaskExecutor::TaskType::PLATFORM, "ArkUIWebOnRenderToBackground");
4070 }
4071 
OnOnlineRenderToForeground()4072 void WebDelegate::OnOnlineRenderToForeground()
4073 {
4074     TAG_LOGD(AceLogTag::ACE_WEB, "WebDelegate::OnOnlineRenderToForeground");
4075     auto context = context_.Upgrade();
4076     if (!context) {
4077         return;
4078     }
4079     context->GetTaskExecutor()->PostTask(
4080         [weak = WeakClaim(this)]() {
4081             auto delegate = weak.Upgrade();
4082             if (!delegate) {
4083                 return;
4084             }
4085             if (delegate->nweb_) {
4086                 TAG_LOGD(AceLogTag::ACE_WEB, "delegate->nweb_->OnOnlineRenderToForeground");
4087                 delegate->nweb_->OnOnlineRenderToForeground();
4088             }
4089         },
4090         TaskExecutor::TaskType::PLATFORM, "ArkUIWebOnOnlineRenderToForeground");
4091 }
4092 
SetShouldFrameSubmissionBeforeDraw(bool should)4093 void WebDelegate::SetShouldFrameSubmissionBeforeDraw(bool should)
4094 {
4095     auto context = context_.Upgrade();
4096     if (!context) {
4097         return;
4098     }
4099     context->GetTaskExecutor()->PostTask(
4100         [weak = WeakClaim(this), should]() {
4101             auto delegate = weak.Upgrade();
4102             if (!delegate) {
4103                 return;
4104             }
4105             if (delegate->nweb_) {
4106                 delegate->nweb_->SetShouldFrameSubmissionBeforeDraw(should);
4107             }
4108         },
4109         TaskExecutor::TaskType::PLATFORM, "ArkUIWebSetShouldFrameSubmissionBeforeDraw");
4110 }
4111 
NotifyMemoryLevel(int32_t level)4112 void WebDelegate::NotifyMemoryLevel(int32_t level)
4113 {
4114     auto context = context_.Upgrade();
4115     if (!context) {
4116         return;
4117     }
4118     context->GetTaskExecutor()->PostTask(
4119         [weak = WeakClaim(this), level]() {
4120             auto delegate = weak.Upgrade();
4121             if (!delegate) {
4122                 return;
4123             }
4124             if (delegate->nweb_) {
4125                 delegate->nweb_->NotifyMemoryLevel(level);
4126             }
4127         },
4128         TaskExecutor::TaskType::PLATFORM, "ArkUIWebNotifyMemoryLevel");
4129 }
4130 
SetAudioMuted(bool muted)4131 void WebDelegate::SetAudioMuted(bool muted)
4132 {
4133     ACE_DCHECK(nweb_ != nullptr);
4134     if (nweb_) {
4135         nweb_->SetAudioMuted(muted);
4136     }
4137 }
4138 
Zoom(float factor)4139 void WebDelegate::Zoom(float factor)
4140 {
4141     auto context = context_.Upgrade();
4142     if (!context) {
4143         return;
4144     }
4145 
4146     context->GetTaskExecutor()->PostTask(
4147         [weak = WeakClaim(this), factor]() {
4148             auto delegate = weak.Upgrade();
4149             if (!delegate) {
4150                 return;
4151             }
4152             if (delegate->nweb_) {
4153                 delegate->nweb_->Zoom(factor);
4154             }
4155         },
4156         TaskExecutor::TaskType::PLATFORM, "ArkUIWebZoom");
4157 }
4158 
ZoomIn()4159 bool WebDelegate::ZoomIn()
4160 {
4161     auto context = context_.Upgrade();
4162     if (!context) {
4163         return false;
4164     }
4165     bool result = false;
4166     context->GetTaskExecutor()->PostSyncTask(
4167         [weak = WeakClaim(this), &result]() {
4168             auto delegate = weak.Upgrade();
4169             if (!delegate) {
4170                 return;
4171             }
4172             if (delegate->nweb_) {
4173                 result = delegate->nweb_->ZoomIn();
4174             }
4175         },
4176         TaskExecutor::TaskType::PLATFORM, "ArkUIWebZoomIn");
4177     return result;
4178 }
4179 
ZoomOut()4180 bool WebDelegate::ZoomOut()
4181 {
4182     auto context = context_.Upgrade();
4183     if (!context) {
4184         return false;
4185     }
4186     bool result = false;
4187     context->GetTaskExecutor()->PostSyncTask(
4188         [weak = WeakClaim(this), &result]() {
4189             auto delegate = weak.Upgrade();
4190             if (!delegate) {
4191                 return;
4192             }
4193             if (delegate->nweb_) {
4194                 result = delegate->nweb_->ZoomOut();
4195             }
4196         },
4197         TaskExecutor::TaskType::PLATFORM, "ArkUIWebZoomOut");
4198     return result;
4199 }
4200 
CreateWindow()4201 sptr<OHOS::Rosen::Window> WebDelegate::CreateWindow()
4202 {
4203     auto context = context_.Upgrade();
4204     if (!context) {
4205         return nullptr;
4206     }
4207     float scale = context->GetViewScale();
4208 
4209     constexpr int DEFAULT_HEIGHT = 1600;
4210     int DEFAULT_HEIGHT_WITHOUT_SYSTEM_BAR = (int)(scale * context->GetRootHeight());
4211     int DEFAULT_STATUS_BAR_HEIGHT = (DEFAULT_HEIGHT - DEFAULT_HEIGHT_WITHOUT_SYSTEM_BAR) / 2;
4212     constexpr int DEFAULT_LEFT = 0;
4213     int DEFAULT_TOP = DEFAULT_STATUS_BAR_HEIGHT;
4214     int DEFAULT_WIDTH = (int)(scale * context->GetRootWidth());
4215     sptr<Rosen::WindowOption> option = new Rosen::WindowOption();
4216     option->SetWindowRect({ DEFAULT_LEFT, DEFAULT_TOP, DEFAULT_WIDTH, DEFAULT_HEIGHT_WITHOUT_SYSTEM_BAR });
4217     option->SetWindowType(Rosen::WindowType::WINDOW_TYPE_APP_LAUNCHING);
4218     option->SetWindowMode(Rosen::WindowMode::WINDOW_MODE_FLOATING);
4219     auto window = Rosen::Window::Create("ohos_web_window", option);
4220     return window;
4221 }
4222 #endif
4223 
RegisterWebEvent()4224 void WebDelegate::RegisterWebEvent()
4225 {
4226     auto context = DynamicCast<PipelineContext>(context_.Upgrade());
4227     CHECK_NULL_VOID(context);
4228     auto resRegister = context->GetPlatformResRegister();
4229     if (resRegister == nullptr) {
4230         return;
4231     }
4232     resRegister->RegisterEvent(MakeEventHash(WEB_EVENT_PAGESTART), [weak = WeakClaim(this)](const std::string& param) {
4233         auto delegate = weak.Upgrade();
4234         if (delegate) {
4235             delegate->OnPageStarted(param);
4236         }
4237     });
4238     resRegister->RegisterEvent(MakeEventHash(WEB_EVENT_PAGEFINISH), [weak = WeakClaim(this)](const std::string& param) {
4239         auto delegate = weak.Upgrade();
4240         if (delegate) {
4241             delegate->OnPageFinished(param);
4242         }
4243     });
4244     resRegister->RegisterEvent(MakeEventHash(WEB_EVENT_PAGEERROR), [weak = WeakClaim(this)](const std::string& param) {
4245         auto delegate = weak.Upgrade();
4246         if (delegate) {
4247             delegate->OnPageError(param);
4248         }
4249     });
4250     resRegister->RegisterEvent(MakeEventHash(WEB_EVENT_ROUTERPUSH), [weak = WeakClaim(this)](const std::string& param) {
4251         auto delegate = weak.Upgrade();
4252         if (delegate) {
4253             delegate->OnRouterPush(param);
4254         }
4255     });
4256     resRegister->RegisterEvent(MakeEventHash(WEB_EVENT_ONMESSAGE), [weak = WeakClaim(this)](const std::string& param) {
4257         auto delegate = weak.Upgrade();
4258         if (delegate) {
4259             delegate->OnMessage(param);
4260         }
4261     });
4262 }
4263 
4264 // upper ui component which inherited from WebComponent
4265 // could implement some curtain createdCallback to customized controller interface
4266 // eg: web.loadurl.
AddCreatedCallback(const CreatedCallback & createdCallback)4267 void WebDelegate::AddCreatedCallback(const CreatedCallback& createdCallback)
4268 {
4269     ACE_DCHECK(createdCallback != nullptr);
4270     ACE_DCHECK(state_ != State::RELEASED);
4271     createdCallbacks_.emplace_back(createdCallback);
4272 }
4273 
RemoveCreatedCallback()4274 void WebDelegate::RemoveCreatedCallback()
4275 {
4276     ACE_DCHECK(state_ != State::RELEASED);
4277     createdCallbacks_.pop_back();
4278 }
4279 
AddReleasedCallback(const ReleasedCallback & releasedCallback)4280 void WebDelegate::AddReleasedCallback(const ReleasedCallback& releasedCallback)
4281 {
4282     ACE_DCHECK(releasedCallback != nullptr && state_ != State::RELEASED);
4283     releasedCallbacks_.emplace_back(releasedCallback);
4284 }
4285 
RemoveReleasedCallback()4286 void WebDelegate::RemoveReleasedCallback()
4287 {
4288     ACE_DCHECK(state_ != State::RELEASED);
4289     releasedCallbacks_.pop_back();
4290 }
4291 
Reload()4292 void WebDelegate::Reload()
4293 {
4294 #ifdef OHOS_STANDARD_SYSTEM
4295     auto context = context_.Upgrade();
4296     if (!context) {
4297         return;
4298     }
4299     context->GetTaskExecutor()->PostTask(
4300         [weak = WeakClaim(this)]() {
4301             auto delegate = weak.Upgrade();
4302             if (!delegate) {
4303                 return;
4304             }
4305             if (delegate->nweb_) {
4306                 delegate->nweb_->Reload();
4307             }
4308         },
4309         TaskExecutor::TaskType::PLATFORM, "ArkUIWebReload");
4310 #else
4311     hash_ = MakeResourceHash();
4312     reloadMethod_ = MakeMethodHash("reload");
4313     CallResRegisterMethod(reloadMethod_, WEB_PARAM_NONE, nullptr);
4314 #endif
4315 }
4316 
UpdateUrl(const std::string & url)4317 void WebDelegate::UpdateUrl(const std::string& url)
4318 {
4319     hash_ = MakeResourceHash();
4320     updateUrlMethod_ = MakeMethodHash(WEB_METHOD_UPDATEURL);
4321     std::stringstream paramStream;
4322     paramStream << NTC_PARAM_SRC << WEB_PARAM_EQUALS << url;
4323     std::string param = paramStream.str();
4324     CallResRegisterMethod(updateUrlMethod_, param, nullptr);
4325 }
4326 
CallWebRouterBack()4327 void WebDelegate::CallWebRouterBack()
4328 {
4329     hash_ = MakeResourceHash();
4330     routerBackMethod_ = MakeMethodHash(WEB_METHOD_ROUTER_BACK);
4331     CallResRegisterMethod(routerBackMethod_, WEB_PARAM_NONE, nullptr);
4332 }
4333 
CallPopPageSuccessPageUrl(const std::string & url)4334 void WebDelegate::CallPopPageSuccessPageUrl(const std::string& url)
4335 {
4336     hash_ = MakeResourceHash();
4337     changePageUrlMethod_ = MakeMethodHash(WEB_METHOD_CHANGE_PAGE_URL);
4338     std::stringstream paramStream;
4339     paramStream << NTC_PARAM_PAGE_URL << WEB_PARAM_EQUALS << url;
4340     std::string param = paramStream.str();
4341     CallResRegisterMethod(changePageUrlMethod_, param, nullptr);
4342 }
4343 
CallIsPagePathInvalid(const bool & isPageInvalid)4344 void WebDelegate::CallIsPagePathInvalid(const bool& isPageInvalid)
4345 {
4346     hash_ = MakeResourceHash();
4347     isPagePathInvalidMethod_ = MakeMethodHash(WEB_METHOD_PAGE_PATH_INVALID);
4348     std::stringstream paramStream;
4349     paramStream << NTC_PARAM_PAGE_INVALID << WEB_PARAM_EQUALS << isPageInvalid;
4350     std::string param = paramStream.str();
4351     CallResRegisterMethod(isPagePathInvalidMethod_, param, nullptr);
4352 }
4353 
RecordWebEvent(Recorder::EventType eventType,const std::string & param) const4354 void WebDelegate::RecordWebEvent(Recorder::EventType eventType, const std::string& param) const
4355 {
4356     if (!Recorder::EventRecorder::Get().IsComponentRecordEnable()) {
4357         return;
4358     }
4359     auto pattern = webPattern_.Upgrade();
4360     CHECK_NULL_VOID(pattern);
4361     auto host = pattern->GetHost();
4362     CHECK_NULL_VOID(host);
4363     Recorder::EventParamsBuilder builder;
4364     builder.SetId(host->GetInspectorIdValue(""))
4365         .SetType(host->GetHostTag())
4366         .SetEventType(eventType)
4367         .SetText(param)
4368         .SetDescription(host->GetAutoEventParamValue(""));
4369     Recorder::EventRecorder::Get().OnEvent(std::move(builder));
4370 }
4371 
OnPageStarted(const std::string & param)4372 void WebDelegate::OnPageStarted(const std::string& param)
4373 {
4374     auto context = context_.Upgrade();
4375     CHECK_NULL_VOID(context);
4376     context->GetTaskExecutor()->PostTask(
4377         [weak = WeakClaim(this), param]() {
4378             auto delegate = weak.Upgrade();
4379             CHECK_NULL_VOID(delegate);
4380             auto webPattern = delegate->webPattern_.Upgrade();
4381             CHECK_NULL_VOID(webPattern);
4382             auto webEventHub = webPattern->GetWebEventHub();
4383             CHECK_NULL_VOID(webEventHub);
4384             webEventHub->FireOnPageStartedEvent(std::make_shared<LoadWebPageStartEvent>(param));
4385             delegate->RecordWebEvent(Recorder::EventType::WEB_PAGE_BEGIN, param);
4386         },
4387         TaskExecutor::TaskType::JS, "ArkUIWebPageStarted");
4388     auto pattern = webPattern_.Upgrade();
4389     CHECK_NULL_VOID(pattern);
4390     pattern->DestroyAnalyzerOverlay();
4391 }
4392 
OnPageFinished(const std::string & param)4393 void WebDelegate::OnPageFinished(const std::string& param)
4394 {
4395     auto context = context_.Upgrade();
4396     CHECK_NULL_VOID(context);
4397     context->GetTaskExecutor()->PostTask(
4398         [weak = WeakClaim(this), param]() {
4399             auto delegate = weak.Upgrade();
4400             CHECK_NULL_VOID(delegate);
4401             auto webPattern = delegate->webPattern_.Upgrade();
4402             CHECK_NULL_VOID(webPattern);
4403             auto webEventHub = webPattern->GetWebEventHub();
4404             CHECK_NULL_VOID(webEventHub);
4405             webEventHub->FireOnPageFinishedEvent(std::make_shared<LoadWebPageFinishEvent>(param));
4406             webPattern->OnScrollEndRecursive(std::nullopt);
4407             delegate->RecordWebEvent(Recorder::EventType::WEB_PAGE_END, param);
4408         },
4409         TaskExecutor::TaskType::JS, "ArkUIWebPageFinished");
4410 }
4411 
OnProgressChanged(int param)4412 void WebDelegate::OnProgressChanged(int param)
4413 {
4414     auto webPattern = webPattern_.Upgrade();
4415     CHECK_NULL_VOID(webPattern);
4416     webPattern->OnProgressChanged(param);
4417 
4418     auto context = context_.Upgrade();
4419     CHECK_NULL_VOID(context);
4420     context->GetTaskExecutor()->PostTask(
4421         [weak = WeakClaim(this), param]() {
4422             auto delegate = weak.Upgrade();
4423             CHECK_NULL_VOID(delegate);
4424             auto eventParam = std::make_shared<LoadWebProgressChangeEvent>(param);
4425             if (Container::IsCurrentUseNewPipeline()) {
4426                 auto webPattern = delegate->webPattern_.Upgrade();
4427                 CHECK_NULL_VOID(webPattern);
4428                 auto webEventHub = webPattern->GetWebEventHub();
4429                 CHECK_NULL_VOID(webEventHub);
4430                 webEventHub->FireOnProgressChangeEvent(eventParam);
4431                 return;
4432             }
4433             auto webCom = delegate->webComponent_.Upgrade();
4434             CHECK_NULL_VOID(webCom);
4435             webCom->OnProgressChange(eventParam.get());
4436         },
4437         TaskExecutor::TaskType::JS, "ArkUIWebProgressChanged");
4438 }
4439 
OnReceivedTitle(const std::string & param)4440 void WebDelegate::OnReceivedTitle(const std::string& param)
4441 {
4442     auto context = context_.Upgrade();
4443     CHECK_NULL_VOID(context);
4444     context->GetTaskExecutor()->PostTask(
4445         [weak = WeakClaim(this), param]() {
4446             auto delegate = weak.Upgrade();
4447             CHECK_NULL_VOID(delegate);
4448             // ace 2.0
4449             auto onTitleReceiveV2 = delegate->onTitleReceiveV2_;
4450             if (onTitleReceiveV2) {
4451                 onTitleReceiveV2(std::make_shared<LoadWebTitleReceiveEvent>(param));
4452             }
4453         },
4454         TaskExecutor::TaskType::JS, "ArkUIWebReceivedTitle");
4455 }
4456 
ExitFullScreen()4457 void WebDelegate::ExitFullScreen()
4458 {
4459     if (Container::IsCurrentUseNewPipeline()) {
4460         auto webPattern = webPattern_.Upgrade();
4461         CHECK_NULL_VOID(webPattern);
4462         webPattern->ExitFullScreen();
4463     }
4464 }
4465 
OnFullScreenExit()4466 void WebDelegate::OnFullScreenExit()
4467 {
4468     auto context = context_.Upgrade();
4469     CHECK_NULL_VOID(context);
4470     context->GetTaskExecutor()->PostTask(
4471         [weak = WeakClaim(this)]() {
4472             auto delegate = weak.Upgrade();
4473             CHECK_NULL_VOID(delegate);
4474             auto param = std::make_shared<FullScreenExitEvent>(false);
4475 #ifdef NG_BUILD
4476             auto webPattern = delegate->webPattern_.Upgrade();
4477             CHECK_NULL_VOID(webPattern);
4478             auto webEventHub = webPattern->GetWebEventHub();
4479             CHECK_NULL_VOID(webEventHub);
4480             auto propOnFullScreenExitEvent = webEventHub->GetOnFullScreenExitEvent();
4481             CHECK_NULL_VOID(propOnFullScreenExitEvent);
4482             propOnFullScreenExitEvent(param);
4483             return;
4484 #else
4485             if (Container::IsCurrentUseNewPipeline()) {
4486                 auto webPattern = delegate->webPattern_.Upgrade();
4487                 CHECK_NULL_VOID(webPattern);
4488                 auto webEventHub = webPattern->GetWebEventHub();
4489                 CHECK_NULL_VOID(webEventHub);
4490                 auto propOnFullScreenExitEvent = webEventHub->GetOnFullScreenExitEvent();
4491                 CHECK_NULL_VOID(propOnFullScreenExitEvent);
4492                 propOnFullScreenExitEvent(param);
4493                 return;
4494             }
4495             // ace 2.0
4496             auto onFullScreenExitV2 = delegate->onFullScreenExitV2_;
4497             if (onFullScreenExitV2) {
4498                 onFullScreenExitV2(param);
4499             }
4500 #endif
4501         },
4502         TaskExecutor::TaskType::JS, "ArkUIWebFullScreenExit");
4503 }
4504 
OnGeolocationPermissionsHidePrompt()4505 void WebDelegate::OnGeolocationPermissionsHidePrompt()
4506 {
4507     auto context = context_.Upgrade();
4508     CHECK_NULL_VOID(context);
4509     context->GetTaskExecutor()->PostTask(
4510         [weak = WeakClaim(this)]() {
4511             auto delegate = weak.Upgrade();
4512             CHECK_NULL_VOID(delegate);
4513             // ace 2.0
4514             auto onGeolocationHideV2 = delegate->onGeolocationHideV2_;
4515             if (onGeolocationHideV2) {
4516                 onGeolocationHideV2(std::make_shared<LoadWebGeolocationHideEvent>(""));
4517             }
4518         },
4519         TaskExecutor::TaskType::JS, "ArkUIWebGeolocationPermissionsHidePrompt");
4520 }
4521 
OnGeolocationPermissionsShowPrompt(const std::string & origin,const std::shared_ptr<OHOS::NWeb::NWebGeolocationCallbackInterface> & callback)4522 void WebDelegate::OnGeolocationPermissionsShowPrompt(
4523     const std::string& origin, const std::shared_ptr<OHOS::NWeb::NWebGeolocationCallbackInterface>& callback)
4524 {
4525     auto context = context_.Upgrade();
4526     CHECK_NULL_VOID(context);
4527     context->GetTaskExecutor()->PostTask(
4528         [weak = WeakClaim(this), origin, callback]() {
4529             auto delegate = weak.Upgrade();
4530             CHECK_NULL_VOID(delegate);
4531             // ace 2.0
4532             auto onGeolocationShowV2 = delegate->onGeolocationShowV2_;
4533             if (onGeolocationShowV2) {
4534                 auto geolocation =
4535                     AceType::MakeRefPtr<WebGeolocationOhos>(callback,
4536                                                             delegate->incognitoMode_);
4537                 onGeolocationShowV2(std::make_shared<LoadWebGeolocationShowEvent>(origin, geolocation));
4538             }
4539         },
4540         TaskExecutor::TaskType::JS, "ArkUIWebGeolocationPermissionsShowPrompt");
4541 }
4542 
OnPermissionRequestPrompt(const std::shared_ptr<OHOS::NWeb::NWebAccessRequest> & request)4543 void WebDelegate::OnPermissionRequestPrompt(const std::shared_ptr<OHOS::NWeb::NWebAccessRequest>& request)
4544 {
4545     auto context = context_.Upgrade();
4546     CHECK_NULL_VOID(context);
4547     context->GetTaskExecutor()->PostTask(
4548         [weak = WeakClaim(this), request]() {
4549             auto delegate = weak.Upgrade();
4550             CHECK_NULL_VOID(delegate);
4551             if (static_cast<uint32_t>(request->ResourceAcessId())
4552                 & OHOS::NWeb::NWebAccessRequest::Resources::CLIPBOARD_READ_WRITE) {
4553                 auto webPattern = delegate->webPattern_.Upgrade();
4554                 CHECK_NULL_VOID(webPattern);
4555                 auto clipboardCallback = webPattern->GetPermissionClipboardCallback();
4556                 CHECK_NULL_VOID(clipboardCallback);
4557                 clipboardCallback(std::make_shared<WebPermissionRequestEvent>(
4558                     AceType::MakeRefPtr<WebPermissionRequestOhos>(request)));
4559                 return;
4560             }
4561             // ace 2.0
4562             auto onPermissionRequestV2 = delegate->onPermissionRequestV2_;
4563             if (onPermissionRequestV2) {
4564                 onPermissionRequestV2(std::make_shared<WebPermissionRequestEvent>(
4565                     AceType::MakeRefPtr<WebPermissionRequestOhos>(request)));
4566             }
4567         },
4568         TaskExecutor::TaskType::JS, "ArkUIWebPermissionRequestPrompt");
4569 }
4570 
OnScreenCaptureRequest(const std::shared_ptr<OHOS::NWeb::NWebScreenCaptureAccessRequest> & request)4571 void WebDelegate::OnScreenCaptureRequest(const std::shared_ptr<OHOS::NWeb::NWebScreenCaptureAccessRequest>& request)
4572 {
4573     auto context = context_.Upgrade();
4574     CHECK_NULL_VOID(context);
4575     context->GetTaskExecutor()->PostTask(
4576         [weak = WeakClaim(this), request]() {
4577             auto delegate = weak.Upgrade();
4578             CHECK_NULL_VOID(delegate);
4579             // ace 2.0
4580             auto onScreenCaptureRequestV2 = delegate->onScreenCaptureRequestV2_;
4581             if (onScreenCaptureRequestV2) {
4582                 onScreenCaptureRequestV2(std::make_shared<WebScreenCaptureRequestEvent>(
4583                     AceType::MakeRefPtr<WebScreenCaptureRequestOhos>(request)));
4584             }
4585         },
4586         TaskExecutor::TaskType::JS, "ArkUIWebScreenCaptureRequest");
4587 }
4588 
OnConsoleLog(std::shared_ptr<OHOS::NWeb::NWebConsoleLog> message)4589 bool WebDelegate::OnConsoleLog(std::shared_ptr<OHOS::NWeb::NWebConsoleLog> message)
4590 {
4591     auto context = context_.Upgrade();
4592     CHECK_NULL_RETURN(context, false);
4593     bool result = false;
4594     auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
4595     jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), message, &result]() {
4596         auto delegate = weak.Upgrade();
4597         CHECK_NULL_VOID(delegate);
4598         auto param = std::make_shared<LoadWebConsoleLogEvent>(AceType::MakeRefPtr<ConsoleLogOhos>(message));
4599         if (Container::IsCurrentUseNewPipeline()) {
4600             auto webPattern = delegate->webPattern_.Upgrade();
4601             CHECK_NULL_VOID(webPattern);
4602             auto webEventHub = webPattern->GetWebEventHub();
4603             CHECK_NULL_VOID(webEventHub);
4604             auto propOnConsoleEvent = webEventHub->GetOnConsoleEvent();
4605             CHECK_NULL_VOID(propOnConsoleEvent);
4606             result = propOnConsoleEvent(param);
4607         }
4608         auto webCom = delegate->webComponent_.Upgrade();
4609         CHECK_NULL_VOID(webCom);
4610         result = webCom->OnConsole(param.get());
4611         return;
4612     }, "ArkUIWebConsoleLog");
4613     return result;
4614 }
4615 
OnCommonDialog(const std::shared_ptr<BaseEventInfo> & info,DialogEventType dialogEventType)4616 bool WebDelegate::OnCommonDialog(const std::shared_ptr<BaseEventInfo>& info, DialogEventType dialogEventType)
4617 {
4618     auto context = context_.Upgrade();
4619     CHECK_NULL_RETURN(context, false);
4620     bool result = false;
4621     auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
4622     jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), info, dialogEventType, &result]() {
4623         auto delegate = weak.Upgrade();
4624         CHECK_NULL_VOID(delegate);
4625 #ifdef NG_BUILD
4626         auto webPattern = delegate->webPattern_.Upgrade();
4627         CHECK_NULL_VOID(webPattern);
4628         auto webEventHub = webPattern->GetWebEventHub();
4629         CHECK_NULL_VOID(webEventHub);
4630         result = webEventHub->FireOnCommonDialogEvent(info, dialogEventType);
4631         return;
4632 #else
4633         if (Container::IsCurrentUseNewPipeline()) {
4634             auto webPattern = delegate->webPattern_.Upgrade();
4635             CHECK_NULL_VOID(webPattern);
4636             auto webEventHub = webPattern->GetWebEventHub();
4637             CHECK_NULL_VOID(webEventHub);
4638             result = webEventHub->FireOnCommonDialogEvent(info, dialogEventType);
4639             return;
4640         }
4641         auto webCom = delegate->webComponent_.Upgrade();
4642         CHECK_NULL_VOID(webCom);
4643         result = webCom->OnCommonDialog(info.get(), dialogEventType);
4644         return;
4645 #endif
4646     }, "ArkUIWebCommonDialogEvent");
4647     return result;
4648 }
4649 
OnFullScreenEnter(std::shared_ptr<OHOS::NWeb::NWebFullScreenExitHandler> handler,int videoNaturalWidth,int videoNaturalHeight)4650 void WebDelegate::OnFullScreenEnter(
4651     std::shared_ptr<OHOS::NWeb::NWebFullScreenExitHandler> handler, int videoNaturalWidth, int videoNaturalHeight)
4652 {
4653     auto context = context_.Upgrade();
4654     CHECK_NULL_VOID(context);
4655     context->GetTaskExecutor()->PostTask(
4656         [weak = WeakClaim(this), handler, videoNaturalWidth, videoNaturalHeight]() {
4657             auto delegate = weak.Upgrade();
4658             CHECK_NULL_VOID(delegate);
4659             auto param =
4660                 std::make_shared<FullScreenEnterEvent>(AceType::MakeRefPtr<FullScreenExitHandlerOhos>(handler, weak),
4661 		    videoNaturalWidth, videoNaturalHeight);
4662 #ifdef NG_BUILD
4663             auto webPattern = delegate->webPattern_.Upgrade();
4664             CHECK_NULL_VOID(webPattern);
4665             webPattern->RequestFullScreen();
4666             webPattern->SetFullScreenExitHandler(param);
4667             auto webEventHub = webPattern->GetWebEventHub();
4668             CHECK_NULL_VOID(webEventHub);
4669             auto propOnFullScreenEnterEvent = webEventHub->GetOnFullScreenEnterEvent();
4670             CHECK_NULL_VOID(propOnFullScreenEnterEvent);
4671             propOnFullScreenEnterEvent(param);
4672             return;
4673 #else
4674             if (Container::IsCurrentUseNewPipeline()) {
4675                 auto webPattern = delegate->webPattern_.Upgrade();
4676                 CHECK_NULL_VOID(webPattern);
4677                 webPattern->RequestFullScreen();
4678                 webPattern->SetFullScreenExitHandler(param);
4679                 auto webEventHub = webPattern->GetWebEventHub();
4680                 CHECK_NULL_VOID(webEventHub);
4681                 auto propOnFullScreenEnterEvent = webEventHub->GetOnFullScreenEnterEvent();
4682                 CHECK_NULL_VOID(propOnFullScreenEnterEvent);
4683                 propOnFullScreenEnterEvent(param);
4684                 return;
4685             }
4686             auto webCom = delegate->webComponent_.Upgrade();
4687             CHECK_NULL_VOID(webCom);
4688             webCom->OnFullScreenEnter(param.get());
4689 #endif
4690         },
4691         TaskExecutor::TaskType::JS, "ArkUIWebFullScreenEnter");
4692 }
4693 
OnHttpAuthRequest(const std::shared_ptr<BaseEventInfo> & info)4694 bool WebDelegate::OnHttpAuthRequest(const std::shared_ptr<BaseEventInfo>& info)
4695 {
4696     auto context = context_.Upgrade();
4697     CHECK_NULL_RETURN(context, false);
4698     bool result = false;
4699     auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
4700     jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), info, &result]() {
4701         auto delegate = weak.Upgrade();
4702         CHECK_NULL_VOID(delegate);
4703 #ifdef NG_BUILD
4704         auto webPattern = delegate->webPattern_.Upgrade();
4705         CHECK_NULL_VOID(webPattern);
4706         auto webEventHub = webPattern->GetWebEventHub();
4707         CHECK_NULL_VOID(webEventHub);
4708         auto propOnHttpAuthRequestEvent = webEventHub->GetOnHttpAuthRequestEvent();
4709         CHECK_NULL_VOID(propOnHttpAuthRequestEvent);
4710         result = propOnHttpAuthRequestEvent(info);
4711         return;
4712 #else
4713         if (Container::IsCurrentUseNewPipeline()) {
4714             auto webPattern = delegate->webPattern_.Upgrade();
4715             CHECK_NULL_VOID(webPattern);
4716             auto webEventHub = webPattern->GetWebEventHub();
4717             CHECK_NULL_VOID(webEventHub);
4718             auto propOnHttpAuthRequestEvent = webEventHub->GetOnHttpAuthRequestEvent();
4719             CHECK_NULL_VOID(propOnHttpAuthRequestEvent);
4720             result = propOnHttpAuthRequestEvent(info);
4721             return;
4722         }
4723         auto webCom = delegate->webComponent_.Upgrade();
4724         CHECK_NULL_VOID(webCom);
4725         result = webCom->OnHttpAuthRequest(info.get());
4726 #endif
4727     }, "ArkUIWebHttpAuthRequest");
4728     return result;
4729 }
4730 
OnSslErrorRequest(const std::shared_ptr<BaseEventInfo> & info)4731 bool WebDelegate::OnSslErrorRequest(const std::shared_ptr<BaseEventInfo>& info)
4732 {
4733     auto context = context_.Upgrade();
4734     CHECK_NULL_RETURN(context, false);
4735     bool result = false;
4736     auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
4737     jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), info, &result]() {
4738         auto delegate = weak.Upgrade();
4739         CHECK_NULL_VOID(delegate);
4740 #ifdef NG_BUILD
4741         auto webPattern = delegate->webPattern_.Upgrade();
4742         CHECK_NULL_VOID(webPattern);
4743         auto webEventHub = webPattern->GetWebEventHub();
4744         CHECK_NULL_VOID(webEventHub);
4745         auto propOnSslErrorEvent = webEventHub->GetOnSslErrorRequestEvent();
4746         CHECK_NULL_VOID(propOnSslErrorEvent);
4747         result = propOnSslErrorEvent(info);
4748         return;
4749 #else
4750         if (Container::IsCurrentUseNewPipeline()) {
4751             auto webPattern = delegate->webPattern_.Upgrade();
4752             CHECK_NULL_VOID(webPattern);
4753             auto webEventHub = webPattern->GetWebEventHub();
4754             CHECK_NULL_VOID(webEventHub);
4755             auto propOnSslErrorEvent = webEventHub->GetOnSslErrorRequestEvent();
4756             CHECK_NULL_VOID(propOnSslErrorEvent);
4757             result = propOnSslErrorEvent(info);
4758             return;
4759         }
4760         auto webCom = delegate->webComponent_.Upgrade();
4761         CHECK_NULL_VOID(webCom);
4762         result = webCom->OnSslErrorRequest(info.get());
4763 #endif
4764     }, "ArkUIWebSslErrorRequest");
4765     return result;
4766 }
4767 
OnAllSslErrorRequest(const std::shared_ptr<BaseEventInfo> & info)4768 bool WebDelegate::OnAllSslErrorRequest(const std::shared_ptr<BaseEventInfo>& info)
4769 {
4770     auto context = context_.Upgrade();
4771     CHECK_NULL_RETURN(context, false);
4772     bool result = false;
4773     auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
4774     jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), info, &result]() {
4775         auto delegate = weak.Upgrade();
4776         CHECK_NULL_VOID(delegate);
4777         auto webPattern = delegate->webPattern_.Upgrade();
4778         CHECK_NULL_VOID(webPattern);
4779         auto webEventHub = webPattern->GetWebEventHub();
4780         CHECK_NULL_VOID(webEventHub);
4781         auto propOnAllSslErrorEvent = webEventHub->GetOnAllSslErrorRequestEvent();
4782         CHECK_NULL_VOID(propOnAllSslErrorEvent);
4783         result = propOnAllSslErrorEvent(info);
4784         return;
4785     }, "ArkUIWebAllSslErrorRequest");
4786     return result;
4787 }
4788 
OnSslSelectCertRequest(const std::shared_ptr<BaseEventInfo> & info)4789 bool WebDelegate::OnSslSelectCertRequest(const std::shared_ptr<BaseEventInfo>& info)
4790 {
4791     auto context = context_.Upgrade();
4792     CHECK_NULL_RETURN(context, false);
4793     bool result = false;
4794     auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
4795     jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), info, &result]() {
4796         auto delegate = weak.Upgrade();
4797         CHECK_NULL_VOID(delegate);
4798 #ifdef NG_BUILD
4799         auto webPattern = delegate->webPattern_.Upgrade();
4800         CHECK_NULL_VOID(webPattern);
4801         auto webEventHub = webPattern->GetWebEventHub();
4802         CHECK_NULL_VOID(webEventHub);
4803         auto propOnSslSelectCertRequestEvent = webEventHub->GetOnSslSelectCertRequestEvent();
4804         CHECK_NULL_VOID(propOnSslSelectCertRequestEvent);
4805         result = propOnSslSelectCertRequestEvent(info);
4806         return;
4807 #else
4808         if (Container::IsCurrentUseNewPipeline()) {
4809             auto webPattern = delegate->webPattern_.Upgrade();
4810             CHECK_NULL_VOID(webPattern);
4811             auto webEventHub = webPattern->GetWebEventHub();
4812             CHECK_NULL_VOID(webEventHub);
4813             auto propOnSslSelectCertRequestEvent = webEventHub->GetOnSslSelectCertRequestEvent();
4814             CHECK_NULL_VOID(propOnSslSelectCertRequestEvent);
4815             result = propOnSslSelectCertRequestEvent(info);
4816             return;
4817         }
4818         auto webCom = delegate->webComponent_.Upgrade();
4819         CHECK_NULL_VOID(webCom);
4820         result = webCom->OnSslSelectCertRequest(info.get());
4821 #endif
4822     }, "ArkUIWebSslSelectCertRequest");
4823     return result;
4824 }
4825 
OnDownloadStart(const std::string & url,const std::string & userAgent,const std::string & contentDisposition,const std::string & mimetype,long contentLength)4826 void WebDelegate::OnDownloadStart(const std::string& url, const std::string& userAgent,
4827     const std::string& contentDisposition, const std::string& mimetype, long contentLength)
4828 {
4829     auto context = context_.Upgrade();
4830     CHECK_NULL_VOID(context);
4831     context->GetTaskExecutor()->PostTask(
4832         [weak = WeakClaim(this), url, userAgent, contentDisposition, mimetype, contentLength]() {
4833             auto delegate = weak.Upgrade();
4834             CHECK_NULL_VOID(delegate);
4835             auto onDownloadStartV2 = delegate->onDownloadStartV2_;
4836             if (onDownloadStartV2) {
4837                 onDownloadStartV2(
4838                     std::make_shared<DownloadStartEvent>(url, userAgent, contentDisposition, mimetype, contentLength));
4839             }
4840         },
4841         TaskExecutor::TaskType::JS, "ArkUIWebDownloadStart");
4842 }
4843 
OnAccessibilityEvent(int64_t accessibilityId,AccessibilityEventType eventType)4844 void WebDelegate::OnAccessibilityEvent(int64_t accessibilityId, AccessibilityEventType eventType)
4845 {
4846     if (!accessibilityState_) {
4847         return;
4848     }
4849     auto context = context_.Upgrade();
4850     CHECK_NULL_VOID(context);
4851     AccessibilityEvent event;
4852     auto webPattern = webPattern_.Upgrade();
4853     CHECK_NULL_VOID(webPattern);
4854     auto accessibilityManager = context->GetAccessibilityManager();
4855     CHECK_NULL_VOID(accessibilityManager);
4856     if (eventType == AccessibilityEventType::ACCESSIBILITY_FOCUSED) {
4857         webPattern->UpdateFocusedAccessibilityId(accessibilityId);
4858     } else if (eventType == AccessibilityEventType::ACCESSIBILITY_FOCUS_CLEARED ||
4859                eventType == AccessibilityEventType::CLICK) {
4860         webPattern->ClearFocusedAccessibilityId();
4861     } else if (eventType == AccessibilityEventType::PAGE_CHANGE || eventType == AccessibilityEventType::SCROLL_END) {
4862         webPattern->UpdateFocusedAccessibilityId();
4863     }
4864     if (eventType == AccessibilityEventType::CLICK) {
4865         WebComponentClickReport(accessibilityId);
4866     }
4867     if (eventType == AccessibilityEventType::FOCUS) {
4868         TextBlurReportByFocusEvent(accessibilityId);
4869     }
4870     if (eventType == AccessibilityEventType::BLUR) {
4871         TextBlurReportByBlurEvent(accessibilityId);
4872     }
4873     event.nodeId = accessibilityId;
4874     event.type = eventType;
4875     accessibilityManager->SendWebAccessibilityAsyncEvent(event, webPattern);
4876 }
4877 
WebComponentClickReport(int64_t accessibilityId)4878 void WebDelegate::WebComponentClickReport(int64_t accessibilityId)
4879 {
4880     auto webPattern = webPattern_.Upgrade();
4881     CHECK_NULL_VOID(webPattern);
4882     auto webAccessibilityNode = webPattern->GetAccessibilityNodeById(accessibilityId);
4883     CHECK_NULL_VOID(webAccessibilityNode);
4884     auto webComponentClickCallback = webPattern->GetWebComponentClickCallback();
4885     CHECK_NULL_VOID(webComponentClickCallback);
4886     webComponentClickCallback(accessibilityId, webAccessibilityNode->GetContent());
4887 }
4888 
TextBlurReportByFocusEvent(int64_t accessibilityId)4889 void WebDelegate::TextBlurReportByFocusEvent(int64_t accessibilityId)
4890 {
4891     auto webPattern = webPattern_.Upgrade();
4892     CHECK_NULL_VOID(webPattern);
4893     auto textBlurCallback = webPattern->GetTextBlurCallback();
4894     CHECK_NULL_VOID(textBlurCallback);
4895     auto lastFocusNode = webPattern->GetAccessibilityNodeById(lastFocusInputId_);
4896     if (lastFocusNode && lastFocusNode->GetIsEditable() && lastFocusInputId_ != accessibilityId) {
4897         if (lastFocusNode->GetIsPassword()) {
4898             TAG_LOGW(AceLogTag::ACE_WEB, "the input type is password, do not report");
4899         } else {
4900             std::string blurText = lastFocusNode->GetContent();
4901             if (!blurText.empty()) {
4902                 TAG_LOGD(AceLogTag::ACE_WEB, "report text blur, the content length is %{public}u",
4903                     static_cast<int32_t>(blurText.length()));
4904                 textBlurCallback(lastFocusInputId_, blurText);
4905                 lastFocusReportId_ = lastFocusInputId_;
4906             }
4907         }
4908     }
4909     if (accessibilityId != 0) {
4910         auto focusNode = webPattern->GetAccessibilityNodeById(accessibilityId);
4911         if (focusNode) {
4912             // record last editable focus id
4913             lastFocusInputId_ = accessibilityId;
4914         }
4915     }
4916 }
4917 
TextBlurReportByBlurEvent(int64_t accessibilityId)4918 void WebDelegate::TextBlurReportByBlurEvent(int64_t accessibilityId)
4919 {
4920     auto webPattern = webPattern_.Upgrade();
4921     CHECK_NULL_VOID(webPattern);
4922     auto textBlurCallback = webPattern->GetTextBlurCallback();
4923     CHECK_NULL_VOID(textBlurCallback);
4924     auto blurNode = webPattern->GetAccessibilityNodeById(accessibilityId);
4925     if (blurNode && blurNode->GetIsEditable() && lastFocusReportId_ != accessibilityId) {
4926         std::string blurText = blurNode->GetContent();
4927         if (!blurNode->GetIsPassword() && !blurText.empty()) {
4928             TAG_LOGD(AceLogTag::ACE_WEB, "report text blur, the content length is %{public}u",
4929                 static_cast<int32_t>(blurText.length()));
4930             textBlurCallback(accessibilityId, blurText);
4931         }
4932     }
4933 }
4934 
OnErrorReceive(std::shared_ptr<OHOS::NWeb::NWebUrlResourceRequest> request,std::shared_ptr<OHOS::NWeb::NWebUrlResourceError> error)4935 void WebDelegate::OnErrorReceive(std::shared_ptr<OHOS::NWeb::NWebUrlResourceRequest> request,
4936     std::shared_ptr<OHOS::NWeb::NWebUrlResourceError> error)
4937 {
4938     auto context = context_.Upgrade();
4939     CHECK_NULL_VOID(context);
4940     context->GetTaskExecutor()->PostTask(
4941         [weak = WeakClaim(this), request, error]() {
4942             auto delegate = weak.Upgrade();
4943             CHECK_NULL_VOID(delegate);
4944             auto webPattern = delegate->webPattern_.Upgrade();
4945             CHECK_NULL_VOID(webPattern);
4946             auto webEventHub = webPattern->GetWebEventHub();
4947             CHECK_NULL_VOID(webEventHub);
4948             webEventHub->FireOnErrorReceiveEvent(std::make_shared<ReceivedErrorEvent>(
4949                     AceType::MakeRefPtr<WebRequest>(request->RequestHeaders(), request->Method(), request->Url(),
4950                         request->FromGesture(), request->IsAboutMainFrame(), request->IsRequestRedirect()),
4951                     AceType::MakeRefPtr<WebError>(error->ErrorInfo(), error->ErrorCode())));
4952         },
4953         TaskExecutor::TaskType::JS, "ArkUIWebErrorReceive");
4954 }
4955 
OnHttpErrorReceive(std::shared_ptr<OHOS::NWeb::NWebUrlResourceRequest> request,std::shared_ptr<OHOS::NWeb::NWebUrlResourceResponse> response)4956 void WebDelegate::OnHttpErrorReceive(std::shared_ptr<OHOS::NWeb::NWebUrlResourceRequest> request,
4957     std::shared_ptr<OHOS::NWeb::NWebUrlResourceResponse> response)
4958 {
4959     if (onHttpErrorReceiveV2_) {
4960         onHttpErrorReceiveV2_(std::make_shared<ReceivedHttpErrorEvent>(
4961             AceType::MakeRefPtr<WebRequest>(request->RequestHeaders(), request->Method(), request->Url(),
4962                 request->FromGesture(), request->IsAboutMainFrame(), request->IsRequestRedirect()),
4963             AceType::MakeRefPtr<WebResponse>(response->ResponseHeaders(), response->ResponseData(),
4964                 response->ResponseEncoding(), response->ResponseMimeType(), response->ResponseStatus(),
4965                 response->ResponseStatusCode())));
4966     }
4967 }
4968 
IsEmptyOnInterceptRequest()4969 bool WebDelegate::IsEmptyOnInterceptRequest()
4970 {
4971 #ifdef NG_BUILD
4972     auto webPattern = webPattern_.Upgrade();
4973     CHECK_NULL_RETURN(webPattern, false);
4974     auto webEventHub = webPattern->GetWebEventHub();
4975     CHECK_NULL_RETURN(webEventHub, false);
4976     return webEventHub->GetOnInterceptRequestEvent() == nullptr;
4977 #else
4978     if (Container::IsCurrentUseNewPipeline()) {
4979         auto webPattern = webPattern_.Upgrade();
4980         CHECK_NULL_RETURN(webPattern, false);
4981         auto webEventHub = webPattern->GetWebEventHub();
4982         CHECK_NULL_RETURN(webEventHub, false);
4983         return webEventHub->GetOnInterceptRequestEvent() == nullptr;
4984     }
4985     auto webCom = webComponent_.Upgrade();
4986     CHECK_NULL_RETURN(webCom, true);
4987     return webCom->IsEmptyOnInterceptRequest();
4988 #endif
4989 }
4990 
OnInterceptRequest(const std::shared_ptr<BaseEventInfo> & info)4991 RefPtr<WebResponse> WebDelegate::OnInterceptRequest(const std::shared_ptr<BaseEventInfo>& info)
4992 {
4993     auto context = context_.Upgrade();
4994     CHECK_NULL_RETURN(context, nullptr);
4995     RefPtr<WebResponse> result = nullptr;
4996     auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
4997     jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), info, &result]() {
4998         auto delegate = weak.Upgrade();
4999         CHECK_NULL_VOID(delegate);
5000         if (Container::IsCurrentUseNewPipeline()) {
5001             auto webPattern = delegate->webPattern_.Upgrade();
5002             CHECK_NULL_VOID(webPattern);
5003             auto webEventHub = webPattern->GetWebEventHub();
5004             CHECK_NULL_VOID(webEventHub);
5005             auto propOnInterceptRequestEvent = webEventHub->GetOnInterceptRequestEvent();
5006             CHECK_NULL_VOID(propOnInterceptRequestEvent);
5007             result = propOnInterceptRequestEvent(info);
5008         }
5009         auto webCom = delegate->webComponent_.Upgrade();
5010         CHECK_NULL_VOID(webCom);
5011         result = webCom->OnInterceptRequest(info.get());
5012     }, "ArkUIWebInterceptRequest");
5013     return result;
5014 }
5015 
OnTooltip(const std::string & tooltip)5016 void WebDelegate::OnTooltip(const std::string& tooltip)
5017 {
5018     auto context = context_.Upgrade();
5019     CHECK_NULL_VOID(context);
5020     context->GetTaskExecutor()->PostTask(
5021         [weak = WeakClaim(this), tooltip]() {
5022             auto delegate = weak.Upgrade();
5023             CHECK_NULL_VOID(delegate);
5024             auto webPattern = delegate->webPattern_.Upgrade();
5025             CHECK_NULL_VOID(webPattern);
5026             webPattern->OnTooltip(tooltip);
5027         },
5028         TaskExecutor::TaskType::UI, "ArkUIWebTooltip");
5029 }
5030 
OnRequestFocus()5031 void WebDelegate::OnRequestFocus()
5032 {
5033     if (onRequestFocusV2_) {
5034         onRequestFocusV2_(std::make_shared<LoadWebRequestFocusEvent>(""));
5035     }
5036 }
5037 
OnRenderExited(OHOS::NWeb::RenderExitReason reason)5038 void WebDelegate::OnRenderExited(OHOS::NWeb::RenderExitReason reason)
5039 {
5040     auto context = context_.Upgrade();
5041     CHECK_NULL_VOID(context);
5042     context->GetTaskExecutor()->PostTask(
5043         [weak = WeakClaim(this), reason]() {
5044             auto delegate = weak.Upgrade();
5045             CHECK_NULL_VOID(delegate);
5046             auto onRenderExitedV2 = delegate->onRenderExitedV2_;
5047             if (onRenderExitedV2) {
5048                 onRenderExitedV2(std::make_shared<RenderExitedEvent>(static_cast<int32_t>(reason)));
5049             }
5050         },
5051         TaskExecutor::TaskType::JS, "ArkUIWebRenderExited");
5052 }
5053 
OnRefreshAccessedHistory(const std::string & url,bool isRefreshed)5054 void WebDelegate::OnRefreshAccessedHistory(const std::string& url, bool isRefreshed)
5055 {
5056     auto context = context_.Upgrade();
5057     CHECK_NULL_VOID(context);
5058     context->GetTaskExecutor()->PostTask(
5059         [weak = WeakClaim(this), url, isRefreshed]() {
5060             auto delegate = weak.Upgrade();
5061             CHECK_NULL_VOID(delegate);
5062             auto onRefreshAccessedHistoryV2 = delegate->onRefreshAccessedHistoryV2_;
5063             if (onRefreshAccessedHistoryV2) {
5064                 onRefreshAccessedHistoryV2(std::make_shared<RefreshAccessedHistoryEvent>(url, isRefreshed));
5065             }
5066         },
5067         TaskExecutor::TaskType::JS, "ArkUIWebRefreshAccessedHistory");
5068 }
5069 
OnPageError(const std::string & param)5070 void WebDelegate::OnPageError(const std::string& param)
5071 {
5072     if (onPageError_) {
5073         int32_t errorCode = GetIntParam(param, NTC_PARAM_ERROR_CODE);
5074         std::string url = GetUrlStringParam(param, NTC_PARAM_URL);
5075         std::string description = GetStringParam(param, NTC_PARAM_DESCRIPTION);
5076 
5077         std::string paramUrl = std::string(R"(")").append(url).append(std::string(R"(")")).append(",");
5078 
5079         std::string paramErrorCode = std::string(R"(")")
5080                                          .append(NTC_PARAM_ERROR_CODE)
5081                                          .append(std::string(R"(")"))
5082                                          .append(":")
5083                                          .append(std::to_string(errorCode))
5084                                          .append(",");
5085 
5086         std::string paramDesc = std::string(R"(")")
5087                                     .append(NTC_PARAM_DESCRIPTION)
5088                                     .append(std::string(R"(")"))
5089                                     .append(":")
5090                                     .append(std::string(R"(")").append(description).append(std::string(R"(")")));
5091         std::string errorParam =
5092             std::string(R"("error",{"url":)").append((paramUrl + paramErrorCode + paramDesc).append("},null"));
5093         onPageError_(errorParam);
5094     }
5095 }
5096 
OnMessage(const std::string & param)5097 void WebDelegate::OnMessage(const std::string& param)
5098 {
5099     std::string removeQuotes = param;
5100     removeQuotes.erase(std::remove(removeQuotes.begin(), removeQuotes.end(), '\"'), removeQuotes.end());
5101     if (onMessage_) {
5102         std::string paramMessage = std::string(R"(")").append(removeQuotes).append(std::string(R"(")"));
5103         std::string messageParam = std::string(R"("message",{"message":)").append(paramMessage.append("},null"));
5104         onMessage_(messageParam);
5105     }
5106 }
5107 
OnRouterPush(const std::string & param)5108 void WebDelegate::OnRouterPush(const std::string& param)
5109 {
5110     OHOS::Ace::Framework::DelegateClient::GetInstance().RouterPush(param);
5111 }
5112 
OnFileSelectorShow(const std::shared_ptr<BaseEventInfo> & info)5113 bool WebDelegate::OnFileSelectorShow(const std::shared_ptr<BaseEventInfo>& info)
5114 {
5115     auto context = context_.Upgrade();
5116     CHECK_NULL_RETURN(context, false);
5117     bool result = false;
5118     auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
5119     jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), info, &result]() {
5120         auto delegate = weak.Upgrade();
5121         CHECK_NULL_VOID(delegate);
5122         if (Container::IsCurrentUseNewPipeline()) {
5123             auto webPattern = delegate->webPattern_.Upgrade();
5124             CHECK_NULL_VOID(webPattern);
5125             auto webEventHub = webPattern->GetWebEventHub();
5126             CHECK_NULL_VOID(webEventHub);
5127             auto propOnFileSelectorShowEvent = webEventHub->GetOnFileSelectorShowEvent();
5128             CHECK_NULL_VOID(propOnFileSelectorShowEvent);
5129             result = propOnFileSelectorShowEvent(info);
5130         }
5131         auto webCom = delegate->webComponent_.Upgrade();
5132         CHECK_NULL_VOID(webCom);
5133         result = webCom->OnFileSelectorShow(info.get());
5134     }, "ArkUIWebFileSelectorShow");
5135 
5136     if (!result) {
5137         TAG_LOGI(AceLogTag::ACE_WEB, "default file selector show handled");
5138         auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
5139         jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), info, &result]() {
5140             auto delegate = weak.Upgrade();
5141             CHECK_NULL_VOID(delegate);
5142             auto webPattern = delegate->webPattern_.Upgrade();
5143             CHECK_NULL_VOID(webPattern);
5144             auto fileSelectCallback = webPattern->GetDefaultFileSelectorShowCallback();
5145             CHECK_NULL_VOID(fileSelectCallback);
5146             fileSelectCallback(info);
5147             result = true;
5148             }, "ArkUIWebDefaultFileSelectorShow");
5149     }
5150     return result;
5151 }
5152 
OnContextMenuShow(const std::shared_ptr<BaseEventInfo> & info)5153 bool WebDelegate::OnContextMenuShow(const std::shared_ptr<BaseEventInfo>& info)
5154 {
5155     auto context = context_.Upgrade();
5156     CHECK_NULL_RETURN(context, false);
5157     bool result = false;
5158     auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
5159     jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), info, &result]() {
5160         auto delegate = weak.Upgrade();
5161         CHECK_NULL_VOID(delegate);
5162 #ifdef NG_BUILD
5163         auto webPattern = delegate->webPattern_.Upgrade();
5164         CHECK_NULL_VOID(webPattern);
5165         if (delegate->richtextData_) {
5166             webPattern->OnContextMenuShow(info, true, true);
5167             result = true;
5168         }
5169         auto webEventHub = webPattern->GetWebEventHub();
5170         CHECK_NULL_VOID(webEventHub);
5171         auto propOnContextMenuShowEvent = webEventHub->GetOnContextMenuShowEvent();
5172         CHECK_NULL_VOID(propOnContextMenuShowEvent);
5173         result = propOnContextMenuShowEvent(info);
5174         if (!delegate->richtextData_) {
5175             webPattern->OnContextMenuShow(info, false, result);
5176         }
5177         return;
5178 #else
5179         if (Container::IsCurrentUseNewPipeline()) {
5180             auto webPattern = delegate->webPattern_.Upgrade();
5181             CHECK_NULL_VOID(webPattern);
5182             if (delegate->richtextData_) {
5183                 webPattern->OnContextMenuShow(info, true, true);
5184                 result = true;
5185             }
5186             auto webEventHub = webPattern->GetWebEventHub();
5187             CHECK_NULL_VOID(webEventHub);
5188             auto propOnContextMenuShowEvent = webEventHub->GetOnContextMenuShowEvent();
5189             CHECK_NULL_VOID(propOnContextMenuShowEvent);
5190             result = propOnContextMenuShowEvent(info);
5191             if (!delegate->richtextData_) {
5192                 webPattern->OnContextMenuShow(info, false, result);
5193             }
5194             return;
5195         }
5196         auto webCom = delegate->webComponent_.Upgrade();
5197         CHECK_NULL_VOID(webCom);
5198         result = webCom->OnContextMenuShow(info.get());
5199 #endif
5200     }, "ArkUIWebContextMenuShow");
5201     return result;
5202 }
5203 
OnContextMenuHide(const std::string & info)5204 void WebDelegate::OnContextMenuHide(const std::string& info)
5205 {
5206     auto context = context_.Upgrade();
5207     CHECK_NULL_VOID(context);
5208     auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
5209     jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), info]() {
5210         auto delegate = weak.Upgrade();
5211         CHECK_NULL_VOID(delegate);
5212         if (Container::IsCurrentUseNewPipeline()) {
5213             auto webPattern = delegate->webPattern_.Upgrade();
5214             CHECK_NULL_VOID(webPattern);
5215             webPattern->OnContextMenuHide();
5216             auto webEventHub = webPattern->GetWebEventHub();
5217             CHECK_NULL_VOID(webEventHub);
5218             auto propOnContextMenuHideEvent = webEventHub->GetOnContextMenuHideEvent();
5219             CHECK_NULL_VOID(propOnContextMenuHideEvent);
5220             propOnContextMenuHideEvent(std::make_shared<ContextMenuHideEvent>(info));
5221             return;
5222         } else {
5223             TAG_LOGW(AceLogTag::ACE_WEB, "current is not new pipeline");
5224         }
5225     }, "ArkUIWebContextMenuHide");
5226     return;
5227 }
5228 
OnHandleInterceptUrlLoading(const std::string & data)5229 bool WebDelegate::OnHandleInterceptUrlLoading(const std::string& data)
5230 {
5231     auto context = context_.Upgrade();
5232     CHECK_NULL_RETURN(context, false);
5233     bool result = false;
5234     auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
5235     jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), data, &result]() {
5236         auto delegate = weak.Upgrade();
5237         CHECK_NULL_VOID(delegate);
5238         auto param = std::make_shared<UrlLoadInterceptEvent>(data);
5239         if (Container::IsCurrentUseNewPipeline()) {
5240             auto webPattern = delegate->webPattern_.Upgrade();
5241             CHECK_NULL_VOID(webPattern);
5242             auto webEventHub = webPattern->GetWebEventHub();
5243             CHECK_NULL_VOID(webEventHub);
5244             auto propOnUrlLoadInterceptEvent = webEventHub->GetOnUrlLoadInterceptEvent();
5245             CHECK_NULL_VOID(propOnUrlLoadInterceptEvent);
5246             result = propOnUrlLoadInterceptEvent(param);
5247         }
5248         auto webCom = delegate->webComponent_.Upgrade();
5249         CHECK_NULL_VOID(webCom);
5250         result = webCom->OnUrlLoadIntercept(param.get());
5251     }, "ArkUIWebHandleInterceptUrlLoading");
5252     return result;
5253 }
5254 
OnHandleInterceptLoading(std::shared_ptr<OHOS::NWeb::NWebUrlResourceRequest> request)5255 bool WebDelegate::OnHandleInterceptLoading(std::shared_ptr<OHOS::NWeb::NWebUrlResourceRequest> request)
5256 {
5257     auto context = context_.Upgrade();
5258     CHECK_NULL_RETURN(context, false);
5259     bool result = false;
5260     auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
5261     jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), request, &result]() {
5262         auto delegate = weak.Upgrade();
5263         CHECK_NULL_VOID(delegate);
5264         auto webRequest = AceType::MakeRefPtr<WebRequest>(request->RequestHeaders(), request->Method(), request->Url(),
5265             request->FromGesture(), request->IsAboutMainFrame(), request->IsRequestRedirect());
5266         auto param = std::make_shared<LoadInterceptEvent>(webRequest);
5267         if (Container::IsCurrentUseNewPipeline()) {
5268             auto webPattern = delegate->webPattern_.Upgrade();
5269             CHECK_NULL_VOID(webPattern);
5270             auto webEventHub = webPattern->GetWebEventHub();
5271             CHECK_NULL_VOID(webEventHub);
5272             auto propOnLoadInterceptEvent = webEventHub->GetOnLoadInterceptEvent();
5273             CHECK_NULL_VOID(propOnLoadInterceptEvent);
5274             result = propOnLoadInterceptEvent(param);
5275         }
5276         auto webCom = delegate->webComponent_.Upgrade();
5277         CHECK_NULL_VOID(webCom);
5278         result = webCom->OnLoadIntercept(param.get());
5279     }, "ArkUIWebHandleInterceptLoading");
5280     return result;
5281 }
5282 
OnResourceLoad(const std::string & url)5283 void WebDelegate::OnResourceLoad(const std::string& url)
5284 {
5285     if (onResourceLoadV2_) {
5286         onResourceLoadV2_(std::make_shared<ResourceLoadEvent>(url));
5287     }
5288 }
5289 
OnScaleChange(float oldScaleFactor,float newScaleFactor)5290 void WebDelegate::OnScaleChange(float oldScaleFactor, float newScaleFactor)
5291 {
5292     auto context = context_.Upgrade();
5293     CHECK_NULL_VOID(context);
5294     context->GetTaskExecutor()->PostTask(
5295         [weak = WeakClaim(this), oldScaleFactor, newScaleFactor]() {
5296             auto delegate = weak.Upgrade();
5297             CHECK_NULL_VOID(delegate);
5298             auto onScaleChangeV2 = delegate->onScaleChangeV2_;
5299             if (onScaleChangeV2) {
5300                 onScaleChangeV2(std::make_shared<ScaleChangeEvent>(oldScaleFactor, newScaleFactor));
5301             }
5302         },
5303         TaskExecutor::TaskType::JS, "ArkUIWebScaleChange");
5304 }
5305 
OnScroll(double xOffset,double yOffset)5306 void WebDelegate::OnScroll(double xOffset, double yOffset)
5307 {
5308     auto context = context_.Upgrade();
5309     CHECK_NULL_VOID(context);
5310     context->GetTaskExecutor()->PostTask(
5311         [weak = WeakClaim(this), xOffset, yOffset]() {
5312             auto delegate = weak.Upgrade();
5313             CHECK_NULL_VOID(delegate);
5314             auto onScrollV2 = delegate->onScrollV2_;
5315             if (onScrollV2) {
5316                 onScrollV2(std::make_shared<WebOnScrollEvent>(xOffset, yOffset));
5317             }
5318         },
5319         TaskExecutor::TaskType::JS, "ArkUIWebScroll");
5320 }
5321 
OnSearchResultReceive(int activeMatchOrdinal,int numberOfMatches,bool isDoneCounting)5322 void WebDelegate::OnSearchResultReceive(int activeMatchOrdinal, int numberOfMatches, bool isDoneCounting)
5323 {
5324     auto context = context_.Upgrade();
5325     CHECK_NULL_VOID(context);
5326     context->GetTaskExecutor()->PostTask(
5327         [weak = WeakClaim(this), activeMatchOrdinal, numberOfMatches, isDoneCounting]() {
5328             auto delegate = weak.Upgrade();
5329             CHECK_NULL_VOID(delegate);
5330             auto onSearchResultReceiveV2 = delegate->onSearchResultReceiveV2_;
5331             if (onSearchResultReceiveV2) {
5332                 onSearchResultReceiveV2(
5333                     std::make_shared<SearchResultReceiveEvent>(activeMatchOrdinal, numberOfMatches, isDoneCounting));
5334             }
5335         },
5336         TaskExecutor::TaskType::JS, "ArkUIWebSearchResultReceive");
5337 }
5338 
OnDragAndDropData(const void * data,size_t len,int width,int height)5339 bool WebDelegate::OnDragAndDropData(const void* data, size_t len, int width, int height)
5340 {
5341     pixelMap_ = PixelMap::ConvertSkImageToPixmap(static_cast<const uint32_t*>(data), len, width, height);
5342     if (pixelMap_ == nullptr) {
5343         return false;
5344     }
5345     isRefreshPixelMap_ = true;
5346 
5347     auto webPattern = webPattern_.Upgrade();
5348     if (!webPattern) {
5349         return false;
5350     }
5351     return webPattern->NotifyStartDragTask();
5352 }
5353 
OnDragAndDropDataUdmf(std::shared_ptr<OHOS::NWeb::NWebDragData> dragData)5354 bool WebDelegate::OnDragAndDropDataUdmf(std::shared_ptr<OHOS::NWeb::NWebDragData> dragData)
5355 {
5356     const void* data = nullptr;
5357     size_t len = 0;
5358     int width = 0;
5359     int height = 0;
5360     dragData->GetPixelMapSetting(&data, len, width, height);
5361     pixelMap_ = PixelMap::ConvertSkImageToPixmap(static_cast<const uint32_t*>(data), len, width, height);
5362     CHECK_NULL_RETURN(pixelMap_, false);
5363     isRefreshPixelMap_ = true;
5364 
5365     dragData_ = dragData;
5366     auto webPattern = webPattern_.Upgrade();
5367     CHECK_NULL_RETURN(webPattern, false);
5368 
5369     if (webPattern->IsRootNeedExportTexture()) {
5370         return false;
5371     }
5372 
5373     if (dragData->IsDragNewStyle() && (!webPattern->IsNewDragStyle() || !webPattern->IsPreviewImageNodeExist())) {
5374         TAG_LOGI(AceLogTag::ACE_WEB, "OnDragAndDropDataUdmf not a new style");
5375         auto context = context_.Upgrade();
5376         CHECK_NULL_RETURN(context, false);
5377         CHECK_NULL_RETURN(context->GetTaskExecutor(), false);
5378         context->GetTaskExecutor()->PostDelayedTask(
5379             [weak = WeakClaim(this)]() {
5380                 auto delegate = weak.Upgrade();
5381                 CHECK_NULL_VOID(delegate);
5382                 auto pattern = delegate->webPattern_.Upgrade();
5383                 pattern->NotifyStartDragTask(true);
5384             },
5385             TaskExecutor::TaskType::UI, DRAG_DELAY_MILLISECONDS, "OnDragAndDropDataUdmf");
5386         return true;
5387     } else if (!dragData->IsDragNewStyle()) {
5388         webPattern->SetNewDragStyle(false);
5389     }
5390     return webPattern->NotifyStartDragTask();
5391 }
5392 
IsDragging()5393 bool WebDelegate::IsDragging()
5394 {
5395     auto webPattern = webPattern_.Upgrade();
5396     CHECK_NULL_RETURN(webPattern, false);
5397     return webPattern->IsDragging();
5398 }
5399 
IsImageDrag()5400 bool WebDelegate::IsImageDrag()
5401 {
5402     if (dragData_) {
5403         return dragData_->IsSingleImageContent();
5404     }
5405     return false;
5406 }
5407 
GetOrCreateDragData()5408 std::shared_ptr<OHOS::NWeb::NWebDragData> WebDelegate::GetOrCreateDragData()
5409 {
5410     if (dragData_) {
5411         return dragData_;
5412     }
5413 
5414     if (nweb_) {
5415         dragData_ = nweb_->GetOrCreateDragData();
5416         return dragData_;
5417     }
5418     return nullptr;
5419 }
5420 
OnWindowNew(const std::string & targetUrl,bool isAlert,bool isUserTrigger,const std::shared_ptr<OHOS::NWeb::NWebControllerHandler> & handler)5421 void WebDelegate::OnWindowNew(const std::string& targetUrl, bool isAlert, bool isUserTrigger,
5422     const std::shared_ptr<OHOS::NWeb::NWebControllerHandler>& handler)
5423 {
5424     auto context = context_.Upgrade();
5425     CHECK_NULL_VOID(context);
5426     context->GetTaskExecutor()->PostSyncTask(
5427         [weak = WeakClaim(this), targetUrl, isAlert, isUserTrigger, handler]() {
5428             auto delegate = weak.Upgrade();
5429             CHECK_NULL_VOID(delegate);
5430             int32_t parentNWebId = (delegate->nweb_ ? static_cast<int32_t>(delegate->nweb_->GetWebId()) : -1);
5431             auto param = std::make_shared<WebWindowNewEvent>(
5432                 targetUrl, isAlert, isUserTrigger, AceType::MakeRefPtr<WebWindowNewHandlerOhos>(handler, parentNWebId));
5433 #ifdef NG_BUILD
5434             auto webPattern = delegate->webPattern_.Upgrade();
5435             CHECK_NULL_VOID(webPattern);
5436             auto webEventHub = webPattern->GetWebEventHub();
5437             CHECK_NULL_VOID(webEventHub);
5438             auto propOnWindowNewEvent = webEventHub->GetOnWindowNewEvent();
5439             CHECK_NULL_VOID(propOnWindowNewEvent);
5440             propOnWindowNewEvent(param);
5441             return;
5442 #else
5443             if (Container::IsCurrentUseNewPipeline()) {
5444                 auto webPattern = delegate->webPattern_.Upgrade();
5445                 CHECK_NULL_VOID(webPattern);
5446                 auto webEventHub = webPattern->GetWebEventHub();
5447                 CHECK_NULL_VOID(webEventHub);
5448                 auto propOnWindowNewEvent = webEventHub->GetOnWindowNewEvent();
5449                 CHECK_NULL_VOID(propOnWindowNewEvent);
5450                 propOnWindowNewEvent(param);
5451                 return;
5452             }
5453             auto webCom = delegate->webComponent_.Upgrade();
5454             CHECK_NULL_VOID(webCom);
5455             webCom->OnWindowNewEvent(param);
5456 #endif
5457         },
5458         TaskExecutor::TaskType::JS, "ArkUIWebWindowNewEvent");
5459 }
5460 
OnWindowExit()5461 void WebDelegate::OnWindowExit()
5462 {
5463     auto context = context_.Upgrade();
5464     CHECK_NULL_VOID(context);
5465     context->GetTaskExecutor()->PostTask(
5466         [weak = WeakClaim(this)]() {
5467             auto delegate = weak.Upgrade();
5468             CHECK_NULL_VOID(delegate);
5469             auto onWindowExitV2 = delegate->onWindowExitV2_;
5470             if (onWindowExitV2) {
5471                 onWindowExitV2(std::make_shared<WebWindowExitEvent>());
5472             }
5473         },
5474         TaskExecutor::TaskType::JS, "ArkUIWebWindowExit");
5475 }
5476 
OnPageVisible(const std::string & url)5477 void WebDelegate::OnPageVisible(const std::string& url)
5478 {
5479     TAG_LOGI(AceLogTag::ACE_WEB, "WebDelegate::OnPageVisible, web id = %{public}d", GetWebId());
5480     if (onPageVisibleV2_) {
5481         onPageVisibleV2_(std::make_shared<PageVisibleEvent>(url));
5482     } else {
5483         TAG_LOGI(AceLogTag::ACE_WEB, "The developer has not registered this OnPageVisible event");
5484     }
5485 
5486     if (isEnableHardwareComposition_) {
5487         return;
5488     }
5489     auto context = context_.Upgrade();
5490     CHECK_NULL_VOID(context);
5491     context->GetTaskExecutor()->PostDelayedTask(
5492         [weak = WeakClaim(this)]() {
5493             auto delegate = weak.Upgrade();
5494             CHECK_NULL_VOID(delegate);
5495             delegate->EnableHardware();
5496         },
5497         TaskExecutor::TaskType::UI, DELAY_MILLISECONDS_1000, "ArkUIWebEnableHardware");
5498 }
5499 
OnFirstContentfulPaint(int64_t navigationStartTick,int64_t firstContentfulPaintMs)5500 void WebDelegate::OnFirstContentfulPaint(int64_t navigationStartTick, int64_t firstContentfulPaintMs)
5501 {
5502     TAG_LOGI(AceLogTag::ACE_WEB, "WebDelegate::OnFirstContentfulPaint, web id = %{public}d", GetWebId());
5503     if (onFirstContentfulPaintV2_) {
5504         onFirstContentfulPaintV2_(
5505             std::make_shared<FirstContentfulPaintEvent>(navigationStartTick, firstContentfulPaintMs));
5506     }
5507 }
5508 
OnFirstMeaningfulPaint(std::shared_ptr<OHOS::NWeb::NWebFirstMeaningfulPaintDetails> details)5509 void WebDelegate::OnFirstMeaningfulPaint(std::shared_ptr<OHOS::NWeb::NWebFirstMeaningfulPaintDetails> details)
5510 {
5511     TAG_LOGI(AceLogTag::ACE_WEB, "WebDelegate::OnFirstMeaningfulPaint, web id = %{public}d", GetWebId());
5512     if (OnFirstMeaningfulPaintV2_) {
5513         OnFirstMeaningfulPaintV2_(std::make_shared<FirstMeaningfulPaintEvent>(
5514             details->GetNavigationStartTime(), details->GetFirstMeaningfulPaintTime()));
5515     }
5516 }
5517 
OnLargestContentfulPaint(std::shared_ptr<OHOS::NWeb::NWebLargestContentfulPaintDetails> details)5518 void WebDelegate::OnLargestContentfulPaint(std::shared_ptr<OHOS::NWeb::NWebLargestContentfulPaintDetails> details)
5519 {
5520     TAG_LOGI(AceLogTag::ACE_WEB, "WebDelegate::OnLargestContentfulPaint, web id = %{public}d", GetWebId());
5521     if (OnLargestContentfulPaintV2_) {
5522         OnLargestContentfulPaintV2_(std::make_shared<LargestContentfulPaintEvent>(details->GetNavigationStartTime(),
5523             details->GetLargestImagePaintTime(), details->GetLargestTextPaintTime(),
5524             details->GetLargestImageLoadStartTime(), details->GetLargestImageLoadEndTime(), details->GetImageBPP()));
5525     }
5526 }
5527 
EnableHardware()5528 void WebDelegate::EnableHardware()
5529 {
5530     if (isEnableHardwareComposition_) {
5531         return;
5532     }
5533 
5534     auto surfaceNode = OHOS::Rosen::RSBaseNode::ReinterpretCast<OHOS::Rosen::RSSurfaceNode>(surfaceRsNode_);
5535     CHECK_NULL_VOID(surfaceNode);
5536     TAG_LOGI(AceLogTag::ACE_WEB, "WebDelegate::EnableHardware, web id = %{public}d", GetWebId());
5537     ACE_SCOPED_TRACE("WebDelegate::EnableHardware, web id = %d", GetWebId());
5538     surfaceNode->SetHardwareEnabled(true);
5539     isEnableHardwareComposition_ = true;
5540 }
5541 
OnSafeBrowsingCheckResult(int threat_type)5542 void WebDelegate::OnSafeBrowsingCheckResult(int threat_type)
5543 {
5544     if (onSafeBrowsingCheckResultV2_) {
5545         onSafeBrowsingCheckResultV2_(
5546             std::make_shared<SafeBrowsingCheckResultEvent>(threat_type));
5547     }
5548 }
5549 
OnDataResubmitted(std::shared_ptr<OHOS::NWeb::NWebDataResubmissionCallback> handler)5550 void WebDelegate::OnDataResubmitted(std::shared_ptr<OHOS::NWeb::NWebDataResubmissionCallback> handler)
5551 {
5552     auto param = std::make_shared<DataResubmittedEvent>(AceType::MakeRefPtr<DataResubmittedOhos>(handler));
5553     if (Container::IsCurrentUseNewPipeline()) {
5554         auto webPattern = webPattern_.Upgrade();
5555         CHECK_NULL_VOID(webPattern);
5556         auto webEventHub = webPattern->GetWebEventHub();
5557         CHECK_NULL_VOID(webEventHub);
5558         auto propOnDataResubmittedEvent = webEventHub->GetOnDataResubmittedEvent();
5559         CHECK_NULL_VOID(propOnDataResubmittedEvent);
5560         propOnDataResubmittedEvent(param);
5561         return;
5562     }
5563 }
5564 
OnNavigationEntryCommitted(std::shared_ptr<OHOS::NWeb::NWebLoadCommittedDetails> details)5565 void WebDelegate::OnNavigationEntryCommitted(std::shared_ptr<OHOS::NWeb::NWebLoadCommittedDetails> details)
5566 {
5567     if (onNavigationEntryCommittedV2_) {
5568         NavigationType type = static_cast<NavigationType>(details->GetNavigationType());
5569         onNavigationEntryCommittedV2_(std::make_shared<NavigationEntryCommittedEvent>(details->GetURL(),
5570             type, details->IsMainFrame(), details->IsSameDocument(),
5571             details->DidReplaceEntry()));
5572     }
5573     auto webPattern = webPattern_.Upgrade();
5574     CHECK_NULL_VOID(webPattern);
5575     webPattern->DestroyAnalyzerOverlay();
5576 }
5577 
OnFaviconReceived(const void * data,size_t width,size_t height,OHOS::NWeb::ImageColorType colorType,OHOS::NWeb::ImageAlphaType alphaType)5578 void WebDelegate::OnFaviconReceived(const void* data, size_t width, size_t height, OHOS::NWeb::ImageColorType colorType,
5579     OHOS::NWeb::ImageAlphaType alphaType)
5580 {
5581     auto param = std::make_shared<FaviconReceivedEvent>(
5582         AceType::MakeRefPtr<FaviconReceivedOhos>(data, width, height, colorType, alphaType));
5583     if (Container::IsCurrentUseNewPipeline()) {
5584         auto webPattern = webPattern_.Upgrade();
5585         CHECK_NULL_VOID(webPattern);
5586         auto webEventHub = webPattern->GetWebEventHub();
5587         CHECK_NULL_VOID(webEventHub);
5588         auto propOnFaviconReceivedEvent = webEventHub->GetOnFaviconReceivedEvent();
5589         CHECK_NULL_VOID(propOnFaviconReceivedEvent);
5590         propOnFaviconReceivedEvent(param);
5591         return;
5592     }
5593 }
5594 
OnTouchIconUrl(const std::string & iconUrl,bool precomposed)5595 void WebDelegate::OnTouchIconUrl(const std::string& iconUrl, bool precomposed)
5596 {
5597     if (onTouchIconUrlV2_) {
5598         onTouchIconUrlV2_(std::make_shared<TouchIconUrlEvent>(iconUrl, precomposed));
5599     }
5600 }
5601 
OnAudioStateChanged(bool audible)5602 void WebDelegate::OnAudioStateChanged(bool audible)
5603 {
5604     if (onAudioStateChangedV2_) {
5605         onAudioStateChangedV2_(std::make_shared<AudioStateChangedEvent>(audible));
5606     }
5607 }
5608 
OnGetTouchHandleHotZone(std::shared_ptr<OHOS::NWeb::NWebTouchHandleHotZone> hotZone)5609 void WebDelegate::OnGetTouchHandleHotZone(std::shared_ptr<OHOS::NWeb::NWebTouchHandleHotZone> hotZone)
5610 {
5611     auto pipeline = PipelineContext::GetCurrentContext();
5612     CHECK_NULL_VOID(pipeline);
5613     auto theme = pipeline->GetTheme<TextOverlayTheme>();
5614     CHECK_NULL_VOID(theme);
5615     auto touchHandleSize = theme->GetHandleHotZoneRadius().ConvertToPx();
5616     if (hotZone) {
5617         hotZone->SetWidth(touchHandleSize);
5618         hotZone->SetHeight(touchHandleSize);
5619     }
5620 }
5621 
GetDragPixelMap()5622 RefPtr<PixelMap> WebDelegate::GetDragPixelMap()
5623 {
5624     return pixelMap_;
5625 }
5626 
5627 #ifdef OHOS_STANDARD_SYSTEM
HandleTouchDown(const int32_t & id,const double & x,const double & y,bool from_overlay)5628 void WebDelegate::HandleTouchDown(const int32_t& id, const double& x, const double& y, bool from_overlay)
5629 {
5630     ACE_DCHECK(nweb_ != nullptr);
5631     if (nweb_) {
5632         ResSchedReport::GetInstance().ResSchedDataReport("web_gesture");
5633         nweb_->OnTouchPress(id, x, y, from_overlay);
5634     }
5635 }
5636 
HandleTouchUp(const int32_t & id,const double & x,const double & y,bool from_overlay)5637 void WebDelegate::HandleTouchUp(const int32_t& id, const double& x, const double& y, bool from_overlay)
5638 {
5639     ACE_DCHECK(nweb_ != nullptr);
5640     if (nweb_) {
5641         ResSchedReport::GetInstance().ResSchedDataReport("web_gesture");
5642         nweb_->OnTouchRelease(id, x, y, from_overlay);
5643     }
5644 }
5645 
HandleTouchMove(const int32_t & id,const double & x,const double & y,bool from_overlay)5646 void WebDelegate::HandleTouchMove(const int32_t& id, const double& x, const double& y, bool from_overlay)
5647 {
5648     ACE_DCHECK(nweb_ != nullptr);
5649     if (nweb_) {
5650         nweb_->OnTouchMove(id, x, y, from_overlay);
5651     }
5652 }
5653 
HandleTouchMove(const std::vector<std::shared_ptr<OHOS::NWeb::NWebTouchPointInfo>> & touch_point_infos,bool from_overlay)5654 void WebDelegate::HandleTouchMove(const std::vector<std::shared_ptr<OHOS::NWeb::NWebTouchPointInfo>> &touch_point_infos,
5655                                   bool from_overlay)
5656 {
5657     ACE_DCHECK(nweb_ != nullptr);
5658     if (nweb_) {
5659         nweb_->OnTouchMove(touch_point_infos, from_overlay);
5660     }
5661 }
5662 
HandleTouchCancel()5663 void WebDelegate::HandleTouchCancel()
5664 {
5665     ACE_DCHECK(nweb_ != nullptr);
5666     if (nweb_) {
5667         nweb_->OnTouchCancel();
5668     }
5669 }
5670 
HandleTouchpadFlingEvent(const double & x,const double & y,const double & vx,const double & vy)5671 void WebDelegate::HandleTouchpadFlingEvent(const double& x, const double& y, const double& vx, const double& vy)
5672 {
5673     if (nweb_) {
5674         nweb_->SendTouchpadFlingEvent(x, y, vx, vy);
5675     }
5676 }
5677 
WebHandleTouchpadFlingEvent(const double & x,const double & y,const double & vx,const double & vy,const std::vector<int32_t> & pressedCodes)5678 void WebDelegate::WebHandleTouchpadFlingEvent(const double& x, const double& y,
5679     const double& vx, const double& vy, const std::vector<int32_t>& pressedCodes)
5680 {
5681     if (nweb_) {
5682         nweb_->WebSendTouchpadFlingEvent(x, y, vx, vy, pressedCodes);
5683     }
5684 }
5685 
HandleAxisEvent(const double & x,const double & y,const double & deltaX,const double & deltaY)5686 void WebDelegate::HandleAxisEvent(const double& x, const double& y, const double& deltaX, const double& deltaY)
5687 {
5688     if (nweb_) {
5689         nweb_->SendMouseWheelEvent(x, y, deltaX, deltaY);
5690     }
5691 }
5692 
WebHandleAxisEvent(const double & x,const double & y,const double & deltaX,const double & deltaY,const std::vector<int32_t> & pressedCodes)5693 void WebDelegate::WebHandleAxisEvent(const double& x, const double& y,
5694     const double& deltaX, const double& deltaY, const std::vector<int32_t>& pressedCodes)
5695 {
5696     if (nweb_) {
5697         nweb_->WebSendMouseWheelEvent(x, y, deltaX, deltaY, pressedCodes);
5698     }
5699 }
5700 
OnKeyEvent(int32_t keyCode,int32_t keyAction)5701 bool WebDelegate::OnKeyEvent(int32_t keyCode, int32_t keyAction)
5702 {
5703     if (nweb_) {
5704         return nweb_->SendKeyEvent(keyCode, keyAction);
5705     }
5706     return false;
5707 }
5708 
WebOnKeyEvent(int32_t keyCode,int32_t keyAction,const std::vector<int32_t> & pressedCodes)5709 bool WebDelegate::WebOnKeyEvent(int32_t keyCode, int32_t keyAction,
5710     const std::vector<int32_t>& pressedCodes)
5711 {
5712     CHECK_NULL_RETURN(nweb_, false);
5713     return nweb_->WebSendKeyEvent(keyCode, keyAction, pressedCodes);
5714 }
5715 
OnMouseEvent(int32_t x,int32_t y,const MouseButton button,const MouseAction action,int count)5716 void WebDelegate::OnMouseEvent(int32_t x, int32_t y, const MouseButton button, const MouseAction action, int count)
5717 {
5718     if (nweb_) {
5719         nweb_->SendMouseEvent(x, y, static_cast<int>(button), static_cast<int>(action), count);
5720     }
5721 }
5722 
OnFocus(const OHOS::NWeb::FocusReason & reason)5723 void WebDelegate::OnFocus(const OHOS::NWeb::FocusReason& reason)
5724 {
5725     ACE_DCHECK(nweb_ != nullptr);
5726     if (nweb_) {
5727         nweb_->OnFocus(reason);
5728     }
5729 }
5730 
NeedSoftKeyboard()5731 bool WebDelegate::NeedSoftKeyboard()
5732 {
5733     if (nweb_) {
5734         return nweb_->NeedSoftKeyboard();
5735     }
5736     return false;
5737 }
5738 
OnBlur()5739 void WebDelegate::OnBlur()
5740 {
5741     ACE_DCHECK(nweb_ != nullptr);
5742     if (nweb_) {
5743         nweb_->OnBlur(blurReason_);
5744     }
5745 }
5746 
UpdateClippedSelectionBounds(int32_t x,int32_t y,int32_t w,int32_t h)5747 void WebDelegate::UpdateClippedSelectionBounds(int32_t x, int32_t y, int32_t w, int32_t h)
5748 {
5749     auto webPattern = webPattern_.Upgrade();
5750     CHECK_NULL_VOID(webPattern);
5751     webPattern->UpdateClippedSelectionBounds(x, y, w, h);
5752 }
5753 
RunQuickMenu(std::shared_ptr<OHOS::NWeb::NWebQuickMenuParams> params,std::shared_ptr<OHOS::NWeb::NWebQuickMenuCallback> callback)5754 bool WebDelegate::RunQuickMenu(std::shared_ptr<OHOS::NWeb::NWebQuickMenuParams> params,
5755     std::shared_ptr<OHOS::NWeb::NWebQuickMenuCallback> callback)
5756 {
5757 #ifdef NG_BUILD
5758     auto webPattern = webPattern_.Upgrade();
5759     CHECK_NULL_RETURN(webPattern, false);
5760     return webPattern->RunQuickMenu(params, callback);
5761 #else
5762     if (Container::IsCurrentUseNewPipeline()) {
5763         auto webPattern = webPattern_.Upgrade();
5764         CHECK_NULL_RETURN(webPattern, false);
5765         return webPattern->RunQuickMenu(params, callback);
5766     }
5767     auto renderWeb = renderWeb_.Upgrade();
5768     if (!renderWeb || !params || !callback) {
5769         return false;
5770     }
5771 
5772     return renderWeb->RunQuickMenu(params, callback);
5773 #endif
5774 }
5775 
HideHandleAndQuickMenuIfNecessary(bool hide)5776 void WebDelegate::HideHandleAndQuickMenuIfNecessary(bool hide)
5777 {
5778     auto webPattern = webPattern_.Upgrade();
5779     CHECK_NULL_VOID(webPattern);
5780     webPattern->HideHandleAndQuickMenuIfNecessary(hide);
5781 }
5782 
ChangeVisibilityOfQuickMenu()5783 void WebDelegate::ChangeVisibilityOfQuickMenu()
5784 {
5785     auto webPattern = webPattern_.Upgrade();
5786     CHECK_NULL_VOID(webPattern);
5787     webPattern->ChangeVisibilityOfQuickMenu();
5788 }
5789 
OnQuickMenuDismissed()5790 void WebDelegate::OnQuickMenuDismissed()
5791 {
5792 #ifdef NG_BUILD
5793     auto webPattern = webPattern_.Upgrade();
5794     CHECK_NULL_VOID(webPattern);
5795     webPattern->OnQuickMenuDismissed();
5796     return;
5797 #else
5798     if (Container::IsCurrentUseNewPipeline()) {
5799         auto webPattern = webPattern_.Upgrade();
5800         CHECK_NULL_VOID(webPattern);
5801         webPattern->OnQuickMenuDismissed();
5802         return;
5803     }
5804     auto renderWeb = renderWeb_.Upgrade();
5805     CHECK_NULL_VOID(renderWeb);
5806     renderWeb->OnQuickMenuDismissed();
5807 #endif
5808 }
5809 
OnTouchSelectionChanged(std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> insertHandle,std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> startSelectionHandle,std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> endSelectionHandle)5810 void WebDelegate::OnTouchSelectionChanged(std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> insertHandle,
5811     std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> startSelectionHandle,
5812     std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> endSelectionHandle)
5813 {
5814 #ifdef NG_BUILD
5815     auto webPattern = webPattern_.Upgrade();
5816     CHECK_NULL_VOID(webPattern);
5817     webPattern->OnTouchSelectionChanged(insertHandle, startSelectionHandle, endSelectionHandle);
5818     return;
5819 #else
5820     if (Container::IsCurrentUseNewPipeline()) {
5821         auto webPattern = webPattern_.Upgrade();
5822         CHECK_NULL_VOID(webPattern);
5823         webPattern->OnTouchSelectionChanged(insertHandle, startSelectionHandle, endSelectionHandle);
5824         return;
5825     }
5826     auto renderWeb = renderWeb_.Upgrade();
5827     CHECK_NULL_VOID(renderWeb);
5828     renderWeb->OnTouchSelectionChanged(insertHandle, startSelectionHandle, endSelectionHandle);
5829 #endif
5830 }
5831 
OnCursorChange(const OHOS::NWeb::CursorType & type,std::shared_ptr<OHOS::NWeb::NWebCursorInfo> info)5832 bool WebDelegate::OnCursorChange(const OHOS::NWeb::CursorType& type, std::shared_ptr<OHOS::NWeb::NWebCursorInfo> info)
5833 {
5834 #ifdef NG_BUILD
5835     auto webPattern = webPattern_.Upgrade();
5836     CHECK_NULL_RETURN(webPattern, false);
5837     return webPattern->OnCursorChange(type, info);
5838 #else
5839     if (Container::IsCurrentUseNewPipeline()) {
5840         auto webPattern = webPattern_.Upgrade();
5841         CHECK_NULL_RETURN(webPattern, false);
5842         return webPattern->OnCursorChange(type, info);
5843     }
5844     auto renderWeb = renderWeb_.Upgrade();
5845     CHECK_NULL_RETURN(renderWeb, false);
5846     return renderWeb->OnCursorChange(type, info);
5847 #endif
5848 }
5849 
OnSelectPopupMenu(std::shared_ptr<OHOS::NWeb::NWebSelectPopupMenuParam> params,std::shared_ptr<OHOS::NWeb::NWebSelectPopupMenuCallback> callback)5850 void WebDelegate::OnSelectPopupMenu(std::shared_ptr<OHOS::NWeb::NWebSelectPopupMenuParam> params,
5851     std::shared_ptr<OHOS::NWeb::NWebSelectPopupMenuCallback> callback)
5852 {
5853 #ifdef NG_BUILD
5854     auto webPattern = webPattern_.Upgrade();
5855     CHECK_NULL_VOID(webPattern);
5856     webPattern->OnSelectPopupMenu(params, callback);
5857     return;
5858 #else
5859     if (Container::IsCurrentUseNewPipeline()) {
5860         auto webPattern = webPattern_.Upgrade();
5861         CHECK_NULL_VOID(webPattern);
5862         webPattern->OnSelectPopupMenu(params, callback);
5863         return;
5864     }
5865     auto renderWeb = renderWeb_.Upgrade();
5866     CHECK_NULL_VOID(renderWeb);
5867     return renderWeb->OnSelectPopupMenu(params, callback);
5868 #endif
5869 }
5870 
HandleDragEvent(int32_t x,int32_t y,const DragAction & dragAction)5871 void WebDelegate::HandleDragEvent(int32_t x, int32_t y, const DragAction& dragAction)
5872 {
5873     if (nweb_) {
5874         std::shared_ptr<NWebDragEventImpl> dragEvent =
5875 	    std::make_shared<NWebDragEventImpl>(x, y, static_cast<OHOS::NWeb::DragAction>(dragAction));
5876         nweb_->SendDragEvent(dragEvent);
5877     }
5878 }
5879 
GetUrl()5880 std::string WebDelegate::GetUrl()
5881 {
5882     if (nweb_) {
5883         return nweb_->GetUrl();
5884     }
5885     return "";
5886 }
5887 
UpdateLocale()5888 void WebDelegate::UpdateLocale()
5889 {
5890     ACE_DCHECK(nweb_ != nullptr);
5891     if (nweb_) {
5892         std::string language = AceApplicationInfo::GetInstance().GetLanguage();
5893         std::string region = AceApplicationInfo::GetInstance().GetCountryOrRegion();
5894         if (!language.empty() || !region.empty()) {
5895             nweb_->UpdateLocale(language, region);
5896         }
5897     }
5898 }
5899 
SetDrawRect(int32_t x,int32_t y,int32_t width,int32_t height)5900 void WebDelegate::SetDrawRect(int32_t x, int32_t y, int32_t width, int32_t height)
5901 {
5902     ACE_DCHECK(nweb_ != nullptr);
5903     if (nweb_) {
5904         nweb_->SetDrawRect(x, y, width, height);
5905     }
5906 }
5907 
GetPendingSizeStatus()5908 bool WebDelegate::GetPendingSizeStatus()
5909 {
5910     ACE_DCHECK(nweb_ != nullptr);
5911     if (nweb_) {
5912         return nweb_->GetPendingSizeStatus();
5913     }
5914     return false;
5915 }
5916 
NotifyAutoFillViewData(const std::string & jsonStr)5917 void WebDelegate::NotifyAutoFillViewData(const std::string& jsonStr)
5918 {
5919     auto context = context_.Upgrade();
5920     CHECK_NULL_VOID(context);
5921     context->GetTaskExecutor()->PostTask(
5922         [weak = WeakClaim(this), jsonStr]() {
5923             auto delegate = weak.Upgrade();
5924             CHECK_NULL_VOID(delegate);
5925             CHECK_NULL_VOID(delegate->nweb_);
5926             auto webMessage = std::make_shared<OHOS::NWeb::NWebMessage>(NWebValue::Type::NONE);
5927             webMessage->SetType(NWebValue::Type::STRING);
5928             webMessage->SetString(jsonStr);
5929             delegate->nweb_->FillAutofillData(webMessage);
5930         },
5931         TaskExecutor::TaskType::PLATFORM, "ArkUIWebNotifyAutoFillViewData");
5932 }
5933 
AutofillCancel(const std::string & fillContent)5934 void WebDelegate::AutofillCancel(const std::string& fillContent)
5935 {
5936     auto context = context_.Upgrade();
5937     CHECK_NULL_VOID(context);
5938     context->GetTaskExecutor()->PostTask(
5939         [weak = WeakClaim(this), fillContent]() {
5940             auto delegate = weak.Upgrade();
5941             CHECK_NULL_VOID(delegate);
5942             CHECK_NULL_VOID(delegate->nweb_);
5943             delegate->nweb_->OnAutofillCancel(fillContent);
5944         },
5945         TaskExecutor::TaskType::UI, "ArkUIWebAutofillCancel");
5946 }
5947 
HandleAutoFillEvent(const std::shared_ptr<OHOS::NWeb::NWebMessage> & viewDataJson)5948 bool WebDelegate::HandleAutoFillEvent(const std::shared_ptr<OHOS::NWeb::NWebMessage>& viewDataJson)
5949 {
5950     auto pattern = webPattern_.Upgrade();
5951     CHECK_NULL_RETURN(pattern, false);
5952     return pattern->HandleAutoFillEvent(viewDataJson);
5953 }
5954 
HandleAccessibilityHoverEvent(int32_t x,int32_t y)5955 void WebDelegate::HandleAccessibilityHoverEvent(int32_t x, int32_t y)
5956 {
5957     ACE_DCHECK(nweb_ != nullptr);
5958     if (nweb_) {
5959         nweb_->SendAccessibilityHoverEvent(x, y);
5960     }
5961 }
5962 
5963 #endif
5964 
GetUrlStringParam(const std::string & param,const std::string & name) const5965 std::string WebDelegate::GetUrlStringParam(const std::string& param, const std::string& name) const
5966 {
5967     size_t len = name.length();
5968     size_t posErrorCode = param.find(NTC_PARAM_ERROR_CODE);
5969     size_t pos = param.find(name);
5970     std::string result;
5971 
5972     if (pos != std::string::npos && posErrorCode != std::string::npos) {
5973         std::stringstream ss;
5974 
5975         ss << param.substr(pos + 1 + len, posErrorCode - 5);
5976         ss >> result;
5977     }
5978     return result;
5979 }
5980 
SetRenderMode(RenderMode renderMode)5981 void WebDelegate::SetRenderMode(RenderMode renderMode)
5982 {
5983     renderMode_ = static_cast<int32_t>(renderMode);
5984 }
5985 
SetFitContentMode(WebLayoutMode layoutMode)5986 void WebDelegate::SetFitContentMode(WebLayoutMode layoutMode)
5987 {
5988     layoutMode_ = static_cast<int32_t>(layoutMode);
5989 }
5990 
BindRouterBackMethod()5991 void WebDelegate::BindRouterBackMethod()
5992 {
5993     auto context = context_.Upgrade();
5994     if (context) {
5995         context->SetRouterBackEventHandler([weak = WeakClaim(this)] {
5996             auto delegate = weak.Upgrade();
5997             if (delegate) {
5998                 delegate->CallWebRouterBack();
5999             }
6000         });
6001     }
6002 }
6003 
BindPopPageSuccessMethod()6004 void WebDelegate::BindPopPageSuccessMethod()
6005 {
6006     auto context = context_.Upgrade();
6007     if (context) {
6008         context->SetPopPageSuccessEventHandler(
6009             [weak = WeakClaim(this)](const std::string& pageUrl, const int32_t pageId) {
6010                 std::string url = pageUrl.substr(0, pageUrl.length() - 3);
6011                 auto delegate = weak.Upgrade();
6012                 if (delegate) {
6013                     delegate->CallPopPageSuccessPageUrl(url);
6014                 }
6015             });
6016     }
6017 }
6018 
BindIsPagePathInvalidMethod()6019 void WebDelegate::BindIsPagePathInvalidMethod()
6020 {
6021     auto context = context_.Upgrade();
6022     if (context) {
6023         context->SetIsPagePathInvalidEventHandler([weak = WeakClaim(this)](bool& isPageInvalid) {
6024             auto delegate = weak.Upgrade();
6025             if (delegate) {
6026                 delegate->CallIsPagePathInvalid(isPageInvalid);
6027             }
6028         });
6029     }
6030 }
6031 
SetComponent(const RefPtr<WebComponent> & component)6032 void WebDelegate::SetComponent(const RefPtr<WebComponent>& component)
6033 {
6034     webComponent_ = component;
6035 }
6036 
SetNGWebPattern(const RefPtr<NG::WebPattern> & webPattern)6037 void WebDelegate::SetNGWebPattern(const RefPtr<NG::WebPattern>& webPattern)
6038 {
6039     webPattern_ = webPattern;
6040 }
6041 
SetDrawSize(const Size & drawSize)6042 void WebDelegate::SetDrawSize(const Size& drawSize)
6043 {
6044     drawSize_ = drawSize;
6045 }
6046 
SetEnhanceSurfaceFlag(const bool & isEnhanceSurface)6047 void WebDelegate::SetEnhanceSurfaceFlag(const bool& isEnhanceSurface)
6048 {
6049     isEnhanceSurface_ = isEnhanceSurface;
6050 }
6051 
GetSurfaceDelegateClient()6052 sptr<OHOS::SurfaceDelegate> WebDelegate::GetSurfaceDelegateClient()
6053 {
6054     return surfaceDelegate_;
6055 }
6056 
SetBoundsOrResize(const Size & drawSize,const Offset & offset,bool isKeyboard)6057 void WebDelegate::SetBoundsOrResize(const Size& drawSize, const Offset& offset, bool isKeyboard)
6058 {
6059     if ((drawSize.Width() == 0) && (drawSize.Height() == 0)) {
6060         return;
6061     }
6062     if (isEnhanceSurface_) {
6063         if (surfaceDelegate_) {
6064             if (needResizeAtFirst_) {
6065                 Resize(drawSize.Width(), drawSize.Height(), isKeyboard);
6066                 needResizeAtFirst_ = false;
6067             }
6068             Size webSize = GetEnhanceSurfaceSize(drawSize);
6069             surfaceDelegate_->SetBounds(offset.GetX(), (int32_t)offset.GetY(), webSize.Width(), webSize.Height());
6070         }
6071     } else {
6072         Resize(drawSize.Width(), drawSize.Height(), isKeyboard);
6073     }
6074 }
6075 
ResizeVisibleViewport(const Size & visibleSize,bool isKeyboard)6076 void WebDelegate::ResizeVisibleViewport(const Size& visibleSize, bool isKeyboard)
6077 {
6078     double width = visibleSize.Width();
6079     double height = visibleSize.Height();
6080     if (NearEqual(resizeVisibleWidth_, width) && NearEqual(resizeVisibleHeight_, height)) {
6081         return;
6082     }
6083     resizeVisibleWidth_ = width;
6084     resizeVisibleHeight_ = height;
6085     auto context = context_.Upgrade();
6086     if (!context) {
6087         return;
6088     }
6089     context->GetTaskExecutor()->PostTask(
6090         [weak = WeakClaim(this), width, height, isKeyboard]() {
6091             auto delegate = weak.Upgrade();
6092             if (delegate && delegate->nweb_ && !delegate->window_) {
6093                 delegate->nweb_->ResizeVisibleViewport(
6094                     width < 0 ? 0 : std::ceil(width), height < 0 ? 0 : std::ceil(height), isKeyboard);
6095             }
6096         },
6097         TaskExecutor::TaskType::PLATFORM, "ArkUIWebResizeVisibleViewport");
6098     auto webPattern = webPattern_.Upgrade();
6099     CHECK_NULL_VOID(webPattern);
6100     webPattern->DestroyAnalyzerOverlay();
6101 }
6102 
GetWebRenderGlobalPos()6103 Offset WebDelegate::GetWebRenderGlobalPos()
6104 {
6105     return offset_;
6106 }
6107 
GetEnhanceSurfaceSize(const Size & drawSize)6108 Size WebDelegate::GetEnhanceSurfaceSize(const Size& drawSize)
6109 {
6110     auto pipeline = PipelineBase::GetCurrentContext();
6111     CHECK_NULL_RETURN(pipeline, Size());
6112     double dipScale = pipeline->GetDipScale();
6113     if (NearZero(dipScale)) {
6114         return Size();
6115     }
6116     int width = std::ceil(std::floor(drawSize.Width() / dipScale) * dipScale);
6117     int height = std::ceil(std::floor(drawSize.Height() / dipScale) * dipScale);
6118     if (width <= 0) {
6119         width = 1;
6120     }
6121     if (height <= 0) {
6122         height = 1;
6123     }
6124     return Size(width, height);
6125 }
6126 
GetAudioStateChangedCallback(bool useNewPipe,const RefPtr<NG::WebEventHub> & eventHub)6127 WebDelegate::EventCallbackV2 WebDelegate::GetAudioStateChangedCallback(
6128     bool useNewPipe, const RefPtr<NG::WebEventHub>& eventHub)
6129 {
6130     if (eventHub && useNewPipe) {
6131         return eventHub->GetOnAudioStateChangedEvent();
6132     }
6133     return nullptr;
6134 }
6135 
6136 #ifdef ENABLE_ROSEN_BACKEND
SetSurface(const sptr<Surface> & surface)6137 void WebDelegate::SetSurface(const sptr<Surface>& surface)
6138 {
6139     surface_ = surface;
6140     auto webPattern = webPattern_.Upgrade();
6141     CHECK_NULL_VOID(webPattern);
6142     auto host = webPattern->GetHost();
6143     CHECK_NULL_VOID(host);
6144     auto renderContext = host->GetRenderContext();
6145     CHECK_NULL_VOID(renderContext);
6146     auto rosenRenderContext = AceType::DynamicCast<NG::RosenRenderContext>(renderContext);
6147     CHECK_NULL_VOID(rosenRenderContext);
6148     rsNode_ = rosenRenderContext->GetRSNode();
6149     CHECK_NULL_VOID(rsNode_);
6150     surfaceNodeId_ = webPattern->GetWebSurfaceNodeId();
6151     surfaceRsNode_ = webPattern->GetSurfaceRSNode();
6152 }
6153 #endif
6154 
UpdateScreenOffSet(double & offsetX,double & offsetY)6155 void WebDelegate::UpdateScreenOffSet(double& offsetX, double& offsetY)
6156 {
6157 #ifdef NG_BUILD
6158     auto webPattern = webPattern_.Upgrade();
6159     CHECK_NULL_VOID(webPattern);
6160     offsetX += webPattern->GetHost()->GetTransformRelativeOffset().GetX();
6161     offsetY += webPattern->GetHost()->GetTransformRelativeOffset().GetY();
6162     auto context = context_.Upgrade();
6163     CHECK_NULL_VOID(context);
6164     auto windowOffset = context->GetDisplayWindowRectInfo().GetOffset();
6165     offsetX += windowOffset.GetX();
6166     offsetY += windowOffset.GetY();
6167     return;
6168 #else
6169     if (Container::IsCurrentUseNewPipeline()) {
6170         auto webPattern = webPattern_.Upgrade();
6171         CHECK_NULL_VOID(webPattern);
6172         offsetX += webPattern->GetHost()->GetTransformRelativeOffset().GetX();
6173         offsetY += webPattern->GetHost()->GetTransformRelativeOffset().GetY();
6174         auto context = context_.Upgrade();
6175         CHECK_NULL_VOID(context);
6176         auto windowOffset = context->GetDisplayWindowRectInfo().GetOffset();
6177         offsetX += windowOffset.GetX();
6178         offsetY += windowOffset.GetY();
6179         return;
6180     }
6181     auto renderWeb = renderWeb_.Upgrade();
6182     CHECK_NULL_VOID(renderWeb);
6183     offsetX += renderWeb->GetGlobalOffset().GetX();
6184     offsetY += renderWeb->GetGlobalOffset().GetY();
6185     auto context = context_.Upgrade();
6186     CHECK_NULL_VOID(context);
6187     auto windowOffset = context->GetDisplayWindowRectInfo().GetOffset();
6188     offsetX += windowOffset.GetX();
6189     offsetY += windowOffset.GetY();
6190     WindowMode windowMode = context->GetWindowManager()->GetWindowMode();
6191     if (windowMode == WindowMode::WINDOW_MODE_FLOATING) {
6192         offsetX += CONTAINER_BORDER_WIDTH.ConvertToPx();
6193         offsetY += CONTAINER_TITLE_HEIGHT.ConvertToPx();
6194     }
6195 #endif
6196 }
6197 
UpdateOverScrollMode(const int overscrollModeValue)6198 void WebDelegate::UpdateOverScrollMode(const int overscrollModeValue)
6199 {
6200     auto context = context_.Upgrade();
6201     CHECK_NULL_VOID(context);
6202     context->GetTaskExecutor()->PostTask(
6203         [weak = WeakClaim(this), overscrollModeValue]() {
6204             auto delegate = weak.Upgrade();
6205             CHECK_NULL_VOID(delegate);
6206             CHECK_NULL_VOID(delegate->nweb_);
6207             std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
6208             CHECK_NULL_VOID(setting);
6209             setting->PutOverscrollMode(overscrollModeValue);
6210         },
6211         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateOverScrollMode");
6212 }
6213 
UpdateCopyOptionMode(const int copyOptionModeValue)6214 void WebDelegate::UpdateCopyOptionMode(const int copyOptionModeValue)
6215 {
6216     auto context = context_.Upgrade();
6217     CHECK_NULL_VOID(context);
6218     context->GetTaskExecutor()->PostTask(
6219         [weak = WeakClaim(this), copyOptionModeValue]() {
6220             auto delegate = weak.Upgrade();
6221             CHECK_NULL_VOID(delegate);
6222             CHECK_NULL_VOID(delegate->nweb_);
6223             std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
6224             CHECK_NULL_VOID(setting);
6225             setting->PutCopyOptionMode(
6226                 static_cast<OHOS::NWeb::NWebPreference::CopyOptionMode>(copyOptionModeValue));
6227         },
6228         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateCopyOptionMode");
6229 }
6230 
UpdateNativeVideoPlayerConfig(bool enable,bool shouldOverlay)6231 void WebDelegate::UpdateNativeVideoPlayerConfig(bool enable, bool shouldOverlay)
6232 {
6233     auto context = context_.Upgrade();
6234     CHECK_NULL_VOID(context);
6235     context->GetTaskExecutor()->PostTask(
6236         [weak = WeakClaim(this), enable, shouldOverlay]() {
6237             auto delegate = weak.Upgrade();
6238             CHECK_NULL_VOID(delegate);
6239             CHECK_NULL_VOID(delegate->nweb_);
6240             std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
6241             CHECK_NULL_VOID(setting);
6242             setting->SetNativeVideoPlayerConfig(enable, shouldOverlay);
6243         },
6244         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateNativeVideoPlayerConfig");
6245 }
6246 
UpdateTextAutosizing(bool isTextAutosizing)6247 void WebDelegate::UpdateTextAutosizing(bool isTextAutosizing)
6248 {
6249     auto context = context_.Upgrade();
6250     if (!context) {
6251         return;
6252     }
6253     context->GetTaskExecutor()->PostTask(
6254         [weak = WeakClaim(this), isTextAutosizing]() {
6255             auto delegate = weak.Upgrade();
6256             if (delegate && delegate->nweb_) {
6257                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
6258                 CHECK_NULL_VOID(setting);
6259                 setting->PutTextAutosizingEnabled(isTextAutosizing);
6260             }
6261         },
6262         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateTextAutosizing");
6263 }
6264 
RegisterSurfacePositionChangedCallback()6265 void WebDelegate::RegisterSurfacePositionChangedCallback()
6266 {
6267 #ifdef NG_BUILD
6268     auto pipelineContext = DynamicCast<NG::PipelineContext>(context_.Upgrade());
6269     CHECK_NULL_VOID(pipelineContext);
6270     if (callbackId_ <= 0) {
6271         callbackId_ = pipelineContext->RegisterSurfacePositionChangedCallback(
6272             [weak = WeakClaim(this)](int32_t posX, int32_t posY) {
6273                 auto delegate = weak.Upgrade();
6274                 if (delegate && delegate->nweb_ && !delegate->window_) {
6275                     double offsetX = 0;
6276                     double offsetY = 0;
6277                     delegate->UpdateScreenOffSet(offsetX, offsetY);
6278                     delegate->nweb_->SetScreenOffSet(offsetX, offsetY);
6279                 }
6280             });
6281     }
6282     return;
6283 #else
6284     if (Container::IsCurrentUseNewPipeline()) {
6285         auto pipelineContext = DynamicCast<NG::PipelineContext>(context_.Upgrade());
6286         CHECK_NULL_VOID(pipelineContext);
6287         if (callbackId_ <= 0) {
6288             callbackId_ = pipelineContext->RegisterSurfacePositionChangedCallback(
6289                 [weak = WeakClaim(this)](int32_t posX, int32_t posY) {
6290                     auto delegate = weak.Upgrade();
6291                     if (delegate && delegate->nweb_ && !delegate->window_) {
6292                         double offsetX = 0;
6293                         double offsetY = 0;
6294                         delegate->UpdateScreenOffSet(offsetX, offsetY);
6295                         delegate->nweb_->SetScreenOffSet(offsetX, offsetY);
6296                     }
6297                 });
6298         }
6299         return;
6300     }
6301     auto pipelineContext = DynamicCast<PipelineContext>(context_.Upgrade());
6302     CHECK_NULL_VOID(pipelineContext);
6303     if (callbackId_ <= 0) {
6304         callbackId_ = pipelineContext->RegisterSurfacePositionChangedCallback(
6305             [weak = WeakClaim(this)](int32_t posX, int32_t posY) {
6306                 auto delegate = weak.Upgrade();
6307                 if (delegate && delegate->nweb_ && !delegate->window_) {
6308                     double offsetX = 0;
6309                     double offsetY = 0;
6310                     delegate->UpdateScreenOffSet(offsetX, offsetY);
6311                     delegate->nweb_->SetScreenOffSet(offsetX, offsetY);
6312                 }
6313             });
6314     }
6315 #endif
6316 }
6317 
UnregisterSurfacePositionChangedCallback()6318 void WebDelegate::UnregisterSurfacePositionChangedCallback()
6319 {
6320     if (callbackId_ <= 0) {
6321         return;
6322     }
6323 #ifdef NG_BUILD
6324     auto pipelineContext = DynamicCast<NG::PipelineContext>(context_.Upgrade());
6325     CHECK_NULL_VOID(pipelineContext);
6326     pipelineContext->UnregisterSurfacePositionChangedCallback(callbackId_);
6327     callbackId_ = 0;
6328     return;
6329 #else
6330     if (Container::IsCurrentUseNewPipeline()) {
6331         auto pipelineContext = DynamicCast<NG::PipelineContext>(context_.Upgrade());
6332         CHECK_NULL_VOID(pipelineContext);
6333         pipelineContext->UnregisterSurfacePositionChangedCallback(callbackId_);
6334         callbackId_ = 0;
6335         return;
6336     }
6337     auto pipelineContext = DynamicCast<PipelineContext>(context_.Upgrade());
6338     CHECK_NULL_VOID(pipelineContext);
6339     pipelineContext->UnregisterSurfacePositionChangedCallback(callbackId_);
6340     callbackId_ = 0;
6341 #endif
6342 }
6343 
OnCompleteSwapWithNewSize()6344 void WebDelegate::OnCompleteSwapWithNewSize()
6345 {
6346     auto webPattern = webPattern_.Upgrade();
6347     CHECK_NULL_VOID(webPattern);
6348     webPattern->OnCompleteSwapWithNewSize();
6349 }
6350 
OnResizeNotWork()6351 void WebDelegate::OnResizeNotWork()
6352 {
6353     auto webPattern = webPattern_.Upgrade();
6354     CHECK_NULL_VOID(webPattern);
6355     webPattern->OnResizeNotWork();
6356 }
6357 
OnDateTimeChooserPopup(std::shared_ptr<OHOS::NWeb::NWebDateTimeChooser> chooser,const std::vector<std::shared_ptr<OHOS::NWeb::NWebDateTimeSuggestion>> & suggestions,std::shared_ptr<OHOS::NWeb::NWebDateTimeChooserCallback> callback)6358 void WebDelegate::OnDateTimeChooserPopup(std::shared_ptr<OHOS::NWeb::NWebDateTimeChooser> chooser,
6359     const std::vector<std::shared_ptr<OHOS::NWeb::NWebDateTimeSuggestion>>& suggestions,
6360     std::shared_ptr<OHOS::NWeb::NWebDateTimeChooserCallback> callback)
6361 {
6362     auto webPattern = webPattern_.Upgrade();
6363     CHECK_NULL_VOID(webPattern);
6364     webPattern->OnDateTimeChooserPopup(chooser, suggestions, callback);
6365 }
6366 
OnDateTimeChooserClose()6367 void WebDelegate::OnDateTimeChooserClose()
6368 {
6369     auto webPattern = webPattern_.Upgrade();
6370     CHECK_NULL_VOID(webPattern);
6371     webPattern->OnDateTimeChooserClose();
6372 }
6373 
OnOverScroll(float xOffset,float yOffset)6374 void WebDelegate::OnOverScroll(float xOffset, float yOffset)
6375 {
6376     auto context = context_.Upgrade();
6377     CHECK_NULL_VOID(context);
6378     context->GetTaskExecutor()->PostTask(
6379         [weak = WeakClaim(this), xOffset, yOffset]() {
6380             auto delegate = weak.Upgrade();
6381             CHECK_NULL_VOID(delegate);
6382             auto onOverScrollV2 = delegate->onOverScrollV2_;
6383             if (onOverScrollV2) {
6384                 onOverScrollV2(std::make_shared<WebOnOverScrollEvent>(xOffset, yOffset));
6385             }
6386         },
6387         TaskExecutor::TaskType::JS, "ArkUIWebOverScroll");
6388 }
6389 
SetTouchEventInfo(std::shared_ptr<OHOS::NWeb::NWebNativeEmbedTouchEvent> touchEvent,TouchEventInfo & touchEventInfo)6390 void WebDelegate::SetTouchEventInfo(std::shared_ptr<OHOS::NWeb::NWebNativeEmbedTouchEvent> touchEvent,
6391                                     TouchEventInfo& touchEventInfo)
6392 {
6393     auto webPattern = webPattern_.Upgrade();
6394     CHECK_NULL_VOID(webPattern);
6395     if (touchEvent) {
6396         TouchEvent event;
6397         event.SetId(touchEvent->GetId())
6398             .SetX(touchEvent->GetX())
6399             .SetY(touchEvent->GetY())
6400             .SetScreenX(touchEvent->GetScreenX())
6401             .SetScreenY(touchEvent->GetScreenY())
6402             .SetType(static_cast<OHOS::Ace::TouchType>(touchEvent->GetType()));
6403         webPattern->SetTouchEventInfo(event, touchEventInfo, touchEvent->GetEmbedId());
6404     } else {
6405         TouchEvent event;
6406         event.SetId(0);
6407         webPattern->SetTouchEventInfo(event, touchEventInfo, DEFAULT_NATIVE_EMBED_ID);
6408     }
6409 }
6410 
OnNativeEmbedAllDestory()6411 void WebDelegate::OnNativeEmbedAllDestory()
6412 {
6413     if (!isEmbedModeEnabled_) {
6414         return;
6415     }
6416     auto iter = embedDataInfo_.begin();
6417     for (; iter != embedDataInfo_.end(); iter++) {
6418         EmbedInfo info;
6419         std::shared_ptr<OHOS::NWeb::NWebNativeEmbedDataInfo> dataInfo  = iter->second;
6420         if (dataInfo == nullptr) {
6421             continue;
6422         }
6423         std::string embedId = dataInfo->GetEmbedId();
6424         TAG_LOGI(AceLogTag::ACE_WEB, "OnNativeEmbedAllDestory embdedid=%{public}s", embedId.c_str());
6425         std::string surfaceId = dataInfo->GetSurfaceId();
6426         auto embedInfo = dataInfo->GetNativeEmbedInfo();
6427         if (embedInfo) {
6428             info = {embedInfo->GetId(), embedInfo->GetType(), embedInfo->GetSrc(),
6429                 embedInfo->GetUrl(), embedInfo->GetTag(), embedInfo->GetWidth(),
6430                 embedInfo->GetHeight(), embedInfo->GetX(), embedInfo->GetY(),
6431                 embedInfo->GetParams()};
6432         }
6433         if (OnNativeEmbedAllDestoryV2_) {
6434             OHOS::Ace::NativeEmbedStatus status = OHOS::Ace::NativeEmbedStatus::DESTROY;
6435             OnNativeEmbedAllDestoryV2_(
6436                 std::make_shared<NativeEmbedDataInfo>(status, surfaceId, embedId, info));
6437         }
6438     }
6439     embedDataInfo_.clear();
6440 }
6441 
OnNativeEmbedLifecycleChange(std::shared_ptr<OHOS::NWeb::NWebNativeEmbedDataInfo> dataInfo)6442 void WebDelegate::OnNativeEmbedLifecycleChange(std::shared_ptr<OHOS::NWeb::NWebNativeEmbedDataInfo> dataInfo)
6443 {
6444     if (!isEmbedModeEnabled_) {
6445         return;
6446     }
6447 
6448     EmbedInfo info;
6449     std::string embedId;
6450     std::string surfaceId;
6451     OHOS::Ace::NativeEmbedStatus status = OHOS::Ace::NativeEmbedStatus::CREATE;
6452     if (dataInfo) {
6453         embedId = dataInfo->GetEmbedId();
6454         surfaceId = dataInfo->GetSurfaceId();
6455         status = static_cast<OHOS::Ace::NativeEmbedStatus>(dataInfo->GetStatus());
6456 
6457         auto embedInfo = dataInfo->GetNativeEmbedInfo();
6458         if (embedInfo) {
6459             info = {embedInfo->GetId(), embedInfo->GetType(), embedInfo->GetSrc(),
6460                 embedInfo->GetUrl(), embedInfo->GetTag(), embedInfo->GetWidth(),
6461                 embedInfo->GetHeight(), embedInfo->GetX(), embedInfo->GetY(),
6462                 embedInfo->GetParams()};
6463         }
6464 
6465         if (status == OHOS::Ace::NativeEmbedStatus::CREATE || status == OHOS::Ace::NativeEmbedStatus::UPDATE) {
6466             embedDataInfo_.insert_or_assign(embedId, dataInfo);
6467         } else if (status == OHOS::Ace::NativeEmbedStatus::DESTROY) {
6468             auto iter = embedDataInfo_.find(embedId);
6469             if (iter != embedDataInfo_.end()) {
6470                 embedDataInfo_.erase(iter);
6471             }
6472         }
6473     }
6474 
6475     auto context = context_.Upgrade();
6476     CHECK_NULL_VOID(context);
6477     context->GetTaskExecutor()->PostTask(
6478         [weak = WeakClaim(this), status, surfaceId, embedId, info]() {
6479             auto delegate = weak.Upgrade();
6480             CHECK_NULL_VOID(delegate);
6481             auto OnNativeEmbedLifecycleChangeV2_ = delegate->OnNativeEmbedLifecycleChangeV2_;
6482             if (OnNativeEmbedLifecycleChangeV2_) {
6483                 OnNativeEmbedLifecycleChangeV2_(
6484                     std::make_shared<NativeEmbedDataInfo>(status, surfaceId, embedId, info));
6485             }
6486         },
6487         TaskExecutor::TaskType::JS, "ArkUIWebNativeEmbedLifecycleChange");
6488 }
6489 
OnNativeEmbedVisibilityChange(const std::string & embed_id,bool visibility)6490 void WebDelegate::OnNativeEmbedVisibilityChange(const std::string& embed_id, bool visibility)
6491 {
6492     if (!isEmbedModeEnabled_) {
6493         return;
6494     }
6495 
6496     auto context = context_.Upgrade();
6497     CHECK_NULL_VOID(context);
6498     context->GetTaskExecutor()->PostTask(
6499         [weak = WeakClaim(this), embed_id, visibility]() {
6500             auto delegate = weak.Upgrade();
6501             CHECK_NULL_VOID(delegate);
6502             auto OnNativeEmbedVisibilityChangeV2_ = delegate->OnNativeEmbedVisibilityChangeV2_;
6503             if (OnNativeEmbedVisibilityChangeV2_) {
6504                 OnNativeEmbedVisibilityChangeV2_(
6505                     std::make_shared<NativeEmbedVisibilityInfo>(visibility, embed_id));
6506             }
6507         },
6508         TaskExecutor::TaskType::JS, "ArkUIWebNativeEmbedVisibilityChange");
6509 }
6510 
OnNativeEmbedGestureEvent(std::shared_ptr<OHOS::NWeb::NWebNativeEmbedTouchEvent> event)6511 void WebDelegate::OnNativeEmbedGestureEvent(std::shared_ptr<OHOS::NWeb::NWebNativeEmbedTouchEvent> event)
6512 {
6513     if (event->GetId() == NO_NATIVE_FINGER_TYPE) {
6514         auto webPattern = webPattern_.Upgrade();
6515         CHECK_NULL_VOID(webPattern);
6516         webPattern->RequestFocus();
6517         return;
6518     }
6519     auto context = context_.Upgrade();
6520     TouchEventInfo touchEventInfo("touchEvent");
6521     auto embedId = event ? event->GetEmbedId() : "";
6522     SetTouchEventInfo(event, touchEventInfo);
6523     CHECK_NULL_VOID(context);
6524     TAG_LOGD(AceLogTag::ACE_WEB, "hit Emebed gusture event notify");
6525     auto param = AceType::MakeRefPtr<GestureEventResultOhos>(event->GetResult());
6526     auto type = event->GetType();
6527     context->GetTaskExecutor()->PostTask(
6528         [weak = WeakClaim(this), embedId, touchEventInfo, param, type]() {
6529             auto delegate = weak.Upgrade();
6530             CHECK_NULL_VOID(delegate);
6531             auto OnNativeEmbedGestureEventV2_ = delegate->OnNativeEmbedGestureEventV2_;
6532             if (OnNativeEmbedGestureEventV2_) {
6533                 OnNativeEmbedGestureEventV2_(
6534                     std::make_shared<NativeEmbeadTouchInfo>(embedId, touchEventInfo, param));
6535                 if (!param->HasSendTask()) {
6536                     param->SetGestureEventResult(true);
6537                 }
6538                 if (!param->GetEventResult() && type == OHOS::NWeb::TouchType::DOWN) {
6539                     auto webPattern = delegate->webPattern_.Upgrade();
6540                     CHECK_NULL_VOID(webPattern);
6541                     webPattern->RequestFocus();
6542                 }
6543             }
6544         },
6545         TaskExecutor::TaskType::JS, "ArkUIWebNativeEmbedGestureEvent");
6546 }
6547 
SetToken()6548 void WebDelegate::SetToken()
6549 {
6550     auto container = AceType::DynamicCast<Platform::AceContainer>(Container::Current());
6551     CHECK_NULL_VOID(container);
6552     int32_t instanceId = container->GetInstanceId();
6553     auto window = Platform::AceContainer::GetUIWindow(instanceId);
6554     CHECK_NULL_VOID(window);
6555     auto uiContent = window->GetUIContent();
6556     CHECK_NULL_VOID(nweb_);
6557     CHECK_NULL_VOID(uiContent);
6558     nweb_->SetToken(static_cast<void*>(uiContent));
6559     TAG_LOGD(AceLogTag::ACE_WEB, "setToken success");
6560 }
6561 
OnOverScrollFlingVelocity(float xVelocity,float yVelocity,bool isFling)6562 void WebDelegate::OnOverScrollFlingVelocity(float xVelocity, float yVelocity, bool isFling)
6563 {
6564     auto webPattern = webPattern_.Upgrade();
6565     CHECK_NULL_VOID(webPattern);
6566     webPattern->OnOverScrollFlingVelocity(xVelocity, yVelocity, isFling);
6567 }
6568 
OnScrollState(bool scrollState)6569 void WebDelegate::OnScrollState(bool scrollState)
6570 {
6571     auto webPattern = webPattern_.Upgrade();
6572     CHECK_NULL_VOID(webPattern);
6573     webPattern->OnScrollState(scrollState);
6574 }
6575 
OnRootLayerChanged(int width,int height)6576 void WebDelegate::OnRootLayerChanged(int width, int height)
6577 {
6578     auto webPattern = webPattern_.Upgrade();
6579     CHECK_NULL_VOID(webPattern);
6580     webPattern->OnRootLayerChanged(width, height);
6581 }
6582 
FilterScrollEvent(const float x,const float y,const float xVelocity,const float yVelocity)6583 bool WebDelegate::FilterScrollEvent(const float x, const float y, const float xVelocity, const float yVelocity)
6584 {
6585     auto webPattern = webPattern_.Upgrade();
6586     CHECK_NULL_RETURN(webPattern, false);
6587     return webPattern->FilterScrollEvent(x, y, xVelocity, yVelocity);
6588 }
6589 
ScrollBy(float deltaX,float deltaY)6590 void WebDelegate::ScrollBy(float deltaX, float deltaY)
6591 {
6592     CHECK_NULL_VOID(nweb_);
6593     nweb_->ScrollBy(deltaX, deltaY);
6594 }
6595 
ReleaseResizeHold()6596 void WebDelegate::ReleaseResizeHold()
6597 {
6598     auto webPattern = webPattern_.Upgrade();
6599     CHECK_NULL_VOID(webPattern);
6600     webPattern->ReleaseResizeHold();
6601 }
6602 
ScrollByRefScreen(float deltaX,float deltaY,float vx,float vy)6603 void WebDelegate::ScrollByRefScreen(float deltaX, float deltaY, float vx, float vy)
6604 {
6605     CHECK_NULL_VOID(nweb_);
6606     nweb_->ScrollByRefScreen(deltaX, deltaY, vx, vy);
6607 }
6608 
SetVirtualKeyBoardArg(int32_t width,int32_t height,double keyboard)6609 void WebDelegate::SetVirtualKeyBoardArg(int32_t width, int32_t height, double keyboard)
6610 {
6611     if (nweb_) {
6612         nweb_->SetVirtualKeyBoardArg(width, height, keyboard);
6613     }
6614 }
6615 
ShouldVirtualKeyboardOverlay()6616 bool WebDelegate::ShouldVirtualKeyboardOverlay()
6617 {
6618     if (nweb_) {
6619         return nweb_->ShouldVirtualKeyboardOverlay();
6620     }
6621     return false;
6622 }
6623 
SetJavaScriptItems(const ScriptItems & scriptItems,const ScriptItemType & type)6624 void WebDelegate::SetJavaScriptItems(const ScriptItems& scriptItems, const ScriptItemType& type)
6625 {
6626     if (type == ScriptItemType::DOCUMENT_START) {
6627         onDocumentStartScriptItems_ = std::make_optional<ScriptItems>(scriptItems);
6628     } else {
6629         onDocumentEndScriptItems_ = std::make_optional<ScriptItems>(scriptItems);
6630     }
6631 }
6632 
JavaScriptOnDocumentStart()6633 void WebDelegate::JavaScriptOnDocumentStart()
6634 {
6635     CHECK_NULL_VOID(nweb_);
6636     if (onDocumentStartScriptItems_.has_value()) {
6637         nweb_->JavaScriptOnDocumentStart(onDocumentStartScriptItems_.value());
6638         onDocumentStartScriptItems_ = std::nullopt;
6639     }
6640 }
6641 
JavaScriptOnDocumentEnd()6642 void WebDelegate::JavaScriptOnDocumentEnd()
6643 {
6644     CHECK_NULL_VOID(nweb_);
6645     if (onDocumentEndScriptItems_.has_value()) {
6646         nweb_->JavaScriptOnDocumentEnd(onDocumentEndScriptItems_.value());
6647         onDocumentEndScriptItems_ = std::nullopt;
6648     }
6649 }
6650 
ExecuteAction(int64_t accessibilityId,AceAction action,const std::map<std::string,std::string> & actionArguments)6651 bool WebDelegate::ExecuteAction(int64_t accessibilityId, AceAction action,
6652     const std::map<std::string, std::string>& actionArguments)
6653 {
6654     if (!accessibilityState_) {
6655         return false;
6656     }
6657     auto context = context_.Upgrade();
6658     CHECK_NULL_RETURN(context, false);
6659     uint32_t nwebAction = static_cast<uint32_t>(action);
6660     context->GetTaskExecutor()->PostTask(
6661         [weak = WeakClaim(this), accessibilityId, nwebAction, actionArguments]() {
6662             auto delegate = weak.Upgrade();
6663             CHECK_NULL_VOID(delegate);
6664             CHECK_NULL_VOID(delegate->nweb_);
6665             delegate->nweb_->PerformAction(accessibilityId, nwebAction, actionArguments);
6666         },
6667         TaskExecutor::TaskType::PLATFORM, "ArkUIWebExecuteAction");
6668     return true;
6669 }
6670 
SetAccessibilityState(bool state)6671 void WebDelegate::SetAccessibilityState(bool state)
6672 {
6673     if (state == accessibilityState_) {
6674         return;
6675     }
6676     accessibilityState_ = state;
6677     if (state) {
6678         auto context = context_.Upgrade();
6679         CHECK_NULL_VOID(context);
6680         context->GetTaskExecutor()->PostTask(
6681             [weak = WeakClaim(this), state]() {
6682                 auto delegate = weak.Upgrade();
6683                 CHECK_NULL_VOID(delegate);
6684                 CHECK_NULL_VOID(delegate->nweb_);
6685                 delegate->nweb_->SetAccessibilityState(state);
6686                 auto accessibilityEventListenerImpl =
6687                     std::make_shared<AccessibilityEventListenerImpl>();
6688                 CHECK_NULL_VOID(accessibilityEventListenerImpl);
6689                 accessibilityEventListenerImpl->SetWebDelegate(weak);
6690                 delegate->nweb_->PutAccessibilityEventCallback(accessibilityEventListenerImpl);
6691             },
6692             TaskExecutor::TaskType::PLATFORM, "ArkUIWebSetAccessibilityState");
6693     } else {
6694         CHECK_NULL_VOID(nweb_);
6695         nweb_->SetAccessibilityState(state);
6696     }
6697 }
6698 
GetFocusedAccessibilityNodeInfo(int64_t accessibilityId,bool isAccessibilityFocus)6699 std::shared_ptr<OHOS::NWeb::NWebAccessibilityNodeInfo> WebDelegate::GetFocusedAccessibilityNodeInfo(
6700     int64_t accessibilityId, bool isAccessibilityFocus)
6701 {
6702     CHECK_NULL_RETURN(nweb_, nullptr);
6703     if (!accessibilityState_) {
6704         return nullptr;
6705     }
6706     return nweb_->GetFocusedAccessibilityNodeInfo(accessibilityId, isAccessibilityFocus);
6707 }
6708 
GetAccessibilityNodeInfoById(int64_t accessibilityId)6709 std::shared_ptr<OHOS::NWeb::NWebAccessibilityNodeInfo> WebDelegate::GetAccessibilityNodeInfoById(
6710     int64_t accessibilityId)
6711 {
6712     CHECK_NULL_RETURN(nweb_, nullptr);
6713     if (!accessibilityState_) {
6714         return nullptr;
6715     }
6716     return nweb_->GetAccessibilityNodeInfoById(accessibilityId);
6717 }
6718 
GetAccessibilityNodeInfoByFocusMove(int64_t accessibilityId,int32_t direction)6719 std::shared_ptr<OHOS::NWeb::NWebAccessibilityNodeInfo> WebDelegate::GetAccessibilityNodeInfoByFocusMove(
6720     int64_t accessibilityId, int32_t direction)
6721 {
6722     CHECK_NULL_RETURN(nweb_, nullptr);
6723     if (!accessibilityState_) {
6724         return nullptr;
6725     }
6726     return nweb_->GetAccessibilityNodeInfoByFocusMove(accessibilityId, direction);
6727 }
6728 
GetCopyOptionMode() const6729 OHOS::NWeb::NWebPreference::CopyOptionMode WebDelegate::GetCopyOptionMode() const
6730 {
6731     CHECK_NULL_RETURN(nweb_, OHOS::NWeb::NWebPreference::CopyOptionMode::CROSS_DEVICE);
6732     std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_->GetPreference();
6733     CHECK_NULL_RETURN(setting, OHOS::NWeb::NWebPreference::CopyOptionMode::CROSS_DEVICE);
6734     auto copyOption = setting->GetCopyOptionMode();
6735     return copyOption;
6736 }
6737 
OnOpenAppLink(const std::string & url,std::shared_ptr<OHOS::NWeb::NWebAppLinkCallback> callback)6738 bool WebDelegate::OnOpenAppLink(
6739     const std::string& url, std::shared_ptr<OHOS::NWeb::NWebAppLinkCallback> callback)
6740 {
6741     if (!callback) {
6742         TAG_LOGE(AceLogTag::ACE_WEB, "open app link callback is nullptr");
6743         return false;
6744     }
6745     auto context = context_.Upgrade();
6746     CHECK_NULL_RETURN(context, false);
6747     bool result = false;
6748     auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
6749     jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), url, callback, &result]() {
6750         auto delegate = weak.Upgrade();
6751         CHECK_NULL_VOID(delegate);
6752         auto webPattern = delegate->webPattern_.Upgrade();
6753         CHECK_NULL_VOID(webPattern);
6754         auto openAppLinkCallback = webPattern->GetOnOpenAppLinkCallback();
6755         CHECK_NULL_VOID(openAppLinkCallback);
6756         openAppLinkCallback(std::make_shared<WebAppLinkEvent>(url,
6757             AceType::MakeRefPtr<WebAppLinkCallbackOhos>(callback)));
6758         result = true;
6759         }, "ArkUIWebOnOpenAppLink");
6760     return result;
6761 }
6762 
GetCanonicalEncodingName(const std::string & alias_name) const6763 std::string WebDelegate::GetCanonicalEncodingName(const std::string& alias_name) const
6764 {
6765     const char* standards[3] = { "HTML", "MIME", "IANA" };
6766     for (auto* standard : standards) {
6767         UErrorCode errorCode = U_ZERO_ERROR;
6768         const char* result =
6769             ucnv_getStandardName(alias_name.c_str(), standard, &errorCode);
6770         if (!U_SUCCESS(errorCode) || !result)
6771             continue;
6772         std::string canonicalName(result);
6773         for (const auto& encodingName : CANONICALENCODINGNAMES) {
6774             if (encodingName == canonicalName)
6775                 return canonicalName;
6776         }
6777     }
6778     return DEFAULT_CANONICAL_ENCODING_NAME;
6779 }
6780 
UpdateDefaultTextEncodingFormat(const std::string & textEncodingFormat)6781 void WebDelegate::UpdateDefaultTextEncodingFormat(const std::string& textEncodingFormat)
6782 {
6783     auto context = context_.Upgrade();
6784     if (!context || textEncodingFormat.empty()) {
6785         return;
6786     }
6787     auto canonicalEncodingName = GetCanonicalEncodingName(textEncodingFormat);
6788     context->GetTaskExecutor()->PostTask(
6789         [weak = WeakClaim(this), canonicalEncodingName]() {
6790             auto delegate = weak.Upgrade();
6791             if (delegate && delegate->nweb_) {
6792                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
6793                 if (setting) {
6794                     setting->PutDefaultTextEncodingFormat(canonicalEncodingName);
6795                 }
6796             }
6797         },
6798         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateDefaultTextEncodingFormat");
6799 }
6800 
OnIntelligentTrackingPreventionResult(const std::string & websiteHost,const std::string & trackerHost)6801 void WebDelegate::OnIntelligentTrackingPreventionResult(
6802     const std::string& websiteHost, const std::string& trackerHost)
6803 {
6804     if (onIntelligentTrackingPreventionResultV2_) {
6805         onIntelligentTrackingPreventionResultV2_(
6806             std::make_shared<IntelligentTrackingPreventionResultEvent>(
6807                 websiteHost, trackerHost));
6808     }
6809 }
6810 
OnHandleOverrideLoading(std::shared_ptr<OHOS::NWeb::NWebUrlResourceRequest> request)6811 bool WebDelegate::OnHandleOverrideLoading(std::shared_ptr<OHOS::NWeb::NWebUrlResourceRequest> request)
6812 {
6813     if (!request) {
6814         return false;
6815     }
6816     auto context = context_.Upgrade();
6817     CHECK_NULL_RETURN(context, false);
6818     bool result = false;
6819     auto jsTaskExecutor = SingleTaskExecutor::Make(context->GetTaskExecutor(), TaskExecutor::TaskType::JS);
6820     jsTaskExecutor.PostSyncTask([weak = WeakClaim(this), request, &result]() {
6821         auto delegate = weak.Upgrade();
6822         CHECK_NULL_VOID(delegate);
6823         auto webRequest = AceType::MakeRefPtr<WebRequest>(request->RequestHeaders(), request->Method(), request->Url(),
6824             request->FromGesture(), request->IsAboutMainFrame(), request->IsRequestRedirect());
6825         auto param = std::make_shared<LoadOverrideEvent>(webRequest);
6826         if (Container::IsCurrentUseNewPipeline()) {
6827             auto webPattern = delegate->webPattern_.Upgrade();
6828             CHECK_NULL_VOID(webPattern);
6829             auto webEventHub = webPattern->GetWebEventHub();
6830             CHECK_NULL_VOID(webEventHub);
6831             auto propOnOverrideUrlLoadingEvent = webEventHub->GetOnOverrideUrlLoadingEvent();
6832             CHECK_NULL_VOID(propOnOverrideUrlLoadingEvent);
6833             result = propOnOverrideUrlLoadingEvent(param);
6834         }
6835         auto webCom = delegate->webComponent_.Upgrade();
6836         CHECK_NULL_VOID(webCom);
6837         result = webCom->OnOverrideUrlLoading(param.get());
6838         }, "ArkUIWebHandleOverrideLoading");
6839     return result;
6840 }
6841 
OnDetachContext()6842 void WebDelegate::OnDetachContext()
6843 {
6844     UnRegisterScreenLockFunction();
6845     UnregisterSurfacePositionChangedCallback();
6846     auto context = context_.Upgrade();
6847     CHECK_NULL_VOID(context);
6848     auto pipelineContext = DynamicCast<NG::PipelineContext>(context);
6849     CHECK_NULL_VOID(pipelineContext);
6850     pipelineContext->AddAfterRenderTask(
6851         [weak = WeakClaim(this)]() {
6852             auto delegate = weak.Upgrade();
6853             CHECK_NULL_VOID(delegate);
6854             delegate->UnregisterAvoidAreaChangeListener();
6855         });
6856 }
6857 
OnAttachContext(const RefPtr<NG::PipelineContext> & context)6858 void WebDelegate::OnAttachContext(const RefPtr<NG::PipelineContext> &context)
6859 {
6860     instanceId_ = context->GetInstanceId();
6861     context_ = context;
6862     RegisterSurfacePositionChangedCallback();
6863     if (nweb_) {
6864         auto screenLockCallback = std::make_shared<NWebScreenLockCallbackImpl>(context);
6865         nweb_->RegisterScreenLockFunction(instanceId_, screenLockCallback);
6866         auto windowId = context->GetFocusWindowId();
6867         nweb_->SetWindowId(windowId);
6868     }
6869     auto pipelineContext = DynamicCast<NG::PipelineContext>(context);
6870     CHECK_NULL_VOID(pipelineContext);
6871     pipelineContext->AddAfterRenderTask(
6872         [weak = WeakClaim(this)]() {
6873             auto delegate = weak.Upgrade();
6874             CHECK_NULL_VOID(delegate);
6875             delegate->RegisterAvoidAreaChangeListener();
6876         });
6877 }
6878 
UpdateMetaViewport(bool isMetaViewportEnabled)6879 void WebDelegate::UpdateMetaViewport(bool isMetaViewportEnabled)
6880 {
6881     auto context = context_.Upgrade();
6882     CHECK_NULL_VOID(context);
6883     context->GetTaskExecutor()->PostTask(
6884         [weak = WeakClaim(this), isMetaViewportEnabled]() {
6885             auto delegate = weak.Upgrade();
6886             if (delegate && delegate->nweb_) {
6887                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
6888                 if (setting) {
6889                     setting->SetViewportEnable(isMetaViewportEnabled);
6890                 }
6891             }
6892         },
6893         TaskExecutor::TaskType::PLATFORM, "ArkUIWebUpdateMetaViewport");
6894 }
6895 
GetWordSelection(const std::string & text,int8_t offset)6896 std::vector<int8_t> WebDelegate::GetWordSelection(const std::string& text, int8_t offset)
6897 {
6898     auto webPattern = webPattern_.Upgrade();
6899     std::vector<int8_t> vec = { -1, -1 };
6900     CHECK_NULL_RETURN(webPattern, vec);
6901     return webPattern->GetWordSelection(text, offset);
6902 }
6903 
NotifyForNextTouchEvent()6904 void WebDelegate::NotifyForNextTouchEvent()
6905 {
6906     ACE_DCHECK(nweb_ != nullptr);
6907     if (nweb_) {
6908         nweb_->NotifyForNextTouchEvent();
6909     }
6910 }
6911 
OnRenderProcessNotResponding(const std::string & jsStack,int pid,OHOS::NWeb::RenderProcessNotRespondingReason reason)6912 void WebDelegate::OnRenderProcessNotResponding(
6913     const std::string& jsStack, int pid, OHOS::NWeb::RenderProcessNotRespondingReason reason)
6914 {
6915     auto context = context_.Upgrade();
6916     CHECK_NULL_VOID(context);
6917     context->GetTaskExecutor()->PostTask(
6918         [weak = WeakClaim(this), jsStack, pid, reason]() {
6919             auto delegate = weak.Upgrade();
6920             CHECK_NULL_VOID(delegate);
6921             auto onRenderProcessNotRespondingV2 = delegate->onRenderProcessNotRespondingV2_;
6922             if (onRenderProcessNotRespondingV2) {
6923                 onRenderProcessNotRespondingV2(std::make_shared<RenderProcessNotRespondingEvent>(
6924                     jsStack, pid, static_cast<int>(reason)));
6925             }
6926         },
6927         TaskExecutor::TaskType::JS, "ArkUIWebHandleRenderProcessNotResponding");
6928 }
6929 
OnRenderProcessResponding()6930 void WebDelegate::OnRenderProcessResponding()
6931 {
6932     auto context = context_.Upgrade();
6933     CHECK_NULL_VOID(context);
6934     context->GetTaskExecutor()->PostTask(
6935         [weak = WeakClaim(this)]() {
6936             auto delegate = weak.Upgrade();
6937             CHECK_NULL_VOID(delegate);
6938             auto onRenderProcessRespondingV2 = delegate->onRenderProcessRespondingV2_;
6939             if (onRenderProcessRespondingV2) {
6940                 onRenderProcessRespondingV2(std::make_shared<RenderProcessRespondingEvent>());
6941             }
6942         },
6943         TaskExecutor::TaskType::JS, "ArkUIWebHandleRenderProcessResponding");
6944 }
6945 
ScaleGestureChange(double scale,double centerX,double centerY)6946 void WebDelegate::ScaleGestureChange(double scale, double centerX, double centerY)
6947 {
6948 #ifdef OHOS_STANDARD_SYSTEM
6949     ACE_DCHECK(nweb_ != nullptr);
6950     if (nweb_) {
6951         nweb_->ScaleGestureChange(scale, centerX, centerY);
6952     }
6953 #endif
6954 }
6955 
GetSelectInfo() const6956 std::string WebDelegate::GetSelectInfo() const
6957 {
6958     CHECK_NULL_RETURN(nweb_, std::string());
6959     return nweb_->GetSelectInfo();
6960 }
6961 
GetPosition(const std::string & embedId)6962 Offset WebDelegate::GetPosition(const std::string& embedId)
6963 {
6964     auto iter = embedDataInfo_.find(embedId);
6965     if (iter != embedDataInfo_.end()) {
6966         std::shared_ptr<OHOS::NWeb::NWebNativeEmbedDataInfo> dataInfo  = iter->second;
6967         if (dataInfo) {
6968             auto embedInfo = dataInfo->GetNativeEmbedInfo();
6969             return Offset(embedInfo->GetX(), embedInfo->GetY());
6970         }
6971     }
6972     return Offset();
6973 }
6974 
OnShowAutofillPopup(const float offsetX,const float offsetY,const std::vector<std::string> & menu_items)6975 void WebDelegate::OnShowAutofillPopup(
6976     const float offsetX, const float offsetY, const std::vector<std::string>& menu_items)
6977 {
6978     auto webPattern = webPattern_.Upgrade();
6979     CHECK_NULL_VOID(webPattern);
6980     webPattern->OnShowAutofillPopup(offsetX, offsetY, menu_items);
6981 }
6982 
SuggestionSelected(int32_t index)6983 void WebDelegate::SuggestionSelected(int32_t index)
6984 {
6985     CHECK_NULL_VOID(nweb_);
6986     nweb_->SuggestionSelected(index);
6987 }
6988 
OnHideAutofillPopup()6989 void WebDelegate::OnHideAutofillPopup()
6990 {
6991     auto webPattern = webPattern_.Upgrade();
6992     CHECK_NULL_VOID(webPattern);
6993     webPattern->OnHideAutofillPopup();
6994 }
6995 
OnAreaChange(const OHOS::Ace::Rect & area)6996 void WebDelegate::OnAreaChange(const OHOS::Ace::Rect& area)
6997 {
6998     if (currentArea_ == area) {
6999         return;
7000     }
7001     currentArea_ = area;
7002     if (nweb_) {
7003         double offsetX = 0;
7004         double offsetY = 0;
7005         UpdateScreenOffSet(offsetX, offsetY);
7006         nweb_->SetScreenOffSet(offsetX, offsetY);
7007     }
7008     OnSafeInsetsChange();
7009 }
7010 
OnViewportFitChange(OHOS::NWeb::ViewportFit viewportFit)7011 void WebDelegate::OnViewportFitChange(OHOS::NWeb::ViewportFit viewportFit)
7012 {
7013     auto context = context_.Upgrade();
7014     CHECK_NULL_VOID(context);
7015     context->GetTaskExecutor()->PostTask(
7016         [weak = WeakClaim(this), viewportFit]() {
7017             auto delegate = weak.Upgrade();
7018             CHECK_NULL_VOID(delegate);
7019             auto onViewportFitChangedV2 = delegate->onViewportFitChangedV2_;
7020             if (onViewportFitChangedV2) {
7021                 onViewportFitChangedV2(std::make_shared<ViewportFitChangedEvent>(static_cast<int32_t>(viewportFit)));
7022             }
7023         },
7024         TaskExecutor::TaskType::JS, "ArkUIWebViewportFitChanged");
7025 }
7026 
OnAvoidAreaChanged(const OHOS::Rosen::AvoidArea avoidArea,OHOS::Rosen::AvoidAreaType type)7027 void WebDelegate::OnAvoidAreaChanged(const OHOS::Rosen::AvoidArea avoidArea, OHOS::Rosen::AvoidAreaType type)
7028 {
7029     bool changed = false;
7030     auto safeArea = ConvertAvoidArea(avoidArea);
7031 
7032     if (type == Rosen::AvoidAreaType::TYPE_SYSTEM) {
7033         changed = (systemSafeArea_ != safeArea);
7034         systemSafeArea_ = safeArea;
7035     } else if (type == Rosen::AvoidAreaType::TYPE_CUTOUT) {
7036         changed = (cutoutSafeArea_ != safeArea);
7037         cutoutSafeArea_ = safeArea;
7038     } else if (type == Rosen::AvoidAreaType::TYPE_NAVIGATION_INDICATOR) {
7039         changed = (navigationIndicatorSafeArea_ != safeArea);
7040         navigationIndicatorSafeArea_ = safeArea;
7041     }
7042 
7043     if (changed) {
7044         OnSafeInsetsChange();
7045     }
7046 }
7047 
OnInterceptKeyboardAttach(const std::shared_ptr<OHOS::NWeb::NWebCustomKeyboardHandler> keyboardHandler,const std::map<std::string,std::string> & attributes,bool & useSystemKeyboard,int32_t & enterKeyType)7048 void WebDelegate::OnInterceptKeyboardAttach(
7049     const std::shared_ptr<OHOS::NWeb::NWebCustomKeyboardHandler> keyboardHandler,
7050     const std::map<std::string, std::string> &attributes, bool &useSystemKeyboard, int32_t &enterKeyType)
7051 {
7052     CHECK_NULL_VOID(onInterceptKeyboardAttachV2_);
7053     auto context = context_.Upgrade();
7054     CHECK_NULL_VOID(context);
7055     keyboardHandler_ = keyboardHandler;
7056     WebKeyboardOption keyboardOpt;
7057     std::function<void()> buildFunc = nullptr;
7058     context->GetTaskExecutor()->PostSyncTask(
7059         [weak = WeakClaim(this), &keyboardHandler, &attributes, &keyboardOpt]() {
7060             auto delegate = weak.Upgrade();
7061             CHECK_NULL_VOID(delegate);
7062             auto onInterceptKeyboardAttachV2_ = delegate->onInterceptKeyboardAttachV2_;
7063             if (onInterceptKeyboardAttachV2_) {
7064                 auto param = AceType::MakeRefPtr<WebCustomKeyboardHandlerOhos>(keyboardHandler);
7065                 keyboardOpt = onInterceptKeyboardAttachV2_(std::make_shared<InterceptKeyboardEvent>(param, attributes));
7066             }
7067         },
7068         TaskExecutor::TaskType::JS, "ArkUIWebHandleInterceptKeyboardAttach");
7069 
7070     useSystemKeyboard = keyboardOpt.isSystemKeyboard_;
7071     enterKeyType = keyboardOpt.enterKeyTpye_;
7072     auto webPattern = webPattern_.Upgrade();
7073     CHECK_NULL_VOID(webPattern);
7074     webPattern->SetCustomKeyboardBuilder(keyboardOpt.customKeyboardBuilder_);
7075     TAG_LOGI(AceLogTag::ACE_WEB, "WebCustomKeyboard OnInterceptKeyboardAttach sync task end");
7076 }
7077 
OnCustomKeyboardAttach()7078 void WebDelegate::OnCustomKeyboardAttach()
7079 {
7080     auto webPattern = webPattern_.Upgrade();
7081     CHECK_NULL_VOID(webPattern);
7082     webPattern->AttachCustomKeyboard();
7083 }
7084 
OnCustomKeyboardClose()7085 void WebDelegate::OnCustomKeyboardClose()
7086 {
7087     auto webPattern = webPattern_.Upgrade();
7088     CHECK_NULL_VOID(webPattern);
7089     webPattern->CloseCustomKeyboard();
7090 }
7091 
KeyboardReDispatch(const std::shared_ptr<OHOS::NWeb::NWebKeyEvent> & event,bool isUsed)7092 void WebDelegate::KeyboardReDispatch(const std::shared_ptr<OHOS::NWeb::NWebKeyEvent>& event, bool isUsed)
7093 {
7094     auto webPattern = webPattern_.Upgrade();
7095     CHECK_NULL_VOID(webPattern);
7096     webPattern->KeyboardReDispatch(event, isUsed);
7097 }
7098 
OnCursorUpdate(double x,double y,double width,double height)7099 void WebDelegate::OnCursorUpdate(double x, double y, double width, double height)
7100 {
7101     auto webPattern = webPattern_.Upgrade();
7102     CHECK_NULL_VOID(webPattern);
7103     webPattern->OnCursorUpdate(x, y, width, height);
7104 }
7105 
OnSafeInsetsChange()7106 void WebDelegate::OnSafeInsetsChange()
7107 {
7108     NG::SafeAreaInsets resultSafeArea({0, 0}, {0, 0}, {0, 0}, {0, 0});
7109     resultSafeArea = resultSafeArea.Combine(systemSafeArea_);
7110     resultSafeArea = resultSafeArea.Combine(cutoutSafeArea_);
7111     resultSafeArea = resultSafeArea.Combine(navigationIndicatorSafeArea_);
7112 
7113     int left = 0;
7114     if (resultSafeArea.left_.IsValid() && resultSafeArea.left_.end > currentArea_.Left()) {
7115         left = static_cast<int>(resultSafeArea.left_.start + resultSafeArea.left_.end);
7116     }
7117     int top = 0;
7118     if (resultSafeArea.top_.IsValid() && resultSafeArea.top_.end > currentArea_.Top()) {
7119         top = static_cast<int>(resultSafeArea.top_.end - resultSafeArea.top_.start);
7120     }
7121     int right = 0;
7122     if (resultSafeArea.right_.IsValid() && resultSafeArea.right_.start < currentArea_.Right()) {
7123         constexpr static int32_t CUTOUT_EDGES_BALANCE_FACTOR = 2;
7124         right = static_cast<int>(resultSafeArea.right_.end - resultSafeArea.right_.start +
7125                 (currentArea_.Right() - resultSafeArea.right_.end) * CUTOUT_EDGES_BALANCE_FACTOR);
7126     }
7127     int bottom = 0;
7128     if (resultSafeArea.bottom_.IsValid() && resultSafeArea.bottom_.start < currentArea_.Bottom()) {
7129         bottom = static_cast<int>(resultSafeArea.bottom_.end - resultSafeArea.bottom_.start);
7130     }
7131 
7132     if (left < 0 || bottom < 0 || right < 0 || top < 0) {
7133         TAG_LOGE(AceLogTag::ACE_WEB, "WebDelegate::OnSafeInsetsChange occur errors "
7134                 "ltrb:%{public}d,%{public}d,%{public}d,%{public}d", left, top, right, bottom);
7135         return;
7136     }
7137 
7138     TAG_LOGD(AceLogTag::ACE_WEB,
7139         "WebDelegate::OnSafeInsetsChange left:%{public}d top:%{public}d right:%{public}d bottom:%{public}d "
7140         "systemSafeArea:%{public}s cutoutSafeArea:%{public}s navigationIndicatorSafeArea:%{public}s "
7141         "resultSafeArea:%{public}s currentArea:%{public}s", left, top, right, bottom,
7142         systemSafeArea_.ToString().c_str(), cutoutSafeArea_.ToString().c_str(),
7143         navigationIndicatorSafeArea_.ToString().c_str(), resultSafeArea.ToString().c_str(),
7144         currentArea_.ToString().c_str());
7145 
7146     auto context = context_.Upgrade();
7147     if (!context) {
7148         return;
7149     }
7150     context->GetTaskExecutor()->PostTask(
7151         [weak = WeakClaim(this), left, top, right, bottom]() {
7152             auto delegate = weak.Upgrade();
7153             if (delegate && delegate->nweb_ && !delegate->window_) {
7154                 delegate->nweb_->OnSafeInsetsChange(left, top, right, bottom);
7155             }
7156         },
7157         TaskExecutor::TaskType::PLATFORM, "ArkUIWebSafeInsetsChange");
7158 }
7159 
CreateOverlay(void * data,size_t len,int width,int height,int offsetX,int offsetY,int rectWidth,int rectHeight,int pointX,int pointY)7160 void WebDelegate::CreateOverlay(void* data, size_t len, int width, int height, int offsetX, int offsetY, int rectWidth,
7161     int rectHeight, int pointX, int pointY)
7162 {
7163     auto webPattern = webPattern_.Upgrade();
7164     CHECK_NULL_VOID(webPattern);
7165     webPattern->CreateOverlay(PixelMap::ConvertSkImageToPixmap(static_cast<const uint32_t*>(data), len, width, height),
7166         offsetX,
7167         offsetY,
7168         rectWidth,
7169         rectHeight,
7170         pointX,
7171         pointY);
7172 }
7173 
OnOverlayStateChanged(int offsetX,int offsetY,int rectWidth,int rectHeight)7174 void WebDelegate::OnOverlayStateChanged(int offsetX, int offsetY, int rectWidth, int rectHeight)
7175 {
7176     auto webPattern = webPattern_.Upgrade();
7177     CHECK_NULL_VOID(webPattern);
7178     webPattern->OnOverlayStateChanged(offsetX, offsetY, rectWidth, rectHeight);
7179 }
7180 
OnTextSelected()7181 void WebDelegate::OnTextSelected()
7182 {
7183     auto delegate = WeakClaim(this).Upgrade();
7184     CHECK_NULL_VOID(delegate);
7185     if (delegate->nweb_) {
7186         delegate->nweb_->OnTextSelected();
7187     }
7188 }
7189 
OnDestroyImageAnalyzerOverlay()7190 void WebDelegate::OnDestroyImageAnalyzerOverlay()
7191 {
7192     CHECK_NULL_VOID(nweb_);
7193     nweb_->OnDestroyImageAnalyzerOverlay();
7194 }
7195 
GetWebInfoType()7196 std::string WebDelegate::GetWebInfoType()
7197 {
7198     std::string factoryLevel = NWebAdapterHelper::Instance()
7199         .ParsePerfConfig("factoryConfig", "factoryLevel");
7200     if (factoryLevel.empty()) {
7201         NWebAdapterHelper::Instance().ReadConfigIfNeeded();
7202         factoryLevel = NWebAdapterHelper::Instance().
7203             ParsePerfConfig("factoryConfig", "factoryLevel");
7204     }
7205     TAG_LOGD(AceLogTag::ACE_WEB, "read config factoryLevel: %{public}s ", factoryLevel.c_str());
7206     return factoryLevel;
7207 }
7208 
SetSurfaceId(const std::string & surfaceId)7209 void WebDelegate::SetSurfaceId(const std::string& surfaceId)
7210 {
7211     auto context = context_.Upgrade();
7212     if (!context) {
7213         return;
7214     }
7215     context->GetTaskExecutor()->PostTask(
7216         [weak = WeakClaim(this), surfaceId]() {
7217             auto delegate = weak.Upgrade();
7218             if (delegate && delegate->nweb_) {
7219                 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = delegate->nweb_->GetPreference();
7220                 CHECK_NULL_VOID(setting);
7221                 setting->SetSurfaceId(surfaceId);
7222             }
7223         },
7224         TaskExecutor::TaskType::PLATFORM, "ArkUIWebSetSurfaceId");
7225 }
7226 
OnAdsBlocked(const std::string & url,const std::vector<std::string> & adsBlocked)7227 void WebDelegate::OnAdsBlocked(const std::string& url, const std::vector<std::string>& adsBlocked)
7228 {
7229     auto context = context_.Upgrade();
7230     CHECK_NULL_VOID(context);
7231     context->GetTaskExecutor()->PostTask(
7232         [weak = WeakClaim(this), url, adsBlocked]() {
7233             auto delegate = weak.Upgrade();
7234             CHECK_NULL_VOID(delegate);
7235             auto onAdsBlockedV2 = delegate->onAdsBlockedV2_;
7236             if (onAdsBlockedV2) {
7237                 onAdsBlockedV2(std::make_shared<AdsBlockedEvent>(url, adsBlocked));
7238             }
7239         },
7240         TaskExecutor::TaskType::JS, "ArkUiWebAdsBlocked");
7241 }
7242 
SpanstringConvertHtml(const std::vector<uint8_t> & content)7243 std::string WebDelegate::SpanstringConvertHtml(const std::vector<uint8_t> &content)
7244 {
7245     std::vector<uint8_t> tempVec(content.begin(), content.end());
7246     std::string htmlStr = OHOS::Ace::SpanToHtml::ToHtml(tempVec);
7247     TAG_LOGD(AceLogTag::ACE_WEB, "pasteboard spasntring convert html success,"
7248         " string length = %{public}u", static_cast<int32_t>(htmlStr.length()));
7249     return htmlStr;
7250 }
7251 
StartVibraFeedback(const std::string & vibratorType)7252 void WebDelegate::StartVibraFeedback(const std::string& vibratorType)
7253 {
7254     auto webPattern = webPattern_.Upgrade();
7255     CHECK_NULL_VOID(webPattern);
7256     webPattern->StartVibraFeedback(vibratorType);
7257 }
7258 
CloseImageOverlaySelection()7259 bool WebDelegate::CloseImageOverlaySelection()
7260 {
7261     auto webPattern = webPattern_.Upgrade();
7262     CHECK_NULL_RETURN(webPattern, false);
7263     return webPattern->CloseImageOverlaySelection();
7264 }
7265 
GetAccessibilityVisible(int64_t accessibilityId)7266 bool WebDelegate::GetAccessibilityVisible(int64_t accessibilityId)
7267 {
7268     CHECK_NULL_RETURN(nweb_, true);
7269     return nweb_->GetAccessibilityVisible(accessibilityId);
7270 }
7271 } // namespace OHOS::Ace
7272