• 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 "frameworks/bridge/declarative_frontend/jsview/js_web.h"
17 
18 #include <optional>
19 #include <string>
20 
21 #include "pixel_map.h"
22 #include "pixel_map_napi.h"
23 #include "securec.h"
24 
25 #include "base/log/ace_scoring_log.h"
26 #include "base/memory/ace_type.h"
27 #include "base/memory/referenced.h"
28 #include "base/utils/utils.h"
29 #if !defined(ANDROID_PLATFORM) && !defined(IOS_PLATFORM)
30 #include "base/web/webview/ohos_nweb/include/nweb.h"
31 #else
32 #include "base/web/webview/ohos_interface/include/ohos_nweb/nweb.h"
33 #endif
34 #include "bridge/common/utils/engine_helper.h"
35 #include "bridge/declarative_frontend/engine/functions/js_click_function.h"
36 #include "bridge/declarative_frontend/engine/functions/js_drag_function.h"
37 #include "bridge/declarative_frontend/engine/functions/js_key_function.h"
38 #include "bridge/declarative_frontend/engine/js_converter.h"
39 #include "bridge/declarative_frontend/engine/js_ref_ptr.h"
40 #include "bridge/declarative_frontend/jsview/js_utils.h"
41 #include "bridge/declarative_frontend/jsview/js_web_controller.h"
42 #include "bridge/declarative_frontend/jsview/models/web_model_impl.h"
43 #include "bridge/declarative_frontend/view_stack_processor.h"
44 #include "core/common/ace_application_info.h"
45 #include "core/common/container.h"
46 #include "core/common/container_scope.h"
47 #include "core/components/web/web_event.h"
48 #include "core/components_ng/base/frame_node.h"
49 #include "core/components_ng/pattern/web/web_model_ng.h"
50 #include "core/pipeline/pipeline_base.h"
51 
52 namespace OHOS::Ace {
53 namespace {
54 const std::string RAWFILE_PREFIX = "resource://RAWFILE/";
55 const std::string BUNDLE_NAME_PREFIX = "bundleName:";
56 const std::string MODULE_NAME_PREFIX = "moduleName:";
57 
58 const int32_t SELECTION_MENU_OPTION_PARAM_INDEX = 3;
59 const int32_t SELECTION_MENU_CONTENT_PARAM_INDEX = 2;
60 const int32_t PARAM_ZERO = 0;
61 const int32_t PARAM_ONE = 1;
62 const int32_t PARAM_TWO = 2;
63 constexpr Dimension PREVIEW_MENU_MARGIN_LEFT = 16.0_vp;
64 constexpr Dimension PREVIEW_MENU_MARGIN_RIGHT = 16.0_vp;
65 
EraseSpace(std::string & data)66 void EraseSpace(std::string& data)
67 {
68     auto iter = data.begin();
69     while (iter != data.end()) {
70         if (isspace(*iter)) {
71             iter = data.erase(iter);
72         } else {
73             ++iter;
74         }
75     }
76 }
77 }
78 
79 std::unique_ptr<WebModel> WebModel::instance_ = nullptr;
80 std::mutex WebModel::mutex_;
GetInstance()81 WebModel* WebModel::GetInstance()
82 {
83     if (!instance_) {
84         std::lock_guard<std::mutex> lock(mutex_);
85         if (!instance_) {
86 #ifdef NG_BUILD
87             instance_.reset(new NG::WebModelNG());
88 #else
89             if (Container::IsCurrentUseNewPipeline()) {
90                 instance_.reset(new NG::WebModelNG());
91             } else {
92                 instance_.reset(new Framework::WebModelImpl());
93             }
94 #endif
95         }
96     }
97     return instance_.get();
98 }
99 
100 } // namespace OHOS::Ace
101 
102 namespace OHOS::Ace::Framework {
103 bool JSWeb::webDebuggingAccess_ = false;
104 class JSWebDialog : public Referenced {
105 public:
JSBind(BindingTarget globalObj)106     static void JSBind(BindingTarget globalObj)
107     {
108         JSClass<JSWebDialog>::Declare("WebDialog");
109         JSClass<JSWebDialog>::CustomMethod("handleConfirm", &JSWebDialog::Confirm);
110         JSClass<JSWebDialog>::CustomMethod("handleCancel", &JSWebDialog::Cancel);
111         JSClass<JSWebDialog>::CustomMethod("handlePromptConfirm", &JSWebDialog::PromptConfirm);
112         JSClass<JSWebDialog>::Bind(globalObj, &JSWebDialog::Constructor, &JSWebDialog::Destructor);
113     }
114 
SetResult(const RefPtr<Result> & result)115     void SetResult(const RefPtr<Result>& result)
116     {
117         result_ = result;
118     }
119 
Confirm(const JSCallbackInfo & args)120     void Confirm(const JSCallbackInfo& args)
121     {
122         if (result_) {
123             result_->Confirm();
124         }
125     }
126 
PromptConfirm(const JSCallbackInfo & args)127     void PromptConfirm(const JSCallbackInfo& args)
128     {
129         std::string message;
130         if (!result_) {
131             return;
132         }
133         if (args.Length() == 1 && args[0]->IsString()) {
134             message = args[0]->ToString();
135             result_->Confirm(message);
136         }
137     }
138 
Cancel(const JSCallbackInfo & args)139     void Cancel(const JSCallbackInfo& args)
140     {
141         if (result_) {
142             result_->Cancel();
143         }
144     }
145 
146 private:
Constructor(const JSCallbackInfo & args)147     static void Constructor(const JSCallbackInfo& args)
148     {
149         auto jsWebDialog = Referenced::MakeRefPtr<JSWebDialog>();
150         jsWebDialog->IncRefCount();
151         args.SetReturnValue(Referenced::RawPtr(jsWebDialog));
152     }
153 
Destructor(JSWebDialog * jsWebDialog)154     static void Destructor(JSWebDialog* jsWebDialog)
155     {
156         if (jsWebDialog != nullptr) {
157             jsWebDialog->DecRefCount();
158         }
159     }
160 
161     RefPtr<Result> result_;
162 };
163 
164 class JSFullScreenExitHandler : public Referenced {
165 public:
JSBind(BindingTarget globalObj)166     static void JSBind(BindingTarget globalObj)
167     {
168         JSClass<JSFullScreenExitHandler>::Declare("FullScreenExitHandler");
169         JSClass<JSFullScreenExitHandler>::CustomMethod("exitFullScreen", &JSFullScreenExitHandler::ExitFullScreen);
170         JSClass<JSFullScreenExitHandler>::Bind(
171             globalObj, &JSFullScreenExitHandler::Constructor, &JSFullScreenExitHandler::Destructor);
172     }
173 
SetHandler(const RefPtr<FullScreenExitHandler> & handler)174     void SetHandler(const RefPtr<FullScreenExitHandler>& handler)
175     {
176         fullScreenExitHandler_ = handler;
177     }
178 
ExitFullScreen(const JSCallbackInfo & args)179     void ExitFullScreen(const JSCallbackInfo& args)
180     {
181         if (fullScreenExitHandler_) {
182             fullScreenExitHandler_->ExitFullScreen();
183         }
184     }
185 
186 private:
Constructor(const JSCallbackInfo & args)187     static void Constructor(const JSCallbackInfo& args)
188     {
189         auto jsFullScreenExitHandler = Referenced::MakeRefPtr<JSFullScreenExitHandler>();
190         jsFullScreenExitHandler->IncRefCount();
191         args.SetReturnValue(Referenced::RawPtr(jsFullScreenExitHandler));
192     }
193 
Destructor(JSFullScreenExitHandler * jsFullScreenExitHandler)194     static void Destructor(JSFullScreenExitHandler* jsFullScreenExitHandler)
195     {
196         if (jsFullScreenExitHandler != nullptr) {
197             jsFullScreenExitHandler->DecRefCount();
198         }
199     }
200     RefPtr<FullScreenExitHandler> fullScreenExitHandler_;
201 };
202 
203 class JSWebKeyboardController : public Referenced {
204 public:
JSBind(BindingTarget globalObj)205     static void JSBind(BindingTarget globalObj)
206     {
207         JSClass<JSWebKeyboardController>::Declare("WebKeyboardController");
208         JSClass<JSWebKeyboardController>::CustomMethod("insertText", &JSWebKeyboardController::InsertText);
209         JSClass<JSWebKeyboardController>::CustomMethod("deleteForward", &JSWebKeyboardController::DeleteForward);
210         JSClass<JSWebKeyboardController>::CustomMethod("deleteBackward", &JSWebKeyboardController::DeleteBackward);
211         JSClass<JSWebKeyboardController>::CustomMethod("sendFunctionKey", &JSWebKeyboardController::SendFunctionKey);
212         JSClass<JSWebKeyboardController>::CustomMethod("close", &JSWebKeyboardController::Close);
213         JSClass<JSWebKeyboardController>::Bind(
214             globalObj, &JSWebKeyboardController::Constructor, &JSWebKeyboardController::Destructor);
215     }
216 
SeWebKeyboardController(const RefPtr<WebCustomKeyboardHandler> & controller)217     void SeWebKeyboardController(const RefPtr<WebCustomKeyboardHandler>& controller)
218     {
219         webKeyboardController_ = controller;
220     }
221 
InsertText(const JSCallbackInfo & args)222     void InsertText(const JSCallbackInfo& args)
223     {
224         if (!webKeyboardController_) {
225             return;
226         }
227 
228         if (args.Length() < 1 || !(args[0]->IsString())) {
229             return;
230         }
231 
232         webKeyboardController_->InsertText(args[0]->ToString());
233     }
234 
DeleteForward(const JSCallbackInfo & args)235     void DeleteForward(const JSCallbackInfo& args)
236     {
237         if (!webKeyboardController_) {
238             return;
239         }
240 
241         if (args.Length() < 1 || !(args[0]->IsNumber())) {
242             return;
243         }
244 
245         webKeyboardController_->DeleteForward(args[0]->ToNumber<int32_t>());
246     }
247 
DeleteBackward(const JSCallbackInfo & args)248     void DeleteBackward(const JSCallbackInfo& args)
249     {
250         if (!webKeyboardController_) {
251             return;
252         }
253 
254         if (args.Length() < 1 || !(args[0]->IsNumber())) {
255             return;
256         }
257 
258         webKeyboardController_->DeleteBackward(args[0]->ToNumber<int32_t>());
259     }
260 
SendFunctionKey(const JSCallbackInfo & args)261     void SendFunctionKey(const JSCallbackInfo& args)
262     {
263         if (!webKeyboardController_) {
264             return;
265         }
266 
267         if (args.Length() < 1 || !(args[0]->IsNumber())) {
268             return;
269         }
270 
271         webKeyboardController_->SendFunctionKey(args[0]->ToNumber<int32_t>());
272     }
273 
Close(const JSCallbackInfo & args)274     void Close(const JSCallbackInfo& args)
275     {
276         webKeyboardController_->Close();
277     }
278 
279 private:
Constructor(const JSCallbackInfo & args)280     static void Constructor(const JSCallbackInfo& args)
281     {
282         auto jSWebKeyboardController = Referenced::MakeRefPtr<JSWebKeyboardController>();
283         jSWebKeyboardController->IncRefCount();
284         args.SetReturnValue(Referenced::RawPtr(jSWebKeyboardController));
285     }
286 
Destructor(JSWebKeyboardController * jSWebKeyboardController)287     static void Destructor(JSWebKeyboardController* jSWebKeyboardController)
288     {
289         if (jSWebKeyboardController != nullptr) {
290             jSWebKeyboardController->DecRefCount();
291         }
292     }
293     RefPtr<WebCustomKeyboardHandler> webKeyboardController_;
294 };
295 
296 class JSWebHttpAuth : public Referenced {
297 public:
JSBind(BindingTarget globalObj)298     static void JSBind(BindingTarget globalObj)
299     {
300         JSClass<JSWebHttpAuth>::Declare("WebHttpAuthResult");
301         JSClass<JSWebHttpAuth>::CustomMethod("confirm", &JSWebHttpAuth::Confirm);
302         JSClass<JSWebHttpAuth>::CustomMethod("cancel", &JSWebHttpAuth::Cancel);
303         JSClass<JSWebHttpAuth>::CustomMethod("isHttpAuthInfoSaved", &JSWebHttpAuth::IsHttpAuthInfoSaved);
304         JSClass<JSWebHttpAuth>::Bind(globalObj, &JSWebHttpAuth::Constructor, &JSWebHttpAuth::Destructor);
305     }
306 
SetResult(const RefPtr<AuthResult> & result)307     void SetResult(const RefPtr<AuthResult>& result)
308     {
309         result_ = result;
310     }
311 
Confirm(const JSCallbackInfo & args)312     void Confirm(const JSCallbackInfo& args)
313     {
314         if (args.Length() < 2 || !args[0]->IsString() || !args[1]->IsString()) {
315             auto code = JSVal(ToJSValue(false));
316             auto descriptionRef = JSRef<JSVal>::Make(code);
317             args.SetReturnValue(descriptionRef);
318             return;
319         }
320         std::string userName = args[0]->ToString();
321         std::string password = args[1]->ToString();
322         bool ret = false;
323         if (result_) {
324             result_->Confirm(userName, password);
325             ret = true;
326         }
327         auto code = JSVal(ToJSValue(ret));
328         auto descriptionRef = JSRef<JSVal>::Make(code);
329         args.SetReturnValue(descriptionRef);
330     }
331 
Cancel(const JSCallbackInfo & args)332     void Cancel(const JSCallbackInfo& args)
333     {
334         if (result_) {
335             result_->Cancel();
336         }
337     }
338 
IsHttpAuthInfoSaved(const JSCallbackInfo & args)339     void IsHttpAuthInfoSaved(const JSCallbackInfo& args)
340     {
341         bool ret = false;
342         if (result_) {
343             ret = result_->IsHttpAuthInfoSaved();
344         }
345         auto code = JSVal(ToJSValue(ret));
346         auto descriptionRef = JSRef<JSVal>::Make(code);
347         args.SetReturnValue(descriptionRef);
348     }
349 
350 private:
Constructor(const JSCallbackInfo & args)351     static void Constructor(const JSCallbackInfo& args)
352     {
353         auto jsWebHttpAuth = Referenced::MakeRefPtr<JSWebHttpAuth>();
354         jsWebHttpAuth->IncRefCount();
355         args.SetReturnValue(Referenced::RawPtr(jsWebHttpAuth));
356     }
357 
Destructor(JSWebHttpAuth * jsWebHttpAuth)358     static void Destructor(JSWebHttpAuth* jsWebHttpAuth)
359     {
360         if (jsWebHttpAuth != nullptr) {
361             jsWebHttpAuth->DecRefCount();
362         }
363     }
364 
365     RefPtr<AuthResult> result_;
366 };
367 
368 class JSWebSslError : public Referenced {
369 public:
JSBind(BindingTarget globalObj)370     static void JSBind(BindingTarget globalObj)
371     {
372         JSClass<JSWebSslError>::Declare("WebSslErrorResult");
373         JSClass<JSWebSslError>::CustomMethod("handleConfirm", &JSWebSslError::HandleConfirm);
374         JSClass<JSWebSslError>::CustomMethod("handleCancel", &JSWebSslError::HandleCancel);
375         JSClass<JSWebSslError>::Bind(globalObj, &JSWebSslError::Constructor, &JSWebSslError::Destructor);
376     }
377 
SetResult(const RefPtr<SslErrorResult> & result)378     void SetResult(const RefPtr<SslErrorResult>& result)
379     {
380         result_ = result;
381     }
382 
HandleConfirm(const JSCallbackInfo & args)383     void HandleConfirm(const JSCallbackInfo& args)
384     {
385         if (result_) {
386             result_->HandleConfirm();
387         }
388     }
389 
HandleCancel(const JSCallbackInfo & args)390     void HandleCancel(const JSCallbackInfo& args)
391     {
392         if (result_) {
393             result_->HandleCancel();
394         }
395     }
396 
397 private:
Constructor(const JSCallbackInfo & args)398     static void Constructor(const JSCallbackInfo& args)
399     {
400         auto jsWebSslError = Referenced::MakeRefPtr<JSWebSslError>();
401         jsWebSslError->IncRefCount();
402         args.SetReturnValue(Referenced::RawPtr(jsWebSslError));
403     }
404 
Destructor(JSWebSslError * jsWebSslError)405     static void Destructor(JSWebSslError* jsWebSslError)
406     {
407         if (jsWebSslError != nullptr) {
408             jsWebSslError->DecRefCount();
409         }
410     }
411 
412     RefPtr<SslErrorResult> result_;
413 };
414 
415 class JSWebAllSslError : public Referenced {
416 public:
JSBind(BindingTarget globalObj)417     static void JSBind(BindingTarget globalObj)
418     {
419         JSClass<JSWebAllSslError>::Declare("WebAllSslErrorResult");
420         JSClass<JSWebAllSslError>::CustomMethod("handleConfirm", &JSWebAllSslError::HandleConfirm);
421         JSClass<JSWebAllSslError>::CustomMethod("handleCancel", &JSWebAllSslError::HandleCancel);
422         JSClass<JSWebAllSslError>::Bind(globalObj, &JSWebAllSslError::Constructor, &JSWebAllSslError::Destructor);
423     }
424 
SetResult(const RefPtr<AllSslErrorResult> & result)425     void SetResult(const RefPtr<AllSslErrorResult>& result)
426     {
427         result_ = result;
428     }
429 
HandleConfirm(const JSCallbackInfo & args)430     void HandleConfirm(const JSCallbackInfo& args)
431     {
432         if (result_) {
433             result_->HandleConfirm();
434         }
435     }
436 
HandleCancel(const JSCallbackInfo & args)437     void HandleCancel(const JSCallbackInfo& args)
438     {
439         if (result_) {
440             result_->HandleCancel();
441         }
442     }
443 
444 private:
Constructor(const JSCallbackInfo & args)445     static void Constructor(const JSCallbackInfo& args)
446     {
447         auto jsWebAllSslError = Referenced::MakeRefPtr<JSWebAllSslError>();
448         jsWebAllSslError->IncRefCount();
449         args.SetReturnValue(Referenced::RawPtr(jsWebAllSslError));
450     }
451 
Destructor(JSWebAllSslError * jsWebAllSslError)452     static void Destructor(JSWebAllSslError* jsWebAllSslError)
453     {
454         if (jsWebAllSslError != nullptr) {
455             jsWebAllSslError->DecRefCount();
456         }
457     }
458 
459     RefPtr<AllSslErrorResult> result_;
460 };
461 
462 class JSWebSslSelectCert : public Referenced {
463 public:
JSBind(BindingTarget globalObj)464     static void JSBind(BindingTarget globalObj)
465     {
466         JSClass<JSWebSslSelectCert>::Declare("WebSslSelectCertResult");
467         JSClass<JSWebSslSelectCert>::CustomMethod("confirm", &JSWebSslSelectCert::HandleConfirm);
468         JSClass<JSWebSslSelectCert>::CustomMethod("cancel", &JSWebSslSelectCert::HandleCancel);
469         JSClass<JSWebSslSelectCert>::CustomMethod("ignore", &JSWebSslSelectCert::HandleIgnore);
470         JSClass<JSWebSslSelectCert>::Bind(globalObj, &JSWebSslSelectCert::Constructor, &JSWebSslSelectCert::Destructor);
471     }
472 
SetResult(const RefPtr<SslSelectCertResult> & result)473     void SetResult(const RefPtr<SslSelectCertResult>& result)
474     {
475         result_ = result;
476     }
477 
HandleConfirm(const JSCallbackInfo & args)478     void HandleConfirm(const JSCallbackInfo& args)
479     {
480         std::string privateKeyFile;
481         std::string certChainFile;
482         if (args.Length() == 1 && args[0]->IsString()) {
483             privateKeyFile = args[0]->ToString();
484         } else if (args.Length() == 2 && args[0]->IsString() && args[1]->IsString()) {
485             privateKeyFile = args[0]->ToString();
486             certChainFile = args[1]->ToString();
487         } else {
488             return;
489         }
490 
491         if (result_) {
492             result_->HandleConfirm(privateKeyFile, certChainFile);
493         }
494     }
495 
HandleCancel(const JSCallbackInfo & args)496     void HandleCancel(const JSCallbackInfo& args)
497     {
498         if (result_) {
499             result_->HandleCancel();
500         }
501     }
502 
HandleIgnore(const JSCallbackInfo & args)503     void HandleIgnore(const JSCallbackInfo& args)
504     {
505         if (result_) {
506             result_->HandleIgnore();
507         }
508     }
509 
510 private:
Constructor(const JSCallbackInfo & args)511     static void Constructor(const JSCallbackInfo& args)
512     {
513         auto jsWebSslSelectCert = Referenced::MakeRefPtr<JSWebSslSelectCert>();
514         jsWebSslSelectCert->IncRefCount();
515         args.SetReturnValue(Referenced::RawPtr(jsWebSslSelectCert));
516     }
517 
Destructor(JSWebSslSelectCert * jsWebSslSelectCert)518     static void Destructor(JSWebSslSelectCert* jsWebSslSelectCert)
519     {
520         if (jsWebSslSelectCert != nullptr) {
521             jsWebSslSelectCert->DecRefCount();
522         }
523     }
524 
525     RefPtr<SslSelectCertResult> result_;
526 };
527 
528 class JSWebConsoleLog : public Referenced {
529 public:
JSBind(BindingTarget globalObj)530     static void JSBind(BindingTarget globalObj)
531     {
532         JSClass<JSWebConsoleLog>::Declare("ConsoleMessage");
533         JSClass<JSWebConsoleLog>::CustomMethod("getLineNumber", &JSWebConsoleLog::GetLineNumber);
534         JSClass<JSWebConsoleLog>::CustomMethod("getMessage", &JSWebConsoleLog::GetLog);
535         JSClass<JSWebConsoleLog>::CustomMethod("getMessageLevel", &JSWebConsoleLog::GetLogLevel);
536         JSClass<JSWebConsoleLog>::CustomMethod("getSourceId", &JSWebConsoleLog::GetSourceId);
537         JSClass<JSWebConsoleLog>::Bind(globalObj, &JSWebConsoleLog::Constructor, &JSWebConsoleLog::Destructor);
538     }
539 
SetMessage(const RefPtr<WebConsoleLog> & message)540     void SetMessage(const RefPtr<WebConsoleLog>& message)
541     {
542         message_ = message;
543     }
544 
GetLineNumber(const JSCallbackInfo & args)545     void GetLineNumber(const JSCallbackInfo& args)
546     {
547         auto code = JSVal(ToJSValue(message_->GetLineNumber()));
548         auto descriptionRef = JSRef<JSVal>::Make(code);
549         args.SetReturnValue(descriptionRef);
550     }
551 
GetLog(const JSCallbackInfo & args)552     void GetLog(const JSCallbackInfo& args)
553     {
554         auto code = JSVal(ToJSValue(message_->GetLog()));
555         auto descriptionRef = JSRef<JSVal>::Make(code);
556         args.SetReturnValue(descriptionRef);
557     }
558 
GetLogLevel(const JSCallbackInfo & args)559     void GetLogLevel(const JSCallbackInfo& args)
560     {
561         auto code = JSVal(ToJSValue(message_->GetLogLevel()));
562         auto descriptionRef = JSRef<JSVal>::Make(code);
563         args.SetReturnValue(descriptionRef);
564     }
565 
GetSourceId(const JSCallbackInfo & args)566     void GetSourceId(const JSCallbackInfo& args)
567     {
568         auto code = JSVal(ToJSValue(message_->GetSourceId()));
569         auto descriptionRef = JSRef<JSVal>::Make(code);
570         args.SetReturnValue(descriptionRef);
571     }
572 
573 private:
Constructor(const JSCallbackInfo & args)574     static void Constructor(const JSCallbackInfo& args)
575     {
576         auto jsWebConsoleLog = Referenced::MakeRefPtr<JSWebConsoleLog>();
577         jsWebConsoleLog->IncRefCount();
578         args.SetReturnValue(Referenced::RawPtr(jsWebConsoleLog));
579     }
580 
Destructor(JSWebConsoleLog * jsWebConsoleLog)581     static void Destructor(JSWebConsoleLog* jsWebConsoleLog)
582     {
583         if (jsWebConsoleLog != nullptr) {
584             jsWebConsoleLog->DecRefCount();
585         }
586     }
587 
588     RefPtr<WebConsoleLog> message_;
589 };
590 
591 class JSWebGeolocation : public Referenced {
592 public:
JSBind(BindingTarget globalObj)593     static void JSBind(BindingTarget globalObj)
594     {
595         JSClass<JSWebGeolocation>::Declare("WebGeolocation");
596         JSClass<JSWebGeolocation>::CustomMethod("invoke", &JSWebGeolocation::Invoke);
597         JSClass<JSWebGeolocation>::Bind(globalObj, &JSWebGeolocation::Constructor, &JSWebGeolocation::Destructor);
598     }
599 
SetEvent(const LoadWebGeolocationShowEvent & eventInfo)600     void SetEvent(const LoadWebGeolocationShowEvent& eventInfo)
601     {
602         webGeolocation_ = eventInfo.GetWebGeolocation();
603     }
604 
Invoke(const JSCallbackInfo & args)605     void Invoke(const JSCallbackInfo& args)
606     {
607         std::string origin;
608         bool allow = false;
609         bool retain = false;
610         if (args[0]->IsString()) {
611             origin = args[0]->ToString();
612         }
613         if (args[1]->IsBoolean()) {
614             allow = args[1]->ToBoolean();
615         }
616         if (args[2]->IsBoolean()) {
617             retain = args[2]->ToBoolean();
618         }
619         if (webGeolocation_) {
620             webGeolocation_->Invoke(origin, allow, retain);
621         }
622     }
623 
624 private:
Constructor(const JSCallbackInfo & args)625     static void Constructor(const JSCallbackInfo& args)
626     {
627         auto jsWebGeolocation = Referenced::MakeRefPtr<JSWebGeolocation>();
628         jsWebGeolocation->IncRefCount();
629         args.SetReturnValue(Referenced::RawPtr(jsWebGeolocation));
630     }
631 
Destructor(JSWebGeolocation * jsWebGeolocation)632     static void Destructor(JSWebGeolocation* jsWebGeolocation)
633     {
634         if (jsWebGeolocation != nullptr) {
635             jsWebGeolocation->DecRefCount();
636         }
637     }
638 
639     RefPtr<WebGeolocation> webGeolocation_;
640 };
641 
642 class JSWebPermissionRequest : public Referenced {
643 public:
JSBind(BindingTarget globalObj)644     static void JSBind(BindingTarget globalObj)
645     {
646         JSClass<JSWebPermissionRequest>::Declare("WebPermissionRequest");
647         JSClass<JSWebPermissionRequest>::CustomMethod("deny", &JSWebPermissionRequest::Deny);
648         JSClass<JSWebPermissionRequest>::CustomMethod("getOrigin", &JSWebPermissionRequest::GetOrigin);
649         JSClass<JSWebPermissionRequest>::CustomMethod("getAccessibleResource", &JSWebPermissionRequest::GetResources);
650         JSClass<JSWebPermissionRequest>::CustomMethod("grant", &JSWebPermissionRequest::Grant);
651         JSClass<JSWebPermissionRequest>::Bind(
652             globalObj, &JSWebPermissionRequest::Constructor, &JSWebPermissionRequest::Destructor);
653     }
654 
SetEvent(const WebPermissionRequestEvent & eventInfo)655     void SetEvent(const WebPermissionRequestEvent& eventInfo)
656     {
657         webPermissionRequest_ = eventInfo.GetWebPermissionRequest();
658     }
659 
Deny(const JSCallbackInfo & args)660     void Deny(const JSCallbackInfo& args)
661     {
662         if (webPermissionRequest_) {
663             webPermissionRequest_->Deny();
664         }
665     }
666 
GetOrigin(const JSCallbackInfo & args)667     void GetOrigin(const JSCallbackInfo& args)
668     {
669         std::string origin;
670         if (webPermissionRequest_) {
671             origin = webPermissionRequest_->GetOrigin();
672         }
673         auto originJs = JSVal(ToJSValue(origin));
674         auto originJsRef = JSRef<JSVal>::Make(originJs);
675         args.SetReturnValue(originJsRef);
676     }
677 
GetResources(const JSCallbackInfo & args)678     void GetResources(const JSCallbackInfo& args)
679     {
680         JSRef<JSArray> result = JSRef<JSArray>::New();
681         if (webPermissionRequest_) {
682             std::vector<std::string> resources = webPermissionRequest_->GetResources();
683             uint32_t index = 0;
684             for (auto iterator = resources.begin(); iterator != resources.end(); ++iterator) {
685                 auto valueStr = JSVal(ToJSValue(*iterator));
686                 auto value = JSRef<JSVal>::Make(valueStr);
687                 result->SetValueAt(index++, value);
688             }
689         }
690         args.SetReturnValue(result);
691     }
692 
Grant(const JSCallbackInfo & args)693     void Grant(const JSCallbackInfo& args)
694     {
695         if (args.Length() < 1) {
696             if (webPermissionRequest_) {
697                 webPermissionRequest_->Deny();
698             }
699         }
700         std::vector<std::string> resources;
701         if (args[0]->IsArray()) {
702             JSRef<JSArray> array = JSRef<JSArray>::Cast(args[0]);
703             for (size_t i = 0; i < array->Length(); i++) {
704                 JSRef<JSVal> val = array->GetValueAt(i);
705                 if (!val->IsString()) {
706                     continue;
707                 }
708                 std::string res;
709                 if (!ConvertFromJSValue(val, res)) {
710                     continue;
711                 }
712                 resources.push_back(res);
713             }
714         }
715 
716         if (webPermissionRequest_) {
717             webPermissionRequest_->Grant(resources);
718         }
719     }
720 
721 private:
Constructor(const JSCallbackInfo & args)722     static void Constructor(const JSCallbackInfo& args)
723     {
724         auto jsWebPermissionRequest = Referenced::MakeRefPtr<JSWebPermissionRequest>();
725         jsWebPermissionRequest->IncRefCount();
726         args.SetReturnValue(Referenced::RawPtr(jsWebPermissionRequest));
727     }
728 
Destructor(JSWebPermissionRequest * jsWebPermissionRequest)729     static void Destructor(JSWebPermissionRequest* jsWebPermissionRequest)
730     {
731         if (jsWebPermissionRequest != nullptr) {
732             jsWebPermissionRequest->DecRefCount();
733         }
734     }
735 
736     RefPtr<WebPermissionRequest> webPermissionRequest_;
737 };
738 
739 class JSScreenCaptureRequest : public Referenced {
740 public:
JSBind(BindingTarget globalObj)741     static void JSBind(BindingTarget globalObj)
742     {
743         JSClass<JSScreenCaptureRequest>::Declare("ScreenCaptureRequest");
744         JSClass<JSScreenCaptureRequest>::CustomMethod("deny", &JSScreenCaptureRequest::Deny);
745         JSClass<JSScreenCaptureRequest>::CustomMethod("getOrigin", &JSScreenCaptureRequest::GetOrigin);
746         JSClass<JSScreenCaptureRequest>::CustomMethod("grant", &JSScreenCaptureRequest::Grant);
747         JSClass<JSScreenCaptureRequest>::Bind(
748             globalObj, &JSScreenCaptureRequest::Constructor, &JSScreenCaptureRequest::Destructor);
749     }
750 
SetEvent(const WebScreenCaptureRequestEvent & eventInfo)751     void SetEvent(const WebScreenCaptureRequestEvent& eventInfo)
752     {
753         request_ = eventInfo.GetWebScreenCaptureRequest();
754     }
755 
Deny(const JSCallbackInfo & args)756     void Deny(const JSCallbackInfo& args)
757     {
758         if (request_) {
759             request_->Deny();
760         }
761     }
762 
GetOrigin(const JSCallbackInfo & args)763     void GetOrigin(const JSCallbackInfo& args)
764     {
765         std::string origin;
766         if (request_) {
767             origin = request_->GetOrigin();
768         }
769         auto originJs = JSVal(ToJSValue(origin));
770         auto originJsRef = JSRef<JSVal>::Make(originJs);
771         args.SetReturnValue(originJsRef);
772     }
773 
Grant(const JSCallbackInfo & args)774     void Grant(const JSCallbackInfo& args)
775     {
776         if (!request_) {
777             return;
778         }
779         if (args.Length() < 1 || !args[0]->IsObject()) {
780             request_->Deny();
781             return;
782         }
783         JSRef<JSObject> paramObject = JSRef<JSObject>::Cast(args[0]);
784         auto captureModeObj = paramObject->GetProperty("captureMode");
785         if (!captureModeObj->IsNumber()) {
786             request_->Deny();
787             return;
788         }
789         int32_t captureMode = captureModeObj->ToNumber<int32_t>();
790         request_->SetCaptureMode(captureMode);
791         request_->SetSourceId(-1);
792         request_->Grant();
793     }
794 
795 private:
Constructor(const JSCallbackInfo & args)796     static void Constructor(const JSCallbackInfo& args)
797     {
798         auto jsScreenCaptureRequest = Referenced::MakeRefPtr<JSScreenCaptureRequest>();
799         jsScreenCaptureRequest->IncRefCount();
800         args.SetReturnValue(Referenced::RawPtr(jsScreenCaptureRequest));
801     }
802 
Destructor(JSScreenCaptureRequest * jsScreenCaptureRequest)803     static void Destructor(JSScreenCaptureRequest* jsScreenCaptureRequest)
804     {
805         if (jsScreenCaptureRequest != nullptr) {
806             jsScreenCaptureRequest->DecRefCount();
807         }
808     }
809 
810     RefPtr<WebScreenCaptureRequest> request_;
811 };
812 
813 class JSNativeEmbedGestureRequest : public Referenced {
814 public:
JSBind(BindingTarget globalObj)815     static void JSBind(BindingTarget globalObj)
816     {
817         JSClass<JSNativeEmbedGestureRequest>::Declare("NativeEmbedGesture");
818         JSClass<JSNativeEmbedGestureRequest>::CustomMethod(
819             "setGestureEventResult", &JSNativeEmbedGestureRequest::SetGestureEventResult);
820         JSClass<JSNativeEmbedGestureRequest>::Bind(
821             globalObj, &JSNativeEmbedGestureRequest::Constructor, &JSNativeEmbedGestureRequest::Destructor);
822     }
823 
SetResult(const RefPtr<GestureEventResult> & result)824     void SetResult(const RefPtr<GestureEventResult>& result)
825     {
826         eventResult_ = result;
827     }
828 
SetGestureEventResult(const JSCallbackInfo & args)829     void SetGestureEventResult(const JSCallbackInfo& args)
830     {
831         if (eventResult_) {
832             bool result = true;
833             bool stopPropagation = true;
834             if (args.Length() == PARAM_ONE && args[PARAM_ZERO]->IsBoolean()) {
835                 result = args[PARAM_ZERO]->ToBoolean();
836                 eventResult_->SetGestureEventResult(result);
837             } else if (args.Length() == PARAM_TWO && args[PARAM_ZERO]->IsBoolean() && args[PARAM_ONE]->IsBoolean()) {
838                 result = args[PARAM_ZERO]->ToBoolean();
839                 stopPropagation = args[PARAM_ONE]->ToBoolean();
840                 eventResult_->SetGestureEventResult(result, stopPropagation);
841             }
842         }
843     }
844 
845 private:
Constructor(const JSCallbackInfo & args)846     static void Constructor(const JSCallbackInfo& args)
847     {
848         auto jSNativeEmbedGestureRequest = Referenced::MakeRefPtr<JSNativeEmbedGestureRequest>();
849         jSNativeEmbedGestureRequest->IncRefCount();
850         args.SetReturnValue(Referenced::RawPtr(jSNativeEmbedGestureRequest));
851     }
852 
Destructor(JSNativeEmbedGestureRequest * jSNativeEmbedGestureRequest)853     static void Destructor(JSNativeEmbedGestureRequest* jSNativeEmbedGestureRequest)
854     {
855         if (jSNativeEmbedGestureRequest != nullptr) {
856             jSNativeEmbedGestureRequest->DecRefCount();
857         }
858     }
859 
860     RefPtr<GestureEventResult> eventResult_;
861 };
862 
863 class JSWebWindowNewHandler : public Referenced {
864 public:
865     struct ChildWindowInfo {
866         int32_t parentWebId_ = -1;
867         JSRef<JSObject> controller_;
868     };
869 
JSBind(BindingTarget globalObj)870     static void JSBind(BindingTarget globalObj)
871     {
872         JSClass<JSWebWindowNewHandler>::Declare("WebWindowNewHandler");
873         JSClass<JSWebWindowNewHandler>::CustomMethod("setWebController", &JSWebWindowNewHandler::SetWebController);
874         JSClass<JSWebWindowNewHandler>::Bind(
875             globalObj, &JSWebWindowNewHandler::Constructor, &JSWebWindowNewHandler::Destructor);
876     }
877 
SetEvent(const WebWindowNewEvent & eventInfo)878     void SetEvent(const WebWindowNewEvent& eventInfo)
879     {
880         handler_ = eventInfo.GetWebWindowNewHandler();
881     }
882 
PopController(int32_t id,int32_t * parentId=nullptr)883     static JSRef<JSObject> PopController(int32_t id, int32_t* parentId = nullptr)
884     {
885         auto iter = controller_map_.find(id);
886         if (iter == controller_map_.end()) {
887             return JSRef<JSVal>::Make();
888         }
889         auto controller = iter->second.controller_;
890         if (parentId) {
891             *parentId = iter->second.parentWebId_;
892         }
893         controller_map_.erase(iter);
894         return controller;
895     }
896 
ExistController(JSRef<JSObject> & controller,int32_t & parentWebId)897     static bool ExistController(JSRef<JSObject>& controller, int32_t& parentWebId)
898     {
899         auto getThisVarFunction = controller->GetProperty("innerGetThisVar");
900         if (!getThisVarFunction->IsFunction()) {
901             parentWebId = -1;
902             return false;
903         }
904         auto func = JSRef<JSFunc>::Cast(getThisVarFunction);
905         auto thisVar = func->Call(controller, 0, {});
906         int64_t thisPtr = thisVar->ToNumber<int64_t>();
907         for (auto iter = controller_map_.begin(); iter != controller_map_.end(); iter++) {
908             auto getThisVarFunction1 = iter->second.controller_->GetProperty("innerGetThisVar");
909             if (getThisVarFunction1->IsFunction()) {
910                 auto func1 = JSRef<JSFunc>::Cast(getThisVarFunction1);
911                 auto thisVar1 = func1->Call(iter->second.controller_, 0, {});
912                 if (thisPtr == thisVar1->ToNumber<int64_t>()) {
913                     parentWebId = iter->second.parentWebId_;
914                     return true;
915                 }
916             }
917         }
918         parentWebId = -1;
919         return false;
920     }
921 
SetWebController(const JSCallbackInfo & args)922     void SetWebController(const JSCallbackInfo& args)
923     {
924         if (handler_) {
925             int32_t parentNWebId = handler_->GetParentNWebId();
926             if (parentNWebId == -1) {
927                 return;
928             }
929             if (args.Length() < 1 || !args[0]->IsObject()) {
930                 WebModel::GetInstance()->NotifyPopupWindowResult(parentNWebId, false);
931                 return;
932             }
933             auto controller = JSRef<JSObject>::Cast(args[0]);
934             if (controller.IsEmpty()) {
935                 WebModel::GetInstance()->NotifyPopupWindowResult(parentNWebId, false);
936                 return;
937             }
938             auto getWebIdFunction = controller->GetProperty("innerGetWebId");
939             if (!getWebIdFunction->IsFunction()) {
940                 WebModel::GetInstance()->NotifyPopupWindowResult(parentNWebId, false);
941                 return;
942             }
943             auto func = JSRef<JSFunc>::Cast(getWebIdFunction);
944             auto webId = func->Call(controller, 0, {});
945             int32_t childWebId = webId->ToNumber<int32_t>();
946             if (childWebId == parentNWebId || childWebId != -1) {
947                 WebModel::GetInstance()->NotifyPopupWindowResult(parentNWebId, false);
948                 return;
949             }
950             controller_map_.insert(
951                 std::pair<int32_t, ChildWindowInfo>(handler_->GetId(), { parentNWebId, controller }));
952         }
953     }
954 
955 private:
Constructor(const JSCallbackInfo & args)956     static void Constructor(const JSCallbackInfo& args)
957     {
958         auto jsWebWindowNewHandler = Referenced::MakeRefPtr<JSWebWindowNewHandler>();
959         jsWebWindowNewHandler->IncRefCount();
960         args.SetReturnValue(Referenced::RawPtr(jsWebWindowNewHandler));
961     }
962 
Destructor(JSWebWindowNewHandler * jsWebWindowNewHandler)963     static void Destructor(JSWebWindowNewHandler* jsWebWindowNewHandler)
964     {
965         if (jsWebWindowNewHandler != nullptr) {
966             jsWebWindowNewHandler->DecRefCount();
967         }
968     }
969 
970     RefPtr<WebWindowNewHandler> handler_;
971     static std::unordered_map<int32_t, ChildWindowInfo> controller_map_;
972 };
973 std::unordered_map<int32_t, JSWebWindowNewHandler::ChildWindowInfo> JSWebWindowNewHandler::controller_map_;
974 
975 class JSDataResubmitted : public Referenced {
976 public:
JSBind(BindingTarget globalObj)977     static void JSBind(BindingTarget globalObj)
978     {
979         JSClass<JSDataResubmitted>::Declare("DataResubmissionHandler");
980         JSClass<JSDataResubmitted>::CustomMethod("resend", &JSDataResubmitted::Resend);
981         JSClass<JSDataResubmitted>::CustomMethod("cancel", &JSDataResubmitted::Cancel);
982         JSClass<JSDataResubmitted>::Bind(globalObj, &JSDataResubmitted::Constructor, &JSDataResubmitted::Destructor);
983     }
984 
SetHandler(const RefPtr<DataResubmitted> & handler)985     void SetHandler(const RefPtr<DataResubmitted>& handler)
986     {
987         dataResubmitted_ = handler;
988     }
989 
Resend(const JSCallbackInfo & args)990     void Resend(const JSCallbackInfo& args)
991     {
992         if (dataResubmitted_) {
993             dataResubmitted_->Resend();
994         }
995     }
996 
Cancel(const JSCallbackInfo & args)997     void Cancel(const JSCallbackInfo& args)
998     {
999         if (dataResubmitted_) {
1000             dataResubmitted_->Cancel();
1001         }
1002     }
1003 
1004 private:
Constructor(const JSCallbackInfo & args)1005     static void Constructor(const JSCallbackInfo& args)
1006     {
1007         auto jsDataResubmitted = Referenced::MakeRefPtr<JSDataResubmitted>();
1008         jsDataResubmitted->IncRefCount();
1009         args.SetReturnValue(Referenced::RawPtr(jsDataResubmitted));
1010     }
1011 
Destructor(JSDataResubmitted * jsDataResubmitted)1012     static void Destructor(JSDataResubmitted* jsDataResubmitted)
1013     {
1014         if (jsDataResubmitted != nullptr) {
1015             jsDataResubmitted->DecRefCount();
1016         }
1017     }
1018     RefPtr<DataResubmitted> dataResubmitted_;
1019 };
1020 
1021 class JSWebResourceError : public Referenced {
1022 public:
JSBind(BindingTarget globalObj)1023     static void JSBind(BindingTarget globalObj)
1024     {
1025         JSClass<JSWebResourceError>::Declare("WebResourceError");
1026         JSClass<JSWebResourceError>::CustomMethod("getErrorCode", &JSWebResourceError::GetErrorCode);
1027         JSClass<JSWebResourceError>::CustomMethod("getErrorInfo", &JSWebResourceError::GetErrorInfo);
1028         JSClass<JSWebResourceError>::Bind(globalObj, &JSWebResourceError::Constructor, &JSWebResourceError::Destructor);
1029     }
1030 
SetEvent(const ReceivedErrorEvent & eventInfo)1031     void SetEvent(const ReceivedErrorEvent& eventInfo)
1032     {
1033         error_ = eventInfo.GetError();
1034     }
1035 
GetErrorCode(const JSCallbackInfo & args)1036     void GetErrorCode(const JSCallbackInfo& args)
1037     {
1038         auto code = JSVal(ToJSValue(error_->GetCode()));
1039         auto descriptionRef = JSRef<JSVal>::Make(code);
1040         args.SetReturnValue(descriptionRef);
1041     }
1042 
GetErrorInfo(const JSCallbackInfo & args)1043     void GetErrorInfo(const JSCallbackInfo& args)
1044     {
1045         auto info = JSVal(ToJSValue(error_->GetInfo()));
1046         auto descriptionRef = JSRef<JSVal>::Make(info);
1047         args.SetReturnValue(descriptionRef);
1048     }
1049 
1050 private:
Constructor(const JSCallbackInfo & args)1051     static void Constructor(const JSCallbackInfo& args)
1052     {
1053         auto jSWebResourceError = Referenced::MakeRefPtr<JSWebResourceError>();
1054         jSWebResourceError->IncRefCount();
1055         args.SetReturnValue(Referenced::RawPtr(jSWebResourceError));
1056     }
1057 
Destructor(JSWebResourceError * jSWebResourceError)1058     static void Destructor(JSWebResourceError* jSWebResourceError)
1059     {
1060         if (jSWebResourceError != nullptr) {
1061             jSWebResourceError->DecRefCount();
1062         }
1063     }
1064 
1065     RefPtr<WebError> error_;
1066 };
1067 
1068 class JSWebResourceResponse : public Referenced {
1069 public:
JSBind(BindingTarget globalObj)1070     static void JSBind(BindingTarget globalObj)
1071     {
1072         JSClass<JSWebResourceResponse>::Declare("WebResourceResponse");
1073         JSClass<JSWebResourceResponse>::CustomMethod("getResponseData", &JSWebResourceResponse::GetResponseData);
1074         JSClass<JSWebResourceResponse>::CustomMethod("getResponseDataEx", &JSWebResourceResponse::GetResponseDataEx);
1075         JSClass<JSWebResourceResponse>::CustomMethod(
1076             "getResponseEncoding", &JSWebResourceResponse::GetResponseEncoding);
1077         JSClass<JSWebResourceResponse>::CustomMethod(
1078             "getResponseMimeType", &JSWebResourceResponse::GetResponseMimeType);
1079         JSClass<JSWebResourceResponse>::CustomMethod("getReasonMessage", &JSWebResourceResponse::GetReasonMessage);
1080         JSClass<JSWebResourceResponse>::CustomMethod("getResponseCode", &JSWebResourceResponse::GetResponseCode);
1081         JSClass<JSWebResourceResponse>::CustomMethod("getResponseHeader", &JSWebResourceResponse::GetResponseHeader);
1082         JSClass<JSWebResourceResponse>::CustomMethod("setResponseData", &JSWebResourceResponse::SetResponseData);
1083         JSClass<JSWebResourceResponse>::CustomMethod(
1084             "setResponseEncoding", &JSWebResourceResponse::SetResponseEncoding);
1085         JSClass<JSWebResourceResponse>::CustomMethod(
1086             "setResponseMimeType", &JSWebResourceResponse::SetResponseMimeType);
1087         JSClass<JSWebResourceResponse>::CustomMethod("setReasonMessage", &JSWebResourceResponse::SetReasonMessage);
1088         JSClass<JSWebResourceResponse>::CustomMethod("setResponseCode", &JSWebResourceResponse::SetResponseCode);
1089         JSClass<JSWebResourceResponse>::CustomMethod("setResponseHeader", &JSWebResourceResponse::SetResponseHeader);
1090         JSClass<JSWebResourceResponse>::CustomMethod("setResponseIsReady", &JSWebResourceResponse::SetResponseIsReady);
1091         JSClass<JSWebResourceResponse>::CustomMethod("getResponseIsReady", &JSWebResourceResponse::GetResponseIsReady);
1092         JSClass<JSWebResourceResponse>::Bind(
1093             globalObj, &JSWebResourceResponse::Constructor, &JSWebResourceResponse::Destructor);
1094     }
1095 
JSWebResourceResponse()1096     JSWebResourceResponse() : response_(AceType::MakeRefPtr<WebResponse>()) {}
1097 
SetEvent(const ReceivedHttpErrorEvent & eventInfo)1098     void SetEvent(const ReceivedHttpErrorEvent& eventInfo)
1099     {
1100         response_ = eventInfo.GetResponse();
1101     }
1102 
GetResponseData(const JSCallbackInfo & args)1103     void GetResponseData(const JSCallbackInfo& args)
1104     {
1105         auto data = JSVal(ToJSValue(response_->GetData()));
1106         auto descriptionRef = JSRef<JSVal>::Make(data);
1107         args.SetReturnValue(descriptionRef);
1108     }
1109 
GetResponseDataEx(const JSCallbackInfo & args)1110     void GetResponseDataEx(const JSCallbackInfo& args)
1111     {
1112         args.SetReturnValue(responseData_);
1113     }
1114 
GetResponseIsReady(const JSCallbackInfo & args)1115     void GetResponseIsReady(const JSCallbackInfo& args)
1116     {
1117         auto status = JSVal(ToJSValue(response_->GetResponseStatus()));
1118         auto descriptionRef = JSRef<JSVal>::Make(status);
1119         args.SetReturnValue(descriptionRef);
1120     }
1121 
GetResponseEncoding(const JSCallbackInfo & args)1122     void GetResponseEncoding(const JSCallbackInfo& args)
1123     {
1124         auto encoding = JSVal(ToJSValue(response_->GetEncoding()));
1125         auto descriptionRef = JSRef<JSVal>::Make(encoding);
1126         args.SetReturnValue(descriptionRef);
1127     }
1128 
GetResponseMimeType(const JSCallbackInfo & args)1129     void GetResponseMimeType(const JSCallbackInfo& args)
1130     {
1131         auto mimeType = JSVal(ToJSValue(response_->GetMimeType()));
1132         auto descriptionRef = JSRef<JSVal>::Make(mimeType);
1133         args.SetReturnValue(descriptionRef);
1134     }
1135 
GetReasonMessage(const JSCallbackInfo & args)1136     void GetReasonMessage(const JSCallbackInfo& args)
1137     {
1138         auto reason = JSVal(ToJSValue(response_->GetReason()));
1139         auto descriptionRef = JSRef<JSVal>::Make(reason);
1140         args.SetReturnValue(descriptionRef);
1141     }
1142 
GetResponseCode(const JSCallbackInfo & args)1143     void GetResponseCode(const JSCallbackInfo& args)
1144     {
1145         auto code = JSVal(ToJSValue(response_->GetStatusCode()));
1146         auto descriptionRef = JSRef<JSVal>::Make(code);
1147         args.SetReturnValue(descriptionRef);
1148     }
1149 
GetResponseHeader(const JSCallbackInfo & args)1150     void GetResponseHeader(const JSCallbackInfo& args)
1151     {
1152         auto map = response_->GetHeaders();
1153         std::map<std::string, std::string>::iterator iterator;
1154         uint32_t index = 0;
1155         JSRef<JSArray> headers = JSRef<JSArray>::New();
1156         for (iterator = map.begin(); iterator != map.end(); ++iterator) {
1157             JSRef<JSObject> header = JSRef<JSObject>::New();
1158             header->SetProperty("headerKey", iterator->first);
1159             header->SetProperty("headerValue", iterator->second);
1160             headers->SetValueAt(index++, header);
1161         }
1162         args.SetReturnValue(headers);
1163     }
1164 
GetResponseObj() const1165     RefPtr<WebResponse> GetResponseObj() const
1166     {
1167         return response_;
1168     }
1169 
SetResponseData(const JSCallbackInfo & args)1170     void SetResponseData(const JSCallbackInfo& args)
1171     {
1172         if (args.Length() <= 0) {
1173             return;
1174         }
1175 
1176         responseData_ = args[0];
1177         if (args[0]->IsNumber()) {
1178             auto fd = args[0]->ToNumber<int32_t>();
1179             response_->SetFileHandle(fd);
1180             return;
1181         }
1182         if (args[0]->IsString()) {
1183             auto data = args[0]->ToString();
1184             response_->SetData(data);
1185             return;
1186         }
1187         if (args[0]->IsArrayBuffer()) {
1188             JsiRef<JsiArrayBuffer> arrayBuffer = JsiRef<JsiArrayBuffer>::Cast(args[0]);
1189             int32_t bufferSize = arrayBuffer->ByteLength();
1190             void* buffer = arrayBuffer->GetBuffer();
1191             const char* charPtr = static_cast<const char*>(buffer);
1192             std::string data(charPtr, bufferSize);
1193             response_->SetData(data);
1194             response_->SetBuffer(static_cast<char*>(buffer), bufferSize);
1195             return;
1196         }
1197         if (args[0]->IsObject()) {
1198             std::string resourceUrl;
1199             std::string url;
1200             if (!JSViewAbstract::ParseJsMedia(args[0], resourceUrl)) {
1201                 return;
1202             }
1203             auto np = resourceUrl.find_first_of("/");
1204             url = (np == std::string::npos) ? resourceUrl : resourceUrl.erase(np, 1);
1205             response_->SetResourceUrl(url);
1206             return;
1207         }
1208     }
1209 
SetResponseEncoding(const JSCallbackInfo & args)1210     void SetResponseEncoding(const JSCallbackInfo& args)
1211     {
1212         if ((args.Length() <= 0) || !(args[0]->IsString())) {
1213             return;
1214         }
1215         auto encode = args[0]->ToString();
1216         response_->SetEncoding(encode);
1217     }
1218 
SetResponseMimeType(const JSCallbackInfo & args)1219     void SetResponseMimeType(const JSCallbackInfo& args)
1220     {
1221         if ((args.Length() <= 0) || !(args[0]->IsString())) {
1222             return;
1223         }
1224         auto mineType = args[0]->ToString();
1225         response_->SetMimeType(mineType);
1226     }
1227 
SetReasonMessage(const JSCallbackInfo & args)1228     void SetReasonMessage(const JSCallbackInfo& args)
1229     {
1230         if ((args.Length() <= 0) || !(args[0]->IsString())) {
1231             return;
1232         }
1233         auto reason = args[0]->ToString();
1234         response_->SetReason(reason);
1235     }
1236 
SetResponseCode(const JSCallbackInfo & args)1237     void SetResponseCode(const JSCallbackInfo& args)
1238     {
1239         if ((args.Length() <= 0) || !(args[0]->IsNumber())) {
1240             return;
1241         }
1242         auto statusCode = args[0]->ToNumber<int32_t>();
1243         response_->SetStatusCode(statusCode);
1244     }
1245 
SetResponseHeader(const JSCallbackInfo & args)1246     void SetResponseHeader(const JSCallbackInfo& args)
1247     {
1248         if ((args.Length() <= 0) || !(args[0]->IsArray())) {
1249             return;
1250         }
1251         JSRef<JSArray> array = JSRef<JSArray>::Cast(args[0]);
1252         for (size_t i = 0; i < array->Length(); i++) {
1253             if (!(array->GetValueAt(i)->IsObject())) {
1254                 return;
1255             }
1256             auto obj = JSRef<JSObject>::Cast(array->GetValueAt(i));
1257             auto headerKey = obj->GetProperty("headerKey");
1258             auto headerValue = obj->GetProperty("headerValue");
1259             if (!headerKey->IsString() || !headerValue->IsString()) {
1260                 return;
1261             }
1262             auto keystr = headerKey->ToString();
1263             auto valstr = headerValue->ToString();
1264             response_->SetHeadersVal(keystr, valstr);
1265         }
1266     }
1267 
SetResponseIsReady(const JSCallbackInfo & args)1268     void SetResponseIsReady(const JSCallbackInfo& args)
1269     {
1270         if ((args.Length() <= 0) || !(args[0]->IsBoolean())) {
1271             return;
1272         }
1273         bool isReady = false;
1274         if (!ConvertFromJSValue(args[0], isReady)) {
1275             return;
1276         }
1277         response_->SetResponseStatus(isReady);
1278     }
1279 
1280 private:
Constructor(const JSCallbackInfo & args)1281     static void Constructor(const JSCallbackInfo& args)
1282     {
1283         auto jSWebResourceResponse = Referenced::MakeRefPtr<JSWebResourceResponse>();
1284         jSWebResourceResponse->IncRefCount();
1285         args.SetReturnValue(Referenced::RawPtr(jSWebResourceResponse));
1286     }
1287 
Destructor(JSWebResourceResponse * jSWebResourceResponse)1288     static void Destructor(JSWebResourceResponse* jSWebResourceResponse)
1289     {
1290         if (jSWebResourceResponse != nullptr) {
1291             jSWebResourceResponse->DecRefCount();
1292         }
1293     }
1294 
1295     RefPtr<WebResponse> response_;
1296     JSRef<JSVal> responseData_;
1297 };
1298 
1299 class JSWebResourceRequest : public Referenced {
1300 public:
JSBind(BindingTarget globalObj)1301     static void JSBind(BindingTarget globalObj)
1302     {
1303         JSClass<JSWebResourceRequest>::Declare("WebResourceRequest");
1304         JSClass<JSWebResourceRequest>::CustomMethod("getRequestUrl", &JSWebResourceRequest::GetRequestUrl);
1305         JSClass<JSWebResourceRequest>::CustomMethod("getRequestHeader", &JSWebResourceRequest::GetRequestHeader);
1306         JSClass<JSWebResourceRequest>::CustomMethod("getRequestMethod", &JSWebResourceRequest::GetRequestMethod);
1307         JSClass<JSWebResourceRequest>::CustomMethod("isRequestGesture", &JSWebResourceRequest::IsRequestGesture);
1308         JSClass<JSWebResourceRequest>::CustomMethod("isMainFrame", &JSWebResourceRequest::IsMainFrame);
1309         JSClass<JSWebResourceRequest>::CustomMethod("isRedirect", &JSWebResourceRequest::IsRedirect);
1310         JSClass<JSWebResourceRequest>::Bind(
1311             globalObj, &JSWebResourceRequest::Constructor, &JSWebResourceRequest::Destructor);
1312     }
1313 
SetErrorEvent(const ReceivedErrorEvent & eventInfo)1314     void SetErrorEvent(const ReceivedErrorEvent& eventInfo)
1315     {
1316         request_ = eventInfo.GetRequest();
1317     }
1318 
SetHttpErrorEvent(const ReceivedHttpErrorEvent & eventInfo)1319     void SetHttpErrorEvent(const ReceivedHttpErrorEvent& eventInfo)
1320     {
1321         request_ = eventInfo.GetRequest();
1322     }
1323 
SetOnInterceptRequestEvent(const OnInterceptRequestEvent & eventInfo)1324     void SetOnInterceptRequestEvent(const OnInterceptRequestEvent& eventInfo)
1325     {
1326         request_ = eventInfo.GetRequest();
1327     }
1328 
SetLoadInterceptEvent(const LoadInterceptEvent & eventInfo)1329     void SetLoadInterceptEvent(const LoadInterceptEvent& eventInfo)
1330     {
1331         request_ = eventInfo.GetRequest();
1332     }
1333 
IsRedirect(const JSCallbackInfo & args)1334     void IsRedirect(const JSCallbackInfo& args)
1335     {
1336         auto isRedirect = JSVal(ToJSValue(request_->IsRedirect()));
1337         auto descriptionRef = JSRef<JSVal>::Make(isRedirect);
1338         args.SetReturnValue(descriptionRef);
1339     }
1340 
GetRequestUrl(const JSCallbackInfo & args)1341     void GetRequestUrl(const JSCallbackInfo& args)
1342     {
1343         auto url = JSVal(ToJSValue(request_->GetUrl()));
1344         auto descriptionRef = JSRef<JSVal>::Make(url);
1345         args.SetReturnValue(descriptionRef);
1346     }
1347 
GetRequestMethod(const JSCallbackInfo & args)1348     void GetRequestMethod(const JSCallbackInfo& args)
1349     {
1350         auto method = JSVal(ToJSValue(request_->GetMethod()));
1351         auto descriptionRef = JSRef<JSVal>::Make(method);
1352         args.SetReturnValue(descriptionRef);
1353     }
1354 
IsRequestGesture(const JSCallbackInfo & args)1355     void IsRequestGesture(const JSCallbackInfo& args)
1356     {
1357         auto isRequestGesture = JSVal(ToJSValue(request_->HasGesture()));
1358         auto descriptionRef = JSRef<JSVal>::Make(isRequestGesture);
1359         args.SetReturnValue(descriptionRef);
1360     }
1361 
IsMainFrame(const JSCallbackInfo & args)1362     void IsMainFrame(const JSCallbackInfo& args)
1363     {
1364         auto isMainFrame = JSVal(ToJSValue(request_->IsMainFrame()));
1365         auto descriptionRef = JSRef<JSVal>::Make(isMainFrame);
1366         args.SetReturnValue(descriptionRef);
1367     }
1368 
GetRequestHeader(const JSCallbackInfo & args)1369     void GetRequestHeader(const JSCallbackInfo& args)
1370     {
1371         auto map = request_->GetHeaders();
1372         std::map<std::string, std::string>::iterator iterator;
1373         uint32_t index = 0;
1374         JSRef<JSArray> headers = JSRef<JSArray>::New();
1375         for (iterator = map.begin(); iterator != map.end(); ++iterator) {
1376             JSRef<JSObject> header = JSRef<JSObject>::New();
1377             header->SetProperty("headerKey", iterator->first);
1378             header->SetProperty("headerValue", iterator->second);
1379             headers->SetValueAt(index++, header);
1380         }
1381         args.SetReturnValue(headers);
1382     }
1383 
SetLoadOverrideEvent(const LoadOverrideEvent & eventInfo)1384     void SetLoadOverrideEvent(const LoadOverrideEvent& eventInfo)
1385     {
1386         request_ = eventInfo.GetRequest();
1387     }
1388 
1389 private:
Constructor(const JSCallbackInfo & args)1390     static void Constructor(const JSCallbackInfo& args)
1391     {
1392         auto jSWebResourceRequest = Referenced::MakeRefPtr<JSWebResourceRequest>();
1393         jSWebResourceRequest->IncRefCount();
1394         args.SetReturnValue(Referenced::RawPtr(jSWebResourceRequest));
1395     }
1396 
Destructor(JSWebResourceRequest * jSWebResourceRequest)1397     static void Destructor(JSWebResourceRequest* jSWebResourceRequest)
1398     {
1399         if (jSWebResourceRequest != nullptr) {
1400             jSWebResourceRequest->DecRefCount();
1401         }
1402     }
1403 
1404     RefPtr<WebRequest> request_;
1405 };
1406 
1407 class JSFileSelectorParam : public Referenced {
1408 public:
JSBind(BindingTarget globalObj)1409     static void JSBind(BindingTarget globalObj)
1410     {
1411         JSClass<JSFileSelectorParam>::Declare("FileSelectorParam");
1412         JSClass<JSFileSelectorParam>::CustomMethod("getTitle", &JSFileSelectorParam::GetTitle);
1413         JSClass<JSFileSelectorParam>::CustomMethod("getMode", &JSFileSelectorParam::GetMode);
1414         JSClass<JSFileSelectorParam>::CustomMethod("getAcceptType", &JSFileSelectorParam::GetAcceptType);
1415         JSClass<JSFileSelectorParam>::CustomMethod("isCapture", &JSFileSelectorParam::IsCapture);
1416         JSClass<JSFileSelectorParam>::Bind(
1417             globalObj, &JSFileSelectorParam::Constructor, &JSFileSelectorParam::Destructor);
1418     }
1419 
SetParam(const FileSelectorEvent & eventInfo)1420     void SetParam(const FileSelectorEvent& eventInfo)
1421     {
1422         param_ = eventInfo.GetParam();
1423     }
1424 
GetTitle(const JSCallbackInfo & args)1425     void GetTitle(const JSCallbackInfo& args)
1426     {
1427         auto title = JSVal(ToJSValue(param_->GetTitle()));
1428         auto descriptionRef = JSRef<JSVal>::Make(title);
1429         args.SetReturnValue(descriptionRef);
1430     }
1431 
GetMode(const JSCallbackInfo & args)1432     void GetMode(const JSCallbackInfo& args)
1433     {
1434         auto mode = JSVal(ToJSValue(param_->GetMode()));
1435         auto descriptionRef = JSRef<JSVal>::Make(mode);
1436         args.SetReturnValue(descriptionRef);
1437     }
1438 
IsCapture(const JSCallbackInfo & args)1439     void IsCapture(const JSCallbackInfo& args)
1440     {
1441         auto isCapture = JSVal(ToJSValue(param_->IsCapture()));
1442         auto descriptionRef = JSRef<JSVal>::Make(isCapture);
1443         args.SetReturnValue(descriptionRef);
1444     }
1445 
GetAcceptType(const JSCallbackInfo & args)1446     void GetAcceptType(const JSCallbackInfo& args)
1447     {
1448         auto acceptTypes = param_->GetAcceptType();
1449         JSRef<JSArray> result = JSRef<JSArray>::New();
1450         std::vector<std::string>::iterator iterator;
1451         uint32_t index = 0;
1452         for (iterator = acceptTypes.begin(); iterator != acceptTypes.end(); ++iterator) {
1453             auto valueStr = JSVal(ToJSValue(*iterator));
1454             auto value = JSRef<JSVal>::Make(valueStr);
1455             result->SetValueAt(index++, value);
1456         }
1457         args.SetReturnValue(result);
1458     }
1459 
1460 private:
Constructor(const JSCallbackInfo & args)1461     static void Constructor(const JSCallbackInfo& args)
1462     {
1463         auto jSFilerSelectorParam = Referenced::MakeRefPtr<JSFileSelectorParam>();
1464         jSFilerSelectorParam->IncRefCount();
1465         args.SetReturnValue(Referenced::RawPtr(jSFilerSelectorParam));
1466     }
1467 
Destructor(JSFileSelectorParam * jSFilerSelectorParam)1468     static void Destructor(JSFileSelectorParam* jSFilerSelectorParam)
1469     {
1470         if (jSFilerSelectorParam != nullptr) {
1471             jSFilerSelectorParam->DecRefCount();
1472         }
1473     }
1474 
1475     RefPtr<WebFileSelectorParam> param_;
1476 };
1477 
1478 class JSFileSelectorResult : public Referenced {
1479 public:
JSBind(BindingTarget globalObj)1480     static void JSBind(BindingTarget globalObj)
1481     {
1482         JSClass<JSFileSelectorResult>::Declare("FileSelectorResult");
1483         JSClass<JSFileSelectorResult>::CustomMethod("handleFileList", &JSFileSelectorResult::HandleFileList);
1484         JSClass<JSFileSelectorResult>::Bind(
1485             globalObj, &JSFileSelectorResult::Constructor, &JSFileSelectorResult::Destructor);
1486     }
1487 
SetResult(const FileSelectorEvent & eventInfo)1488     void SetResult(const FileSelectorEvent& eventInfo)
1489     {
1490         result_ = eventInfo.GetFileSelectorResult();
1491     }
1492 
HandleFileList(const JSCallbackInfo & args)1493     void HandleFileList(const JSCallbackInfo& args)
1494     {
1495         std::vector<std::string> fileList;
1496         if (args[0]->IsArray()) {
1497             JSRef<JSArray> array = JSRef<JSArray>::Cast(args[0]);
1498             for (size_t i = 0; i < array->Length(); i++) {
1499                 JSRef<JSVal> val = array->GetValueAt(i);
1500                 if (!val->IsString()) {
1501                     continue;
1502                 }
1503                 std::string fileName;
1504                 if (!ConvertFromJSValue(val, fileName)) {
1505                     continue;
1506                 }
1507                 fileList.push_back(fileName);
1508             }
1509         }
1510 
1511         if (result_) {
1512             result_->HandleFileList(fileList);
1513         }
1514     }
1515 
1516 private:
Constructor(const JSCallbackInfo & args)1517     static void Constructor(const JSCallbackInfo& args)
1518     {
1519         auto jsFileSelectorResult = Referenced::MakeRefPtr<JSFileSelectorResult>();
1520         jsFileSelectorResult->IncRefCount();
1521         args.SetReturnValue(Referenced::RawPtr(jsFileSelectorResult));
1522     }
1523 
Destructor(JSFileSelectorResult * jsFileSelectorResult)1524     static void Destructor(JSFileSelectorResult* jsFileSelectorResult)
1525     {
1526         if (jsFileSelectorResult != nullptr) {
1527             jsFileSelectorResult->DecRefCount();
1528         }
1529     }
1530 
1531     RefPtr<FileSelectorResult> result_;
1532 };
1533 
1534 class JSContextMenuParam : public Referenced {
1535 public:
JSBind(BindingTarget globalObj)1536     static void JSBind(BindingTarget globalObj)
1537     {
1538         JSClass<JSContextMenuParam>::Declare("WebContextMenuParam");
1539         JSClass<JSContextMenuParam>::CustomMethod("x", &JSContextMenuParam::GetXCoord);
1540         JSClass<JSContextMenuParam>::CustomMethod("y", &JSContextMenuParam::GetYCoord);
1541         JSClass<JSContextMenuParam>::CustomMethod("getLinkUrl", &JSContextMenuParam::GetLinkUrl);
1542         JSClass<JSContextMenuParam>::CustomMethod("getUnfilteredLinkUrl", &JSContextMenuParam::GetUnfilteredLinkUrl);
1543         JSClass<JSContextMenuParam>::CustomMethod("getSourceUrl", &JSContextMenuParam::GetSourceUrl);
1544         JSClass<JSContextMenuParam>::CustomMethod("existsImageContents", &JSContextMenuParam::HasImageContents);
1545         JSClass<JSContextMenuParam>::CustomMethod("getSelectionText", &JSContextMenuParam::GetSelectionText);
1546         JSClass<JSContextMenuParam>::CustomMethod("isEditable", &JSContextMenuParam::IsEditable);
1547         JSClass<JSContextMenuParam>::CustomMethod("getEditStateFlags", &JSContextMenuParam::GetEditStateFlags);
1548         JSClass<JSContextMenuParam>::CustomMethod("getSourceType", &JSContextMenuParam::GetSourceType);
1549         JSClass<JSContextMenuParam>::CustomMethod("getInputFieldType", &JSContextMenuParam::GetInputFieldType);
1550         JSClass<JSContextMenuParam>::CustomMethod("getMediaType", &JSContextMenuParam::GetMediaType);
1551         JSClass<JSContextMenuParam>::CustomMethod("getPreviewWidth", &JSContextMenuParam::GetPreviewWidth);
1552         JSClass<JSContextMenuParam>::CustomMethod("getPreviewHeight", &JSContextMenuParam::GetPreviewHeight);
1553         JSClass<JSContextMenuParam>::Bind(globalObj, &JSContextMenuParam::Constructor, &JSContextMenuParam::Destructor);
1554     }
1555 
UpdatePreviewSize()1556     void UpdatePreviewSize()
1557     {
1558         if (previewWidth_ >= 0 && previewHeight_ >= 0) {
1559             return;
1560         }
1561         if (param_) {
1562             int32_t x = 0;
1563             int32_t y = 0;
1564             param_->GetImageRect(x, y, previewWidth_, previewHeight_);
1565         }
1566     }
1567 
GetPreviewWidth(const JSCallbackInfo & args)1568     void GetPreviewWidth(const JSCallbackInfo& args)
1569     {
1570         auto ret = JSVal(ToJSValue(previewWidth_));
1571         auto descriptionRef = JSRef<JSVal>::Make(ret);
1572         args.SetReturnValue(descriptionRef);
1573     }
1574 
GetPreviewHeight(const JSCallbackInfo & args)1575     void GetPreviewHeight(const JSCallbackInfo& args)
1576     {
1577         auto ret = JSVal(ToJSValue(previewHeight_));
1578         auto descriptionRef = JSRef<JSVal>::Make(ret);
1579         args.SetReturnValue(descriptionRef);
1580     }
1581 
SetParam(const ContextMenuEvent & eventInfo)1582     void SetParam(const ContextMenuEvent& eventInfo)
1583     {
1584         param_ = eventInfo.GetParam();
1585         UpdatePreviewSize();
1586     }
1587 
GetXCoord(const JSCallbackInfo & args)1588     void GetXCoord(const JSCallbackInfo& args)
1589     {
1590         int32_t ret = -1;
1591         if (param_) {
1592             ret = param_->GetXCoord();
1593         }
1594         auto xCoord = JSVal(ToJSValue(ret));
1595         auto descriptionRef = JSRef<JSVal>::Make(xCoord);
1596         args.SetReturnValue(descriptionRef);
1597     }
1598 
GetYCoord(const JSCallbackInfo & args)1599     void GetYCoord(const JSCallbackInfo& args)
1600     {
1601         int32_t ret = -1;
1602         if (param_) {
1603             ret = param_->GetYCoord();
1604         }
1605         auto yCoord = JSVal(ToJSValue(ret));
1606         auto descriptionRef = JSRef<JSVal>::Make(yCoord);
1607         args.SetReturnValue(descriptionRef);
1608     }
1609 
GetLinkUrl(const JSCallbackInfo & args)1610     void GetLinkUrl(const JSCallbackInfo& args)
1611     {
1612         std::string url;
1613         if (param_) {
1614             url = param_->GetLinkUrl();
1615         }
1616         auto linkUrl = JSVal(ToJSValue(url));
1617         auto descriptionRef = JSRef<JSVal>::Make(linkUrl);
1618         args.SetReturnValue(descriptionRef);
1619     }
1620 
GetUnfilteredLinkUrl(const JSCallbackInfo & args)1621     void GetUnfilteredLinkUrl(const JSCallbackInfo& args)
1622     {
1623         std::string url;
1624         if (param_) {
1625             url = param_->GetUnfilteredLinkUrl();
1626         }
1627         auto unfilteredLinkUrl = JSVal(ToJSValue(url));
1628         auto descriptionRef = JSRef<JSVal>::Make(unfilteredLinkUrl);
1629         args.SetReturnValue(descriptionRef);
1630     }
1631 
GetSourceUrl(const JSCallbackInfo & args)1632     void GetSourceUrl(const JSCallbackInfo& args)
1633     {
1634         std::string url;
1635         if (param_) {
1636             url = param_->GetSourceUrl();
1637         }
1638         auto sourceUrl = JSVal(ToJSValue(url));
1639         auto descriptionRef = JSRef<JSVal>::Make(sourceUrl);
1640         args.SetReturnValue(descriptionRef);
1641     }
1642 
HasImageContents(const JSCallbackInfo & args)1643     void HasImageContents(const JSCallbackInfo& args)
1644     {
1645         bool ret = false;
1646         if (param_) {
1647             ret = param_->HasImageContents();
1648         }
1649         auto hasImageContents = JSVal(ToJSValue(ret));
1650         auto descriptionRef = JSRef<JSVal>::Make(hasImageContents);
1651         args.SetReturnValue(descriptionRef);
1652     }
1653 
GetSelectionText(const JSCallbackInfo & args)1654     void GetSelectionText(const JSCallbackInfo& args)
1655     {
1656         std::string text;
1657         if (param_) {
1658             text = param_->GetSelectionText();
1659         }
1660         auto jsText = JSVal(ToJSValue(text));
1661         auto descriptionRef = JSRef<JSVal>::Make(jsText);
1662         args.SetReturnValue(descriptionRef);
1663     }
1664 
IsEditable(const JSCallbackInfo & args)1665     void IsEditable(const JSCallbackInfo& args)
1666     {
1667         bool flag = false;
1668         if (param_) {
1669             flag = param_->IsEditable();
1670         }
1671         auto jsFlag = JSVal(ToJSValue(flag));
1672         auto descriptionRef = JSRef<JSVal>::Make(jsFlag);
1673         args.SetReturnValue(descriptionRef);
1674     }
1675 
GetEditStateFlags(const JSCallbackInfo & args)1676     void GetEditStateFlags(const JSCallbackInfo& args)
1677     {
1678         int32_t flags = 0;
1679         if (param_) {
1680             flags = param_->GetEditStateFlags();
1681         }
1682         auto jsFlags = JSVal(ToJSValue(flags));
1683         auto descriptionRef = JSRef<JSVal>::Make(jsFlags);
1684         args.SetReturnValue(descriptionRef);
1685     }
1686 
GetSourceType(const JSCallbackInfo & args)1687     void GetSourceType(const JSCallbackInfo& args)
1688     {
1689         int32_t type = 0;
1690         if (param_) {
1691             type = param_->GetSourceType();
1692         }
1693         auto jsType = JSVal(ToJSValue(type));
1694         auto descriptionRef = JSRef<JSVal>::Make(jsType);
1695         args.SetReturnValue(descriptionRef);
1696     }
1697 
GetInputFieldType(const JSCallbackInfo & args)1698     void GetInputFieldType(const JSCallbackInfo& args)
1699     {
1700         int32_t type = 0;
1701         if (param_) {
1702             type = param_->GetInputFieldType();
1703         }
1704         auto jsType = JSVal(ToJSValue(type));
1705         auto descriptionRef = JSRef<JSVal>::Make(jsType);
1706         args.SetReturnValue(descriptionRef);
1707     }
1708 
GetMediaType(const JSCallbackInfo & args)1709     void GetMediaType(const JSCallbackInfo& args)
1710     {
1711         int32_t type = 0;
1712         if (param_) {
1713             type = param_->GetMediaType();
1714         }
1715         auto jsType = JSVal(ToJSValue(type));
1716         auto descriptionRef = JSRef<JSVal>::Make(jsType);
1717         args.SetReturnValue(descriptionRef);
1718     }
1719 
1720 private:
Constructor(const JSCallbackInfo & args)1721     static void Constructor(const JSCallbackInfo& args)
1722     {
1723         auto jSContextMenuParam = Referenced::MakeRefPtr<JSContextMenuParam>();
1724         jSContextMenuParam->IncRefCount();
1725         args.SetReturnValue(Referenced::RawPtr(jSContextMenuParam));
1726     }
1727 
Destructor(JSContextMenuParam * jSContextMenuParam)1728     static void Destructor(JSContextMenuParam* jSContextMenuParam)
1729     {
1730         if (jSContextMenuParam != nullptr) {
1731             jSContextMenuParam->DecRefCount();
1732         }
1733     }
1734 
1735     RefPtr<WebContextMenuParam> param_;
1736 
1737     int32_t previewWidth_ = -1;
1738 
1739     int32_t previewHeight_ = -1;
1740 };
1741 
1742 class JSContextMenuResult : public Referenced {
1743 public:
JSBind(BindingTarget globalObj)1744     static void JSBind(BindingTarget globalObj)
1745     {
1746         JSClass<JSContextMenuResult>::Declare("WebContextMenuResult");
1747         JSClass<JSContextMenuResult>::CustomMethod("closeContextMenu", &JSContextMenuResult::Cancel);
1748         JSClass<JSContextMenuResult>::CustomMethod("copyImage", &JSContextMenuResult::CopyImage);
1749         JSClass<JSContextMenuResult>::CustomMethod("copy", &JSContextMenuResult::Copy);
1750         JSClass<JSContextMenuResult>::CustomMethod("paste", &JSContextMenuResult::Paste);
1751         JSClass<JSContextMenuResult>::CustomMethod("cut", &JSContextMenuResult::Cut);
1752         JSClass<JSContextMenuResult>::CustomMethod("selectAll", &JSContextMenuResult::SelectAll);
1753         JSClass<JSContextMenuResult>::Bind(
1754             globalObj, &JSContextMenuResult::Constructor, &JSContextMenuResult::Destructor);
1755     }
1756 
SetResult(const ContextMenuEvent & eventInfo)1757     void SetResult(const ContextMenuEvent& eventInfo)
1758     {
1759         result_ = eventInfo.GetContextMenuResult();
1760     }
1761 
Cancel(const JSCallbackInfo & args)1762     void Cancel(const JSCallbackInfo& args)
1763     {
1764         if (result_) {
1765             result_->Cancel();
1766         }
1767     }
1768 
CopyImage(const JSCallbackInfo & args)1769     void CopyImage(const JSCallbackInfo& args)
1770     {
1771         if (result_) {
1772             result_->CopyImage();
1773         }
1774     }
1775 
Copy(const JSCallbackInfo & args)1776     void Copy(const JSCallbackInfo& args)
1777     {
1778         if (result_) {
1779             result_->Copy();
1780         }
1781     }
1782 
Paste(const JSCallbackInfo & args)1783     void Paste(const JSCallbackInfo& args)
1784     {
1785         if (result_) {
1786             result_->Paste();
1787         }
1788     }
1789 
Cut(const JSCallbackInfo & args)1790     void Cut(const JSCallbackInfo& args)
1791     {
1792         if (result_) {
1793             result_->Cut();
1794         }
1795     }
1796 
SelectAll(const JSCallbackInfo & args)1797     void SelectAll(const JSCallbackInfo& args)
1798     {
1799         if (result_) {
1800             result_->SelectAll();
1801         }
1802     }
1803 
1804 private:
Constructor(const JSCallbackInfo & args)1805     static void Constructor(const JSCallbackInfo& args)
1806     {
1807         auto jsContextMenuResult = Referenced::MakeRefPtr<JSContextMenuResult>();
1808         jsContextMenuResult->IncRefCount();
1809         args.SetReturnValue(Referenced::RawPtr(jsContextMenuResult));
1810     }
1811 
Destructor(JSContextMenuResult * jsContextMenuResult)1812     static void Destructor(JSContextMenuResult* jsContextMenuResult)
1813     {
1814         if (jsContextMenuResult != nullptr) {
1815             jsContextMenuResult->DecRefCount();
1816         }
1817     }
1818 
1819     RefPtr<ContextMenuResult> result_;
1820 };
1821 
1822 class JSWebAppLinkCallback : public Referenced {
1823 public:
JSBind(BindingTarget globalObj)1824     static void JSBind(BindingTarget globalObj)
1825     {
1826         JSClass<JSWebAppLinkCallback>::Declare("WebAppLinkCallback");
1827         JSClass<JSWebAppLinkCallback>::CustomMethod("continueLoad", &JSWebAppLinkCallback::ContinueLoad);
1828         JSClass<JSWebAppLinkCallback>::CustomMethod("cancelLoad", &JSWebAppLinkCallback::CancelLoad);
1829         JSClass<JSWebAppLinkCallback>::Bind(
1830             globalObj, &JSWebAppLinkCallback::Constructor, &JSWebAppLinkCallback::Destructor);
1831     }
1832 
SetEvent(const WebAppLinkEvent & eventInfo)1833     void SetEvent(const WebAppLinkEvent& eventInfo)
1834     {
1835         callback_ = eventInfo.GetCallback();
1836     }
1837 
ContinueLoad(const JSCallbackInfo & args)1838     void ContinueLoad(const JSCallbackInfo& args)
1839     {
1840         if (callback_) {
1841             callback_->ContinueLoad();
1842         }
1843     }
1844 
CancelLoad(const JSCallbackInfo & args)1845     void CancelLoad(const JSCallbackInfo& args)
1846     {
1847         if (callback_) {
1848             callback_->CancelLoad();
1849         }
1850     }
1851 
1852 private:
Constructor(const JSCallbackInfo & args)1853     static void Constructor(const JSCallbackInfo& args)
1854     {
1855         auto jsWebAppLinkCallback = Referenced::MakeRefPtr<JSWebAppLinkCallback>();
1856         jsWebAppLinkCallback->IncRefCount();
1857         args.SetReturnValue(Referenced::RawPtr(jsWebAppLinkCallback));
1858     }
1859 
Destructor(JSWebAppLinkCallback * jsWebAppLinkCallback)1860     static void Destructor(JSWebAppLinkCallback* jsWebAppLinkCallback)
1861     {
1862         if (jsWebAppLinkCallback != nullptr) {
1863             jsWebAppLinkCallback->DecRefCount();
1864         }
1865     }
1866 
1867     RefPtr<WebAppLinkCallback> callback_;
1868 };
1869 
JSBind(BindingTarget globalObj)1870 void JSWeb::JSBind(BindingTarget globalObj)
1871 {
1872     JSClass<JSWeb>::Declare("Web");
1873     JSClass<JSWeb>::StaticMethod("create", &JSWeb::Create);
1874     JSClass<JSWeb>::StaticMethod("onAlert", &JSWeb::OnAlert);
1875     JSClass<JSWeb>::StaticMethod("onBeforeUnload", &JSWeb::OnBeforeUnload);
1876     JSClass<JSWeb>::StaticMethod("onConfirm", &JSWeb::OnConfirm);
1877     JSClass<JSWeb>::StaticMethod("onPrompt", &JSWeb::OnPrompt);
1878     JSClass<JSWeb>::StaticMethod("onConsole", &JSWeb::OnConsoleLog);
1879     JSClass<JSWeb>::StaticMethod("onFullScreenEnter", &JSWeb::OnFullScreenEnter);
1880     JSClass<JSWeb>::StaticMethod("onFullScreenExit", &JSWeb::OnFullScreenExit);
1881     JSClass<JSWeb>::StaticMethod("onPageBegin", &JSWeb::OnPageStart);
1882     JSClass<JSWeb>::StaticMethod("onPageEnd", &JSWeb::OnPageFinish);
1883     JSClass<JSWeb>::StaticMethod("onProgressChange", &JSWeb::OnProgressChange);
1884     JSClass<JSWeb>::StaticMethod("onTitleReceive", &JSWeb::OnTitleReceive);
1885     JSClass<JSWeb>::StaticMethod("onGeolocationHide", &JSWeb::OnGeolocationHide);
1886     JSClass<JSWeb>::StaticMethod("onGeolocationShow", &JSWeb::OnGeolocationShow);
1887     JSClass<JSWeb>::StaticMethod("onRequestSelected", &JSWeb::OnRequestFocus);
1888     JSClass<JSWeb>::StaticMethod("onShowFileSelector", &JSWeb::OnFileSelectorShow);
1889     JSClass<JSWeb>::StaticMethod("javaScriptAccess", &JSWeb::JsEnabled);
1890     JSClass<JSWeb>::StaticMethod("fileExtendAccess", &JSWeb::ContentAccessEnabled);
1891     JSClass<JSWeb>::StaticMethod("fileAccess", &JSWeb::FileAccessEnabled);
1892     JSClass<JSWeb>::StaticMethod("onDownloadStart", &JSWeb::OnDownloadStart);
1893     JSClass<JSWeb>::StaticMethod("onErrorReceive", &JSWeb::OnErrorReceive);
1894     JSClass<JSWeb>::StaticMethod("onHttpErrorReceive", &JSWeb::OnHttpErrorReceive);
1895     JSClass<JSWeb>::StaticMethod("onInterceptRequest", &JSWeb::OnInterceptRequest);
1896     JSClass<JSWeb>::StaticMethod("onUrlLoadIntercept", &JSWeb::OnUrlLoadIntercept);
1897     JSClass<JSWeb>::StaticMethod("onLoadIntercept", &JSWeb::OnLoadIntercept);
1898     JSClass<JSWeb>::StaticMethod("onlineImageAccess", &JSWeb::OnLineImageAccessEnabled);
1899     JSClass<JSWeb>::StaticMethod("domStorageAccess", &JSWeb::DomStorageAccessEnabled);
1900     JSClass<JSWeb>::StaticMethod("imageAccess", &JSWeb::ImageAccessEnabled);
1901     JSClass<JSWeb>::StaticMethod("mixedMode", &JSWeb::MixedMode);
1902     JSClass<JSWeb>::StaticMethod("enableNativeEmbedMode", &JSWeb::EnableNativeEmbedMode);
1903     JSClass<JSWeb>::StaticMethod("registerNativeEmbedRule", &JSWeb::RegisterNativeEmbedRule);
1904     JSClass<JSWeb>::StaticMethod("zoomAccess", &JSWeb::ZoomAccessEnabled);
1905     JSClass<JSWeb>::StaticMethod("geolocationAccess", &JSWeb::GeolocationAccessEnabled);
1906     JSClass<JSWeb>::StaticMethod("javaScriptProxy", &JSWeb::JavaScriptProxy);
1907     JSClass<JSWeb>::StaticMethod("userAgent", &JSWeb::UserAgent);
1908     JSClass<JSWeb>::StaticMethod("onRenderExited", &JSWeb::OnRenderExited);
1909     JSClass<JSWeb>::StaticMethod("onRefreshAccessedHistory", &JSWeb::OnRefreshAccessedHistory);
1910     JSClass<JSWeb>::StaticMethod("cacheMode", &JSWeb::CacheMode);
1911     JSClass<JSWeb>::StaticMethod("overviewModeAccess", &JSWeb::OverviewModeAccess);
1912     JSClass<JSWeb>::StaticMethod("webDebuggingAccess", &JSWeb::WebDebuggingAccess);
1913     JSClass<JSWeb>::StaticMethod("wideViewModeAccess", &JSWeb::WideViewModeAccess);
1914     JSClass<JSWeb>::StaticMethod("fileFromUrlAccess", &JSWeb::FileFromUrlAccess);
1915     JSClass<JSWeb>::StaticMethod("databaseAccess", &JSWeb::DatabaseAccess);
1916     JSClass<JSWeb>::StaticMethod("textZoomRatio", &JSWeb::TextZoomRatio);
1917     JSClass<JSWeb>::StaticMethod("textZoomAtio", &JSWeb::TextZoomRatio);
1918     JSClass<JSWeb>::StaticMethod("initialScale", &JSWeb::InitialScale);
1919     JSClass<JSWeb>::StaticMethod("backgroundColor", &JSWeb::BackgroundColor);
1920     JSClass<JSWeb>::StaticMethod("onKeyEvent", &JSWeb::OnKeyEvent);
1921     JSClass<JSWeb>::StaticMethod("onTouch", &JSInteractableView::JsOnTouch);
1922     JSClass<JSWeb>::StaticMethod("onMouse", &JSWeb::OnMouse);
1923     JSClass<JSWeb>::StaticMethod("onResourceLoad", &JSWeb::OnResourceLoad);
1924     JSClass<JSWeb>::StaticMethod("onScaleChange", &JSWeb::OnScaleChange);
1925     JSClass<JSWeb>::StaticMethod("password", &JSWeb::Password);
1926     JSClass<JSWeb>::StaticMethod("tableData", &JSWeb::TableData);
1927     JSClass<JSWeb>::StaticMethod("onFileSelectorShow", &JSWeb::OnFileSelectorShowAbandoned);
1928     JSClass<JSWeb>::StaticMethod("onHttpAuthRequest", &JSWeb::OnHttpAuthRequest);
1929     JSClass<JSWeb>::StaticMethod("onSslErrorReceive", &JSWeb::OnSslErrRequest);
1930     JSClass<JSWeb>::StaticMethod("onSslErrorEventReceive", &JSWeb::OnSslErrorRequest);
1931     JSClass<JSWeb>::StaticMethod("onSslErrorEvent", &JSWeb::OnAllSslErrorRequest);
1932     JSClass<JSWeb>::StaticMethod("onClientAuthenticationRequest", &JSWeb::OnSslSelectCertRequest);
1933     JSClass<JSWeb>::StaticMethod("onPermissionRequest", &JSWeb::OnPermissionRequest);
1934     JSClass<JSWeb>::StaticMethod("onContextMenuShow", &JSWeb::OnContextMenuShow);
1935     JSClass<JSWeb>::StaticMethod("onContextMenuHide", &JSWeb::OnContextMenuHide);
1936     JSClass<JSWeb>::StaticMethod("onSearchResultReceive", &JSWeb::OnSearchResultReceive);
1937     JSClass<JSWeb>::StaticMethod("mediaPlayGestureAccess", &JSWeb::MediaPlayGestureAccess);
1938     JSClass<JSWeb>::StaticMethod("onDragStart", &JSWeb::JsOnDragStart);
1939     JSClass<JSWeb>::StaticMethod("onDragEnter", &JSWeb::JsOnDragEnter);
1940     JSClass<JSWeb>::StaticMethod("onDragMove", &JSWeb::JsOnDragMove);
1941     JSClass<JSWeb>::StaticMethod("onDragLeave", &JSWeb::JsOnDragLeave);
1942     JSClass<JSWeb>::StaticMethod("onDrop", &JSWeb::JsOnDrop);
1943     JSClass<JSWeb>::StaticMethod("onScroll", &JSWeb::OnScroll);
1944     JSClass<JSWeb>::StaticMethod("rotate", &JSWeb::WebRotate);
1945     JSClass<JSWeb>::StaticMethod("pinchSmooth", &JSWeb::PinchSmoothModeEnabled);
1946     JSClass<JSWeb>::StaticMethod("onAttach", &JSInteractableView::JsOnAttach);
1947     JSClass<JSWeb>::StaticMethod("onAppear", &JSInteractableView::JsOnAppear);
1948     JSClass<JSWeb>::StaticMethod("onDetach", &JSInteractableView::JsOnDetach);
1949     JSClass<JSWeb>::StaticMethod("onDisAppear", &JSInteractableView::JsOnDisAppear);
1950     JSClass<JSWeb>::StaticMethod("onWindowNew", &JSWeb::OnWindowNew);
1951     JSClass<JSWeb>::StaticMethod("onWindowExit", &JSWeb::OnWindowExit);
1952     JSClass<JSWeb>::StaticMethod("multiWindowAccess", &JSWeb::MultiWindowAccessEnabled);
1953     JSClass<JSWeb>::StaticMethod("allowWindowOpenMethod", &JSWeb::AllowWindowOpenMethod);
1954     JSClass<JSWeb>::StaticMethod("webCursiveFont", &JSWeb::WebCursiveFont);
1955     JSClass<JSWeb>::StaticMethod("webFantasyFont", &JSWeb::WebFantasyFont);
1956     JSClass<JSWeb>::StaticMethod("webFixedFont", &JSWeb::WebFixedFont);
1957     JSClass<JSWeb>::StaticMethod("webSansSerifFont", &JSWeb::WebSansSerifFont);
1958     JSClass<JSWeb>::StaticMethod("webSerifFont", &JSWeb::WebSerifFont);
1959     JSClass<JSWeb>::StaticMethod("webStandardFont", &JSWeb::WebStandardFont);
1960     JSClass<JSWeb>::StaticMethod("defaultFixedFontSize", &JSWeb::DefaultFixedFontSize);
1961     JSClass<JSWeb>::StaticMethod("defaultFontSize", &JSWeb::DefaultFontSize);
1962     JSClass<JSWeb>::StaticMethod("defaultTextEncodingFormat", &JSWeb::DefaultTextEncodingFormat);
1963     JSClass<JSWeb>::StaticMethod("minFontSize", &JSWeb::MinFontSize);
1964     JSClass<JSWeb>::StaticMethod("minLogicalFontSize", &JSWeb::MinLogicalFontSize);
1965     JSClass<JSWeb>::StaticMethod("blockNetwork", &JSWeb::BlockNetwork);
1966     JSClass<JSWeb>::StaticMethod("onPageVisible", &JSWeb::OnPageVisible);
1967     JSClass<JSWeb>::StaticMethod("onInterceptKeyEvent", &JSWeb::OnInterceptKeyEvent);
1968     JSClass<JSWeb>::StaticMethod("onDataResubmitted", &JSWeb::OnDataResubmitted);
1969     JSClass<JSWeb>::StaticMethod("onFaviconReceived", &JSWeb::OnFaviconReceived);
1970     JSClass<JSWeb>::StaticMethod("onTouchIconUrlReceived", &JSWeb::OnTouchIconUrlReceived);
1971     JSClass<JSWeb>::StaticMethod("darkMode", &JSWeb::DarkMode);
1972     JSClass<JSWeb>::StaticMethod("forceDarkAccess", &JSWeb::ForceDarkAccess);
1973     JSClass<JSWeb>::StaticMethod("overScrollMode", &JSWeb::OverScrollMode);
1974     JSClass<JSWeb>::StaticMethod("blurOnKeyboardHideMode", &JSWeb::BlurOnKeyboardHideMode);
1975     JSClass<JSWeb>::StaticMethod("horizontalScrollBarAccess", &JSWeb::HorizontalScrollBarAccess);
1976     JSClass<JSWeb>::StaticMethod("verticalScrollBarAccess", &JSWeb::VerticalScrollBarAccess);
1977     JSClass<JSWeb>::StaticMethod("onAudioStateChanged", &JSWeb::OnAudioStateChanged);
1978     JSClass<JSWeb>::StaticMethod("mediaOptions", &JSWeb::MediaOptions);
1979     JSClass<JSWeb>::StaticMethod("onFirstContentfulPaint", &JSWeb::OnFirstContentfulPaint);
1980     JSClass<JSWeb>::StaticMethod("onFirstMeaningfulPaint", &JSWeb::OnFirstMeaningfulPaint);
1981     JSClass<JSWeb>::StaticMethod("onLargestContentfulPaint", &JSWeb::OnLargestContentfulPaint);
1982     JSClass<JSWeb>::StaticMethod("onSafeBrowsingCheckResult", &JSWeb::OnSafeBrowsingCheckResult);
1983     JSClass<JSWeb>::StaticMethod("onNavigationEntryCommitted", &JSWeb::OnNavigationEntryCommitted);
1984     JSClass<JSWeb>::StaticMethod("onIntelligentTrackingPreventionResult",
1985         &JSWeb::OnIntelligentTrackingPreventionResult);
1986     JSClass<JSWeb>::StaticMethod("onControllerAttached", &JSWeb::OnControllerAttached);
1987     JSClass<JSWeb>::StaticMethod("onOverScroll", &JSWeb::OnOverScroll);
1988     JSClass<JSWeb>::StaticMethod("onNativeEmbedLifecycleChange", &JSWeb::OnNativeEmbedLifecycleChange);
1989     JSClass<JSWeb>::StaticMethod("onNativeEmbedVisibilityChange", &JSWeb::OnNativeEmbedVisibilityChange);
1990     JSClass<JSWeb>::StaticMethod("onNativeEmbedGestureEvent", &JSWeb::OnNativeEmbedGestureEvent);
1991     JSClass<JSWeb>::StaticMethod("copyOptions", &JSWeb::CopyOption);
1992     JSClass<JSWeb>::StaticMethod("onScreenCaptureRequest", &JSWeb::OnScreenCaptureRequest);
1993     JSClass<JSWeb>::StaticMethod("layoutMode", &JSWeb::SetLayoutMode);
1994     JSClass<JSWeb>::StaticMethod("nestedScroll", &JSWeb::SetNestedScroll);
1995     JSClass<JSWeb>::StaticMethod("metaViewport", &JSWeb::SetMetaViewport);
1996     JSClass<JSWeb>::StaticMethod("javaScriptOnDocumentStart", &JSWeb::JavaScriptOnDocumentStart);
1997     JSClass<JSWeb>::StaticMethod("javaScriptOnDocumentEnd", &JSWeb::JavaScriptOnDocumentEnd);
1998     JSClass<JSWeb>::StaticMethod("onOverrideUrlLoading", &JSWeb::OnOverrideUrlLoading);
1999     JSClass<JSWeb>::StaticMethod("textAutosizing", &JSWeb::TextAutosizing);
2000     JSClass<JSWeb>::StaticMethod("enableNativeMediaPlayer", &JSWeb::EnableNativeVideoPlayer);
2001     JSClass<JSWeb>::StaticMethod("onRenderProcessNotResponding", &JSWeb::OnRenderProcessNotResponding);
2002     JSClass<JSWeb>::StaticMethod("onRenderProcessResponding", &JSWeb::OnRenderProcessResponding);
2003     JSClass<JSWeb>::StaticMethod("onViewportFitChanged", &JSWeb::OnViewportFitChanged);
2004     JSClass<JSWeb>::StaticMethod("selectionMenuOptions", &JSWeb::SelectionMenuOptions);
2005     JSClass<JSWeb>::StaticMethod("onAdsBlocked", &JSWeb::OnAdsBlocked);
2006     JSClass<JSWeb>::StaticMethod("onInterceptKeyboardAttach", &JSWeb::OnInterceptKeyboardAttach);
2007     JSClass<JSWeb>::StaticMethod("forceDisplayScrollBar", &JSWeb::ForceDisplayScrollBar);
2008     JSClass<JSWeb>::StaticMethod("keyboardAvoidMode", &JSWeb::KeyboardAvoidMode);
2009     JSClass<JSWeb>::StaticMethod("editMenuOptions", &JSWeb::EditMenuOptions);
2010     JSClass<JSWeb>::StaticMethod("enableHapticFeedback", &JSWeb::EnableHapticFeedback);
2011     JSClass<JSWeb>::StaticMethod("bindSelectionMenu", &JSWeb::BindSelectionMenu);
2012     JSClass<JSWeb>::StaticMethod("optimizeParserBudget", &JSWeb::OptimizeParserBudgetEnabled);
2013     JSClass<JSWeb>::StaticMethod("runJavaScriptOnHeadEnd", &JSWeb::RunJavaScriptOnHeadEnd);
2014     JSClass<JSWeb>::StaticMethod("runJavaScriptOnDocumentStart", &JSWeb::RunJavaScriptOnDocumentStart);
2015     JSClass<JSWeb>::StaticMethod("runJavaScriptOnDocumentEnd", &JSWeb::RunJavaScriptOnDocumentEnd);
2016 
2017     JSClass<JSWeb>::InheritAndBind<JSViewAbstract>(globalObj);
2018     JSWebDialog::JSBind(globalObj);
2019     JSWebGeolocation::JSBind(globalObj);
2020     JSWebResourceRequest::JSBind(globalObj);
2021     JSWebResourceError::JSBind(globalObj);
2022     JSWebResourceResponse::JSBind(globalObj);
2023     JSWebConsoleLog::JSBind(globalObj);
2024     JSFileSelectorParam::JSBind(globalObj);
2025     JSFileSelectorResult::JSBind(globalObj);
2026     JSFullScreenExitHandler::JSBind(globalObj);
2027     JSWebHttpAuth::JSBind(globalObj);
2028     JSWebSslError::JSBind(globalObj);
2029     JSWebAllSslError::JSBind(globalObj);
2030     JSWebSslSelectCert::JSBind(globalObj);
2031     JSWebPermissionRequest::JSBind(globalObj);
2032     JSContextMenuParam::JSBind(globalObj);
2033     JSContextMenuResult::JSBind(globalObj);
2034     JSWebWindowNewHandler::JSBind(globalObj);
2035     JSDataResubmitted::JSBind(globalObj);
2036     JSScreenCaptureRequest::JSBind(globalObj);
2037     JSNativeEmbedGestureRequest::JSBind(globalObj);
2038     JSWebAppLinkCallback::JSBind(globalObj);
2039     JSWebKeyboardController::JSBind(globalObj);
2040 }
2041 
LoadWebConsoleLogEventToJSValue(const LoadWebConsoleLogEvent & eventInfo)2042 JSRef<JSVal> LoadWebConsoleLogEventToJSValue(const LoadWebConsoleLogEvent& eventInfo)
2043 {
2044     JSRef<JSObject> obj = JSRef<JSObject>::New();
2045 
2046     JSRef<JSObject> messageObj = JSClass<JSWebConsoleLog>::NewInstance();
2047     auto jsWebConsoleLog = Referenced::Claim(messageObj->Unwrap<JSWebConsoleLog>());
2048     jsWebConsoleLog->SetMessage(eventInfo.GetMessage());
2049 
2050     obj->SetPropertyObject("message", messageObj);
2051 
2052     return JSRef<JSVal>::Cast(obj);
2053 }
2054 
WebDialogEventToJSValue(const WebDialogEvent & eventInfo)2055 JSRef<JSVal> WebDialogEventToJSValue(const WebDialogEvent& eventInfo)
2056 {
2057     JSRef<JSObject> obj = JSRef<JSObject>::New();
2058 
2059     JSRef<JSObject> resultObj = JSClass<JSWebDialog>::NewInstance();
2060     auto jsWebDialog = Referenced::Claim(resultObj->Unwrap<JSWebDialog>());
2061     jsWebDialog->SetResult(eventInfo.GetResult());
2062 
2063     obj->SetProperty("url", eventInfo.GetUrl());
2064     obj->SetProperty("message", eventInfo.GetMessage());
2065     if (eventInfo.GetType() == DialogEventType::DIALOG_EVENT_PROMPT) {
2066         obj->SetProperty("value", eventInfo.GetValue());
2067     }
2068     obj->SetPropertyObject("result", resultObj);
2069 
2070     return JSRef<JSVal>::Cast(obj);
2071 }
2072 
LoadWebPageFinishEventToJSValue(const LoadWebPageFinishEvent & eventInfo)2073 JSRef<JSVal> LoadWebPageFinishEventToJSValue(const LoadWebPageFinishEvent& eventInfo)
2074 {
2075     JSRef<JSObject> obj = JSRef<JSObject>::New();
2076     obj->SetProperty("url", eventInfo.GetLoadedUrl());
2077     return JSRef<JSVal>::Cast(obj);
2078 }
2079 
ContextMenuHideEventToJSValue(const ContextMenuHideEvent & eventInfo)2080 JSRef<JSVal> ContextMenuHideEventToJSValue(const ContextMenuHideEvent& eventInfo)
2081 {
2082     JSRef<JSObject> obj = JSRef<JSObject>::New();
2083     obj->SetProperty("info", eventInfo.GetInfo());
2084     return JSRef<JSVal>::Cast(obj);
2085 }
2086 
FullScreenEnterEventToJSValue(const FullScreenEnterEvent & eventInfo)2087 JSRef<JSVal> FullScreenEnterEventToJSValue(const FullScreenEnterEvent& eventInfo)
2088 {
2089     JSRef<JSObject> obj = JSRef<JSObject>::New();
2090     JSRef<JSObject> resultObj = JSClass<JSFullScreenExitHandler>::NewInstance();
2091     auto jsFullScreenExitHandler = Referenced::Claim(resultObj->Unwrap<JSFullScreenExitHandler>());
2092     if (!jsFullScreenExitHandler) {
2093         return JSRef<JSVal>::Cast(obj);
2094     }
2095     jsFullScreenExitHandler->SetHandler(eventInfo.GetHandler());
2096 
2097     obj->SetPropertyObject("handler", resultObj);
2098     obj->SetProperty("videoWidth", eventInfo.GetVideoNaturalWidth());
2099     obj->SetProperty("videoHeight", eventInfo.GetVideoNaturalHeight());
2100     return JSRef<JSVal>::Cast(obj);
2101 }
2102 
FullScreenExitEventToJSValue(const FullScreenExitEvent & eventInfo)2103 JSRef<JSVal> FullScreenExitEventToJSValue(const FullScreenExitEvent& eventInfo)
2104 {
2105     return JSRef<JSVal>::Make(ToJSValue(eventInfo.IsFullScreen()));
2106 }
2107 
LoadWebPageStartEventToJSValue(const LoadWebPageStartEvent & eventInfo)2108 JSRef<JSVal> LoadWebPageStartEventToJSValue(const LoadWebPageStartEvent& eventInfo)
2109 {
2110     JSRef<JSObject> obj = JSRef<JSObject>::New();
2111     obj->SetProperty("url", eventInfo.GetLoadedUrl());
2112     return JSRef<JSVal>::Cast(obj);
2113 }
2114 
LoadWebProgressChangeEventToJSValue(const LoadWebProgressChangeEvent & eventInfo)2115 JSRef<JSVal> LoadWebProgressChangeEventToJSValue(const LoadWebProgressChangeEvent& eventInfo)
2116 {
2117     JSRef<JSObject> obj = JSRef<JSObject>::New();
2118     obj->SetProperty("newProgress", eventInfo.GetNewProgress());
2119     return JSRef<JSVal>::Cast(obj);
2120 }
2121 
LoadWebTitleReceiveEventToJSValue(const LoadWebTitleReceiveEvent & eventInfo)2122 JSRef<JSVal> LoadWebTitleReceiveEventToJSValue(const LoadWebTitleReceiveEvent& eventInfo)
2123 {
2124     JSRef<JSObject> obj = JSRef<JSObject>::New();
2125     obj->SetProperty("title", eventInfo.GetTitle());
2126     return JSRef<JSVal>::Cast(obj);
2127 }
2128 
UrlLoadInterceptEventToJSValue(const UrlLoadInterceptEvent & eventInfo)2129 JSRef<JSVal> UrlLoadInterceptEventToJSValue(const UrlLoadInterceptEvent& eventInfo)
2130 {
2131     JSRef<JSObject> obj = JSRef<JSObject>::New();
2132     obj->SetProperty("data", eventInfo.GetData());
2133     return JSRef<JSVal>::Cast(obj);
2134 }
2135 
LoadInterceptEventToJSValue(const LoadInterceptEvent & eventInfo)2136 JSRef<JSVal> LoadInterceptEventToJSValue(const LoadInterceptEvent& eventInfo)
2137 {
2138     JSRef<JSObject> obj = JSRef<JSObject>::New();
2139     JSRef<JSObject> requestObj = JSClass<JSWebResourceRequest>::NewInstance();
2140     auto requestEvent = Referenced::Claim(requestObj->Unwrap<JSWebResourceRequest>());
2141     requestEvent->SetLoadInterceptEvent(eventInfo);
2142     obj->SetPropertyObject("data", requestObj);
2143     return JSRef<JSVal>::Cast(obj);
2144 }
2145 
LoadWebGeolocationHideEventToJSValue(const LoadWebGeolocationHideEvent & eventInfo)2146 JSRef<JSVal> LoadWebGeolocationHideEventToJSValue(const LoadWebGeolocationHideEvent& eventInfo)
2147 {
2148     return JSRef<JSVal>::Make(ToJSValue(eventInfo.GetOrigin()));
2149 }
2150 
LoadWebGeolocationShowEventToJSValue(const LoadWebGeolocationShowEvent & eventInfo)2151 JSRef<JSVal> LoadWebGeolocationShowEventToJSValue(const LoadWebGeolocationShowEvent& eventInfo)
2152 {
2153     JSRef<JSObject> obj = JSRef<JSObject>::New();
2154     obj->SetProperty("origin", eventInfo.GetOrigin());
2155     JSRef<JSObject> geolocationObj = JSClass<JSWebGeolocation>::NewInstance();
2156     auto geolocationEvent = Referenced::Claim(geolocationObj->Unwrap<JSWebGeolocation>());
2157     geolocationEvent->SetEvent(eventInfo);
2158     obj->SetPropertyObject("geolocation", geolocationObj);
2159     return JSRef<JSVal>::Cast(obj);
2160 }
2161 
DownloadStartEventToJSValue(const DownloadStartEvent & eventInfo)2162 JSRef<JSVal> DownloadStartEventToJSValue(const DownloadStartEvent& eventInfo)
2163 {
2164     JSRef<JSObject> obj = JSRef<JSObject>::New();
2165     obj->SetProperty("url", eventInfo.GetUrl());
2166     obj->SetProperty("userAgent", eventInfo.GetUserAgent());
2167     obj->SetProperty("contentDisposition", eventInfo.GetContentDisposition());
2168     obj->SetProperty("mimetype", eventInfo.GetMimetype());
2169     obj->SetProperty("contentLength", eventInfo.GetContentLength());
2170     return JSRef<JSVal>::Cast(obj);
2171 }
2172 
LoadWebRequestFocusEventToJSValue(const LoadWebRequestFocusEvent & eventInfo)2173 JSRef<JSVal> LoadWebRequestFocusEventToJSValue(const LoadWebRequestFocusEvent& eventInfo)
2174 {
2175     return JSRef<JSVal>::Make(ToJSValue(eventInfo.GetRequestFocus()));
2176 }
2177 
WebHttpAuthEventToJSValue(const WebHttpAuthEvent & eventInfo)2178 JSRef<JSVal> WebHttpAuthEventToJSValue(const WebHttpAuthEvent& eventInfo)
2179 {
2180     JSRef<JSObject> obj = JSRef<JSObject>::New();
2181     JSRef<JSObject> resultObj = JSClass<JSWebHttpAuth>::NewInstance();
2182     auto jsWebHttpAuth = Referenced::Claim(resultObj->Unwrap<JSWebHttpAuth>());
2183     if (!jsWebHttpAuth) {
2184         return JSRef<JSVal>::Cast(obj);
2185     }
2186     jsWebHttpAuth->SetResult(eventInfo.GetResult());
2187     obj->SetPropertyObject("handler", resultObj);
2188     obj->SetProperty("host", eventInfo.GetHost());
2189     obj->SetProperty("realm", eventInfo.GetRealm());
2190     return JSRef<JSVal>::Cast(obj);
2191 }
2192 
WebSslErrorEventToJSValue(const WebSslErrorEvent & eventInfo)2193 JSRef<JSVal> WebSslErrorEventToJSValue(const WebSslErrorEvent& eventInfo)
2194 {
2195     JSRef<JSObject> obj = JSRef<JSObject>::New();
2196     JSRef<JSObject> resultObj = JSClass<JSWebSslError>::NewInstance();
2197     auto jsWebSslError = Referenced::Claim(resultObj->Unwrap<JSWebSslError>());
2198     if (!jsWebSslError) {
2199         return JSRef<JSVal>::Cast(obj);
2200     }
2201     jsWebSslError->SetResult(eventInfo.GetResult());
2202     obj->SetPropertyObject("handler", resultObj);
2203     obj->SetProperty("error", eventInfo.GetError());
2204 
2205     auto engine = EngineHelper::GetCurrentEngine();
2206     if (!engine) {
2207         return JSRef<JSVal>::Cast(obj);
2208     }
2209     NativeEngine* nativeEngine = engine->GetNativeEngine();
2210     napi_env env = reinterpret_cast<napi_env>(nativeEngine);
2211     std::vector<std::string> certChainDerData = eventInfo.GetCertChainData();
2212     JSRef<JSArray> certsArr = JSRef<JSArray>::New();
2213     for (uint8_t i = 0; i < certChainDerData.size(); i++) {
2214         if (i == UINT8_MAX) {
2215             TAG_LOGE(AceLogTag::ACE_WEB, "Cert chain data array reach max.");
2216             break;
2217         }
2218 
2219         void *data = nullptr;
2220         napi_value buffer = nullptr;
2221         napi_value item = nullptr;
2222         napi_status status = napi_create_arraybuffer(env, certChainDerData[i].size(), &data, &buffer);
2223         if (status != napi_ok) {
2224             TAG_LOGE(AceLogTag::ACE_WEB, "Create array buffer failed, status = %{public}d.", status);
2225             continue;
2226         }
2227         int retCode = memcpy_s(data, certChainDerData[i].size(),
2228                                certChainDerData[i].data(), certChainDerData[i].size());
2229         if (retCode != 0) {
2230             TAG_LOGE(AceLogTag::ACE_WEB, "Cert chain data failed, index = %{public}u.", i);
2231             continue;
2232         }
2233         status = napi_create_typedarray(env, napi_uint8_array, certChainDerData[i].size(), buffer, 0, &item);
2234         if (status != napi_ok) {
2235             TAG_LOGE(AceLogTag::ACE_WEB, "Create typed array failed, status = %{public}d.", status);
2236             continue;
2237         }
2238         JSRef<JSVal> cert = JsConverter::ConvertNapiValueToJsVal(item);
2239         certsArr->SetValueAt(i, cert);
2240     }
2241     obj->SetPropertyObject("certChainData", certsArr);
2242     return JSRef<JSVal>::Cast(obj);
2243 }
2244 
WebAllSslErrorEventToJSValue(const WebAllSslErrorEvent & eventInfo)2245 JSRef<JSVal> WebAllSslErrorEventToJSValue(const WebAllSslErrorEvent& eventInfo)
2246 {
2247     JSRef<JSObject> obj = JSRef<JSObject>::New();
2248     JSRef<JSObject> resultObj = JSClass<JSWebAllSslError>::NewInstance();
2249     auto jsWebAllSslError = Referenced::Claim(resultObj->Unwrap<JSWebAllSslError>());
2250     if (!jsWebAllSslError) {
2251         return JSRef<JSVal>::Cast(obj);
2252     }
2253     jsWebAllSslError->SetResult(eventInfo.GetResult());
2254     obj->SetPropertyObject("handler", resultObj);
2255     obj->SetProperty("error", eventInfo.GetError());
2256     obj->SetProperty("url", eventInfo.GetUrl());
2257     obj->SetProperty("originalUrl", eventInfo.GetOriginalUrl());
2258     obj->SetProperty("referrer", eventInfo.GetReferrer());
2259     obj->SetProperty("isFatalError", eventInfo.GetIsFatalError());
2260     obj->SetProperty("isMainFrame", eventInfo.GetIsMainFrame());
2261     return JSRef<JSVal>::Cast(obj);
2262 }
2263 
WebSslSelectCertEventToJSValue(const WebSslSelectCertEvent & eventInfo)2264 JSRef<JSVal> WebSslSelectCertEventToJSValue(const WebSslSelectCertEvent& eventInfo)
2265 {
2266     JSRef<JSObject> obj = JSRef<JSObject>::New();
2267     JSRef<JSObject> resultObj = JSClass<JSWebSslSelectCert>::NewInstance();
2268     auto jsWebSslSelectCert = Referenced::Claim(resultObj->Unwrap<JSWebSslSelectCert>());
2269     if (!jsWebSslSelectCert) {
2270         return JSRef<JSVal>::Cast(obj);
2271     }
2272     jsWebSslSelectCert->SetResult(eventInfo.GetResult());
2273     obj->SetPropertyObject("handler", resultObj);
2274     obj->SetProperty("host", eventInfo.GetHost());
2275     obj->SetProperty("port", eventInfo.GetPort());
2276 
2277     JSRef<JSArray> keyTypesArr = JSRef<JSArray>::New();
2278     const std::vector<std::string>& keyTypes = eventInfo.GetKeyTypes();
2279     for (int32_t idx = 0; idx < static_cast<int32_t>(keyTypes.size()); ++idx) {
2280         JSRef<JSVal> keyType = JSRef<JSVal>::Make(ToJSValue(keyTypes[idx]));
2281         keyTypesArr->SetValueAt(idx, keyType);
2282     }
2283     obj->SetPropertyObject("keyTypes", keyTypesArr);
2284 
2285     JSRef<JSArray> issuersArr = JSRef<JSArray>::New();
2286     const std::vector<std::string>& issuers = eventInfo.GetIssuers_();
2287     for (int32_t idx = 0; idx < static_cast<int32_t>(issuers.size()); ++idx) {
2288         JSRef<JSVal> issuer = JSRef<JSVal>::Make(ToJSValue(issuers[idx]));
2289         issuersArr->SetValueAt(idx, issuer);
2290     }
2291 
2292     obj->SetPropertyObject("issuers", issuersArr);
2293 
2294     return JSRef<JSVal>::Cast(obj);
2295 }
2296 
SearchResultReceiveEventToJSValue(const SearchResultReceiveEvent & eventInfo)2297 JSRef<JSVal> SearchResultReceiveEventToJSValue(const SearchResultReceiveEvent& eventInfo)
2298 {
2299     JSRef<JSObject> obj = JSRef<JSObject>::New();
2300     obj->SetProperty("activeMatchOrdinal", eventInfo.GetActiveMatchOrdinal());
2301     obj->SetProperty("numberOfMatches", eventInfo.GetNumberOfMatches());
2302     obj->SetProperty("isDoneCounting", eventInfo.GetIsDoneCounting());
2303     return JSRef<JSVal>::Cast(obj);
2304 }
2305 
LoadOverrideEventToJSValue(const LoadOverrideEvent & eventInfo)2306 JSRef<JSVal> LoadOverrideEventToJSValue(const LoadOverrideEvent& eventInfo)
2307 {
2308     JSRef<JSObject> requestObj = JSClass<JSWebResourceRequest>::NewInstance();
2309     auto requestEvent = Referenced::Claim(requestObj->Unwrap<JSWebResourceRequest>());
2310     requestEvent->SetLoadOverrideEvent(eventInfo);
2311     return JSRef<JSVal>::Cast(requestObj);
2312 }
2313 
AdsBlockedEventToJSValue(const AdsBlockedEvent & eventInfo)2314 JSRef<JSVal> AdsBlockedEventToJSValue(const AdsBlockedEvent& eventInfo)
2315 {
2316     JSRef<JSObject> obj = JSRef<JSObject>::New();
2317     obj->SetProperty("url", eventInfo.GetUrl());
2318 
2319     JSRef<JSArray> adsBlockedArr = JSRef<JSArray>::New();
2320     const std::vector<std::string>& adsBlocked = eventInfo.GetAdsBlocked();
2321     for (int32_t idx = 0; idx < static_cast<int32_t>(adsBlocked.size()); ++idx) {
2322         JSRef<JSVal> blockedUrl = JSRef<JSVal>::Make(ToJSValue(adsBlocked[idx]));
2323         adsBlockedArr->SetValueAt(idx, blockedUrl);
2324     }
2325     obj->SetPropertyObject("adsBlocked", adsBlockedArr);
2326 
2327     return JSRef<JSVal>::Cast(obj);
2328 }
2329 
ParseRawfileWebSrc(const JSRef<JSVal> & srcValue,std::string & webSrc)2330 void JSWeb::ParseRawfileWebSrc(const JSRef<JSVal>& srcValue, std::string& webSrc)
2331 {
2332     if (!srcValue->IsObject() || webSrc.substr(0, RAWFILE_PREFIX.size()) != RAWFILE_PREFIX) {
2333         return;
2334     }
2335     std::string bundleName;
2336     std::string moduleName;
2337     GetJsMediaBundleInfo(srcValue, bundleName, moduleName);
2338     auto container = Container::Current();
2339     CHECK_NULL_VOID(container);
2340     if ((!bundleName.empty() && !moduleName.empty()) &&
2341         (bundleName != AceApplicationInfo::GetInstance().GetPackageName() ||
2342         moduleName != container->GetModuleName())) {
2343         webSrc = RAWFILE_PREFIX + BUNDLE_NAME_PREFIX + bundleName + "/" + MODULE_NAME_PREFIX + moduleName + "/" +
2344             webSrc.substr(RAWFILE_PREFIX.size());
2345     }
2346 }
2347 
Create(const JSCallbackInfo & info)2348 void JSWeb::Create(const JSCallbackInfo& info)
2349 {
2350     if (info.Length() < 1 || !info[0]->IsObject()) {
2351         return;
2352     }
2353     auto paramObject = JSRef<JSObject>::Cast(info[0]);
2354     JSRef<JSVal> srcValue = paramObject->GetProperty("src");
2355     std::string webSrc;
2356     std::optional<std::string> dstSrc;
2357     if (srcValue->IsString()) {
2358         dstSrc = srcValue->ToString();
2359     } else if (ParseJsMedia(srcValue, webSrc)) {
2360         ParseRawfileWebSrc(srcValue, webSrc);
2361         int np = static_cast<int>(webSrc.find_first_of("/"));
2362         dstSrc = np < 0 ? webSrc : webSrc.erase(np, 1);
2363     }
2364     if (!dstSrc) {
2365         return;
2366     }
2367     auto controllerObj = paramObject->GetProperty("controller");
2368     if (!controllerObj->IsObject()) {
2369         return;
2370     }
2371     JsiRef<JsiValue> type = JsiRef<JsiValue>::Make();
2372     bool isHasType = paramObject->HasProperty("type");
2373     if (isHasType) {
2374         type = paramObject->GetProperty("type");
2375     } else {
2376         type = paramObject->GetProperty("renderMode");
2377     }
2378     RenderMode renderMode = RenderMode::ASYNC_RENDER;
2379     if (type->IsNumber() && (type->ToNumber<int32_t>() >= 0) && (type->ToNumber<int32_t>() <= 1)) {
2380         renderMode = static_cast<RenderMode>(type->ToNumber<int32_t>());
2381     }
2382 
2383     bool incognitoMode = false;
2384     ParseJsBool(paramObject->GetProperty("incognitoMode"), incognitoMode);
2385 
2386     std::string sharedRenderProcessToken = "";
2387     ParseJsString(paramObject->GetProperty("sharedRenderProcessToken"), sharedRenderProcessToken);
2388 
2389     auto controller = JSRef<JSObject>::Cast(controllerObj);
2390     auto setWebIdFunction = controller->GetProperty("setWebId");
2391     if (setWebIdFunction->IsFunction()) {
2392         auto setIdCallback = [webviewController = controller, func = JSRef<JSFunc>::Cast(setWebIdFunction)](
2393                                  int32_t webId) {
2394             JSRef<JSVal> argv[] = { JSRef<JSVal>::Make(ToJSValue(webId)) };
2395             func->Call(webviewController, 1, argv);
2396         };
2397 
2398         auto setHapPathFunction = controller->GetProperty("innerSetHapPath");
2399         std::function<void(const std::string&)> setHapPathCallback = nullptr;
2400         if (setHapPathFunction->IsFunction()) {
2401             setHapPathCallback = [webviewController = controller, func = JSRef<JSFunc>::Cast(setHapPathFunction)](
2402                                      const std::string& hapPath) {
2403                 JSRef<JSVal> argv[] = { JSRef<JSVal>::Make(ToJSValue(hapPath)) };
2404                 func->Call(webviewController, 1, argv);
2405             };
2406         }
2407 
2408         auto setRequestPermissionsFromUserFunction = controller->GetProperty("requestPermissionsFromUserWeb");
2409         std::function<void(const std::shared_ptr<BaseEventInfo>&)> requestPermissionsFromUserCallback = nullptr;
2410         if (setRequestPermissionsFromUserFunction->IsFunction()) {
2411             requestPermissionsFromUserCallback = [webviewController = controller,
2412                 func = JSRef<JSFunc>::Cast(setRequestPermissionsFromUserFunction)]
2413                 (const std::shared_ptr<BaseEventInfo>& info) {
2414                     auto* eventInfo = TypeInfoHelper::DynamicCast<WebPermissionRequestEvent>(info.get());
2415                     JSRef<JSObject> obj = JSRef<JSObject>::New();
2416                     JSRef<JSObject> permissionObj = JSClass<JSWebPermissionRequest>::NewInstance();
2417                     auto permissionEvent = Referenced::Claim(permissionObj->Unwrap<JSWebPermissionRequest>());
2418                     permissionEvent->SetEvent(*eventInfo);
2419                     obj->SetPropertyObject("request", permissionObj);
2420                     JSRef<JSVal> argv[] = { JSRef<JSVal>::Cast(obj) };
2421                     auto result = func->Call(webviewController, 1, argv);
2422             };
2423         }
2424 
2425         auto setOpenAppLinkFunction = controller->GetProperty("openAppLink");
2426         std::function<void(const std::shared_ptr<BaseEventInfo>&)> openAppLinkCallback = nullptr;
2427         if (setOpenAppLinkFunction->IsFunction()) {
2428             TAG_LOGI(AceLogTag::ACE_WEB, "WebDelegate::OnOpenAppLink setOpenAppLinkFunction 2");
2429             openAppLinkCallback = [webviewController = controller,
2430                 func = JSRef<JSFunc>::Cast(setOpenAppLinkFunction)]
2431                 (const std::shared_ptr<BaseEventInfo>& info) {
2432                     auto* eventInfo = TypeInfoHelper::DynamicCast<WebAppLinkEvent>(info.get());
2433                     JSRef<JSObject> obj = JSRef<JSObject>::New();
2434                     JSRef<JSObject> callbackObj = JSClass<JSWebAppLinkCallback>::NewInstance();
2435                     auto callbackEvent = Referenced::Claim(callbackObj->Unwrap<JSWebAppLinkCallback>());
2436                     callbackEvent->SetEvent(*eventInfo);
2437                     obj->SetPropertyObject("result", callbackObj);
2438                     JSRef<JSVal> urlVal = JSRef<JSVal>::Make(ToJSValue(eventInfo->GetUrl()));
2439                     obj->SetPropertyObject("url", urlVal);
2440                     JSRef<JSVal> argv[] = { JSRef<JSVal>::Cast(obj) };
2441                     auto result = func->Call(webviewController, 1, argv);
2442             };
2443         }
2444 
2445         auto fileSelectorShowFromUserFunction = controller->GetProperty("fileSelectorShowFromUserWeb");
2446         std::function<void(const std::shared_ptr<BaseEventInfo>&)> fileSelectorShowFromUserCallback = nullptr;
2447         if (fileSelectorShowFromUserFunction->IsFunction()) {
2448             fileSelectorShowFromUserCallback = [webviewController = controller,
2449                 func = JSRef<JSFunc>::Cast(fileSelectorShowFromUserFunction)]
2450                 (const std::shared_ptr<BaseEventInfo>& info) {
2451                     auto* eventInfo = TypeInfoHelper::DynamicCast<FileSelectorEvent>(info.get());
2452                     JSRef<JSObject> obj = JSRef<JSObject>::New();
2453                     JSRef<JSObject> paramObj = JSClass<JSFileSelectorParam>::NewInstance();
2454                     auto fileSelectorParam = Referenced::Claim(paramObj->Unwrap<JSFileSelectorParam>());
2455                     fileSelectorParam->SetParam(*eventInfo);
2456                     obj->SetPropertyObject("fileparam", paramObj);
2457 
2458                     JSRef<JSObject> resultObj = JSClass<JSFileSelectorResult>::NewInstance();
2459                     auto fileSelectorResult = Referenced::Claim(resultObj->Unwrap<JSFileSelectorResult>());
2460 
2461                     fileSelectorResult->SetResult(*eventInfo);
2462 
2463                     obj->SetPropertyObject("fileresult", resultObj);
2464                     JSRef<JSVal> argv[] = { JSRef<JSVal>::Cast(obj) };
2465                     auto result = func->Call(webviewController, 1, argv);
2466                 };
2467         }
2468 
2469         int32_t parentNWebId = -1;
2470         bool isPopup = JSWebWindowNewHandler::ExistController(controller, parentNWebId);
2471         WebModel::GetInstance()->Create(isPopup ? "" : dstSrc.value(), std::move(setIdCallback),
2472             std::move(setHapPathCallback), parentNWebId, isPopup, renderMode, incognitoMode, sharedRenderProcessToken);
2473 
2474         WebModel::GetInstance()->SetDefaultFileSelectorShow(std::move(fileSelectorShowFromUserCallback));
2475         WebModel::GetInstance()->SetPermissionClipboard(std::move(requestPermissionsFromUserCallback));
2476         WebModel::GetInstance()->SetOpenAppLinkFunction(std::move(openAppLinkCallback));
2477         auto getCmdLineFunction = controller->GetProperty("getCustomeSchemeCmdLine");
2478         if (!getCmdLineFunction->IsFunction()) {
2479             return;
2480         }
2481         std::string cmdLine = JSRef<JSFunc>::Cast(getCmdLineFunction)->Call(controller, 0, {})->ToString();
2482         if (!cmdLine.empty()) {
2483             WebModel::GetInstance()->SetCustomScheme(cmdLine);
2484         }
2485 
2486         auto updateInstanceIdFunction = controller->GetProperty("updateInstanceId");
2487         if (updateInstanceIdFunction->IsFunction()) {
2488             std::function<void(int32_t)> updateInstanceIdCallback = [webviewController = controller,
2489                 func = JSRef<JSFunc>::Cast(updateInstanceIdFunction)](int32_t newId) {
2490                 auto newIdVal = JSRef<JSVal>::Make(ToJSValue(newId));
2491                 auto result = func->Call(webviewController, 1, &newIdVal);
2492             };
2493             NG::WebModelNG::GetInstance()->SetUpdateInstanceIdCallback(std::move(updateInstanceIdCallback));
2494         }
2495 
2496         auto getWebDebugingFunction = controller->GetProperty("getWebDebuggingAccess");
2497         if (!getWebDebugingFunction->IsFunction()) {
2498             return;
2499         }
2500         bool webDebuggingAccess = JSRef<JSFunc>::Cast(getWebDebugingFunction)->Call(controller, 0, {})->ToBoolean();
2501         if (webDebuggingAccess == JSWeb::webDebuggingAccess_) {
2502             return;
2503         }
2504         WebModel::GetInstance()->SetWebDebuggingAccessEnabled(webDebuggingAccess);
2505         JSWeb::webDebuggingAccess_ = webDebuggingAccess;
2506         return;
2507 
2508     } else {
2509         auto* jsWebController = controller->Unwrap<JSWebController>();
2510         CHECK_NULL_VOID(jsWebController);
2511         WebModel::GetInstance()->Create(
2512             dstSrc.value(), jsWebController->GetController(), renderMode, incognitoMode, sharedRenderProcessToken);
2513     }
2514 
2515     WebModel::GetInstance()->SetFocusable(true);
2516     WebModel::GetInstance()->SetFocusNode(true);
2517 }
2518 
WebRotate(const JSCallbackInfo & args)2519 void JSWeb::WebRotate(const JSCallbackInfo& args) {}
2520 
OnAlert(const JSCallbackInfo & args)2521 void JSWeb::OnAlert(const JSCallbackInfo& args)
2522 {
2523     JSWeb::OnCommonDialog(args, DialogEventType::DIALOG_EVENT_ALERT);
2524 }
2525 
OnBeforeUnload(const JSCallbackInfo & args)2526 void JSWeb::OnBeforeUnload(const JSCallbackInfo& args)
2527 {
2528     JSWeb::OnCommonDialog(args, DialogEventType::DIALOG_EVENT_BEFORE_UNLOAD);
2529 }
2530 
OnConfirm(const JSCallbackInfo & args)2531 void JSWeb::OnConfirm(const JSCallbackInfo& args)
2532 {
2533     JSWeb::OnCommonDialog(args, DialogEventType::DIALOG_EVENT_CONFIRM);
2534 }
2535 
OnPrompt(const JSCallbackInfo & args)2536 void JSWeb::OnPrompt(const JSCallbackInfo& args)
2537 {
2538     JSWeb::OnCommonDialog(args, DialogEventType::DIALOG_EVENT_PROMPT);
2539 }
2540 
OnCommonDialog(const JSCallbackInfo & args,int dialogEventType)2541 void JSWeb::OnCommonDialog(const JSCallbackInfo& args, int dialogEventType)
2542 {
2543     if (!args[0]->IsFunction()) {
2544         return;
2545     }
2546     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
2547     auto jsFunc =
2548         AceType::MakeRefPtr<JsEventFunction<WebDialogEvent, 1>>(JSRef<JSFunc>::Cast(args[0]), WebDialogEventToJSValue);
2549     auto instanceId = Container::CurrentId();
2550     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
2551                           const BaseEventInfo* info) -> bool {
2552         ContainerScope scope(instanceId);
2553         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx, false);
2554         auto pipelineContext = PipelineContext::GetCurrentContext();
2555         CHECK_NULL_RETURN(pipelineContext, false);
2556         pipelineContext->UpdateCurrentActiveNode(node);
2557         auto* eventInfo = TypeInfoHelper::DynamicCast<WebDialogEvent>(info);
2558         JSRef<JSVal> message = func->ExecuteWithValue(*eventInfo);
2559         if (message->IsBoolean()) {
2560             return message->ToBoolean();
2561         } else {
2562             return false;
2563         }
2564     };
2565     WebModel::GetInstance()->SetOnCommonDialog(jsCallback, dialogEventType);
2566 }
2567 
OnConsoleLog(const JSCallbackInfo & args)2568 void JSWeb::OnConsoleLog(const JSCallbackInfo& args)
2569 {
2570     if (!args[0]->IsFunction()) {
2571         return;
2572     }
2573     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<LoadWebConsoleLogEvent, 1>>(
2574         JSRef<JSFunc>::Cast(args[0]), LoadWebConsoleLogEventToJSValue);
2575 
2576     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
2577     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), node = frameNode](
2578                           const BaseEventInfo* info) -> bool {
2579         bool result = false;
2580         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx, result);
2581         auto pipelineContext = PipelineContext::GetCurrentContext();
2582         CHECK_NULL_RETURN(pipelineContext, false);
2583         pipelineContext->UpdateCurrentActiveNode(node);
2584         auto* eventInfo = TypeInfoHelper::DynamicCast<LoadWebConsoleLogEvent>(info);
2585         JSRef<JSVal> message = func->ExecuteWithValue(*eventInfo);
2586         if (message->IsBoolean()) {
2587             result = message->ToBoolean();
2588         }
2589         return result;
2590     };
2591 
2592     WebModel::GetInstance()->SetOnConsoleLog(jsCallback);
2593 }
2594 
OnPageStart(const JSCallbackInfo & args)2595 void JSWeb::OnPageStart(const JSCallbackInfo& args)
2596 {
2597     if (!args[0]->IsFunction()) {
2598         return;
2599     }
2600     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<LoadWebPageStartEvent, 1>>(
2601         JSRef<JSFunc>::Cast(args[0]), LoadWebPageStartEventToJSValue);
2602 
2603     auto instanceId = Container::CurrentId();
2604     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
2605     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
2606                           const BaseEventInfo* info) {
2607         ContainerScope scope(instanceId);
2608         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
2609         auto pipelineContext = PipelineContext::GetCurrentContext();
2610         CHECK_NULL_VOID(pipelineContext);
2611         pipelineContext->UpdateCurrentActiveNode(node);
2612         auto* eventInfo = TypeInfoHelper::DynamicCast<LoadWebPageStartEvent>(info);
2613         func->Execute(*eventInfo);
2614     };
2615     WebModel::GetInstance()->SetOnPageStart(jsCallback);
2616 }
2617 
OnPageFinish(const JSCallbackInfo & args)2618 void JSWeb::OnPageFinish(const JSCallbackInfo& args)
2619 {
2620     if (!args[0]->IsFunction()) {
2621         return;
2622     }
2623     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<LoadWebPageFinishEvent, 1>>(
2624         JSRef<JSFunc>::Cast(args[0]), LoadWebPageFinishEventToJSValue);
2625 
2626     auto instanceId = Container::CurrentId();
2627     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
2628     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
2629                           const BaseEventInfo* info) {
2630         ContainerScope scope(instanceId);
2631         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
2632         auto pipelineContext = PipelineContext::GetCurrentContext();
2633         CHECK_NULL_VOID(pipelineContext);
2634         pipelineContext->UpdateCurrentActiveNode(node);
2635         auto* eventInfo = TypeInfoHelper::DynamicCast<LoadWebPageFinishEvent>(info);
2636         func->Execute(*eventInfo);
2637     };
2638     WebModel::GetInstance()->SetOnPageFinish(jsCallback);
2639 }
2640 
OnProgressChange(const JSCallbackInfo & args)2641 void JSWeb::OnProgressChange(const JSCallbackInfo& args)
2642 {
2643     if (args.Length() < 1 || !args[0]->IsFunction()) {
2644         return;
2645     }
2646     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<LoadWebProgressChangeEvent, 1>>(
2647         JSRef<JSFunc>::Cast(args[0]), LoadWebProgressChangeEventToJSValue);
2648 
2649     auto instanceId = Container::CurrentId();
2650     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
2651     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
2652                           const BaseEventInfo* info) {
2653         ContainerScope scope(instanceId);
2654         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
2655         auto pipelineContext = PipelineContext::GetCurrentContext();
2656         CHECK_NULL_VOID(pipelineContext);
2657         pipelineContext->UpdateCurrentActiveNode(node);
2658         auto* eventInfo = TypeInfoHelper::DynamicCast<LoadWebProgressChangeEvent>(info);
2659         func->ExecuteWithValue(*eventInfo);
2660     };
2661     WebModel::GetInstance()->SetOnProgressChange(jsCallback);
2662 }
2663 
OnTitleReceive(const JSCallbackInfo & args)2664 void JSWeb::OnTitleReceive(const JSCallbackInfo& args)
2665 {
2666     if (!args[0]->IsFunction()) {
2667         return;
2668     }
2669     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
2670     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<LoadWebTitleReceiveEvent, 1>>(
2671         JSRef<JSFunc>::Cast(args[0]), LoadWebTitleReceiveEventToJSValue);
2672     auto instanceId = Container::CurrentId();
2673     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
2674                           const BaseEventInfo* info) {
2675         ContainerScope scope(instanceId);
2676         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
2677         auto pipelineContext = PipelineContext::GetCurrentContext();
2678         CHECK_NULL_VOID(pipelineContext);
2679         pipelineContext->UpdateCurrentActiveNode(node);
2680         auto* eventInfo = TypeInfoHelper::DynamicCast<LoadWebTitleReceiveEvent>(info);
2681         func->Execute(*eventInfo);
2682     };
2683     WebModel::GetInstance()->SetOnTitleReceive(jsCallback);
2684 }
2685 
OnFullScreenExit(const JSCallbackInfo & args)2686 void JSWeb::OnFullScreenExit(const JSCallbackInfo& args)
2687 {
2688     if (!args[0]->IsFunction()) {
2689         return;
2690     }
2691     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
2692     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<FullScreenExitEvent, 1>>(
2693         JSRef<JSFunc>::Cast(args[0]), FullScreenExitEventToJSValue);
2694     auto instanceId = Container::CurrentId();
2695     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
2696                           const BaseEventInfo* info) {
2697         ContainerScope scope(instanceId);
2698         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
2699         auto pipelineContext = PipelineContext::GetCurrentContext();
2700         CHECK_NULL_VOID(pipelineContext);
2701         pipelineContext->UpdateCurrentActiveNode(node);
2702         auto* eventInfo = TypeInfoHelper::DynamicCast<FullScreenExitEvent>(info);
2703         func->Execute(*eventInfo);
2704     };
2705     WebModel::GetInstance()->SetOnFullScreenExit(jsCallback);
2706 }
2707 
OnFullScreenEnter(const JSCallbackInfo & args)2708 void JSWeb::OnFullScreenEnter(const JSCallbackInfo& args)
2709 {
2710     if (args.Length() < 1 || !args[0]->IsFunction()) {
2711         return;
2712     }
2713     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
2714     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<FullScreenEnterEvent, 1>>(
2715         JSRef<JSFunc>::Cast(args[0]), FullScreenEnterEventToJSValue);
2716     auto instanceId = Container::CurrentId();
2717     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
2718                           const BaseEventInfo* info) {
2719         ContainerScope scope(instanceId);
2720         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
2721         CHECK_NULL_VOID(func);
2722         auto pipelineContext = PipelineContext::GetCurrentContext();
2723         CHECK_NULL_VOID(pipelineContext);
2724         pipelineContext->UpdateCurrentActiveNode(node);
2725         auto* eventInfo = TypeInfoHelper::DynamicCast<FullScreenEnterEvent>(info);
2726         CHECK_NULL_VOID(eventInfo);
2727         func->Execute(*eventInfo);
2728     };
2729     WebModel::GetInstance()->SetOnFullScreenEnter(jsCallback);
2730 }
2731 
OnGeolocationHide(const JSCallbackInfo & args)2732 void JSWeb::OnGeolocationHide(const JSCallbackInfo& args)
2733 {
2734     if (!args[0]->IsFunction()) {
2735         return;
2736     }
2737     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
2738     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<LoadWebGeolocationHideEvent, 1>>(
2739         JSRef<JSFunc>::Cast(args[0]), LoadWebGeolocationHideEventToJSValue);
2740     auto instanceId = Container::CurrentId();
2741     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
2742                           const BaseEventInfo* info) {
2743         ContainerScope scope(instanceId);
2744         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
2745         auto pipelineContext = PipelineContext::GetCurrentContext();
2746         CHECK_NULL_VOID(pipelineContext);
2747         pipelineContext->UpdateCurrentActiveNode(node);
2748         auto* eventInfo = TypeInfoHelper::DynamicCast<LoadWebGeolocationHideEvent>(info);
2749         func->Execute(*eventInfo);
2750     };
2751     WebModel::GetInstance()->SetOnGeolocationHide(jsCallback);
2752 }
2753 
OnGeolocationShow(const JSCallbackInfo & args)2754 void JSWeb::OnGeolocationShow(const JSCallbackInfo& args)
2755 {
2756     if (!args[0]->IsFunction()) {
2757         return;
2758     }
2759     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
2760     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<LoadWebGeolocationShowEvent, 1>>(
2761         JSRef<JSFunc>::Cast(args[0]), LoadWebGeolocationShowEventToJSValue);
2762     auto instanceId = Container::CurrentId();
2763     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
2764                           const BaseEventInfo* info) {
2765         ContainerScope scope(instanceId);
2766         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
2767         auto pipelineContext = PipelineContext::GetCurrentContext();
2768         CHECK_NULL_VOID(pipelineContext);
2769         pipelineContext->UpdateCurrentActiveNode(node);
2770         auto* eventInfo = TypeInfoHelper::DynamicCast<LoadWebGeolocationShowEvent>(info);
2771         func->Execute(*eventInfo);
2772     };
2773     WebModel::GetInstance()->SetOnGeolocationShow(jsCallback);
2774 }
2775 
OnRequestFocus(const JSCallbackInfo & args)2776 void JSWeb::OnRequestFocus(const JSCallbackInfo& args)
2777 {
2778     if (!args[0]->IsFunction()) {
2779         return;
2780     }
2781     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
2782     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<LoadWebRequestFocusEvent, 1>>(
2783         JSRef<JSFunc>::Cast(args[0]), LoadWebRequestFocusEventToJSValue);
2784     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), node = frameNode](
2785                           const BaseEventInfo* info) {
2786         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
2787         auto pipelineContext = PipelineContext::GetCurrentContext();
2788         CHECK_NULL_VOID(pipelineContext);
2789         pipelineContext->UpdateCurrentActiveNode(node);
2790         auto* eventInfo = TypeInfoHelper::DynamicCast<LoadWebRequestFocusEvent>(info);
2791         func->Execute(*eventInfo);
2792     };
2793     WebModel::GetInstance()->SetOnRequestFocus(jsCallback);
2794 }
2795 
OnDownloadStart(const JSCallbackInfo & args)2796 void JSWeb::OnDownloadStart(const JSCallbackInfo& args)
2797 {
2798     if (!args[0]->IsFunction()) {
2799         return;
2800     }
2801     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
2802     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<DownloadStartEvent, 1>>(
2803         JSRef<JSFunc>::Cast(args[0]), DownloadStartEventToJSValue);
2804     auto instanceId = Container::CurrentId();
2805     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
2806                           const BaseEventInfo* info) {
2807         ContainerScope scope(instanceId);
2808         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
2809         auto pipelineContext = PipelineContext::GetCurrentContext();
2810         CHECK_NULL_VOID(pipelineContext);
2811         pipelineContext->UpdateCurrentActiveNode(node);
2812         auto* eventInfo = TypeInfoHelper::DynamicCast<DownloadStartEvent>(info);
2813         func->Execute(*eventInfo);
2814     };
2815     WebModel::GetInstance()->SetOnDownloadStart(jsCallback);
2816 }
2817 
OnHttpAuthRequest(const JSCallbackInfo & args)2818 void JSWeb::OnHttpAuthRequest(const JSCallbackInfo& args)
2819 {
2820     if (args.Length() < 1 || !args[0]->IsFunction()) {
2821         return;
2822     }
2823     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
2824     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<WebHttpAuthEvent, 1>>(
2825         JSRef<JSFunc>::Cast(args[0]), WebHttpAuthEventToJSValue);
2826     auto instanceId = Container::CurrentId();
2827     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
2828                           const BaseEventInfo* info) -> bool {
2829         ContainerScope scope(instanceId);
2830         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx, false);
2831         auto pipelineContext = PipelineContext::GetCurrentContext();
2832         CHECK_NULL_RETURN(pipelineContext, false);
2833         pipelineContext->UpdateCurrentActiveNode(node);
2834         auto* eventInfo = TypeInfoHelper::DynamicCast<WebHttpAuthEvent>(info);
2835         JSRef<JSVal> message = func->ExecuteWithValue(*eventInfo);
2836         if (message->IsBoolean()) {
2837             return message->ToBoolean();
2838         }
2839         return false;
2840     };
2841     WebModel::GetInstance()->SetOnHttpAuthRequest(jsCallback);
2842 }
2843 
OnSslErrRequest(const JSCallbackInfo & args)2844 void JSWeb::OnSslErrRequest(const JSCallbackInfo& args)
2845 {
2846     return;
2847 }
2848 
OnSslErrorRequest(const JSCallbackInfo & args)2849 void JSWeb::OnSslErrorRequest(const JSCallbackInfo& args)
2850 {
2851     if (args.Length() < 1 || !args[0]->IsFunction()) {
2852         return;
2853     }
2854     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
2855     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<WebSslErrorEvent, 1>>(
2856         JSRef<JSFunc>::Cast(args[0]), WebSslErrorEventToJSValue);
2857     auto instanceId = Container::CurrentId();
2858     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
2859                           const BaseEventInfo* info) -> bool {
2860         ContainerScope scope(instanceId);
2861         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx, false);
2862         auto pipelineContext = PipelineContext::GetCurrentContext();
2863         CHECK_NULL_RETURN(pipelineContext, false);
2864         pipelineContext->UpdateCurrentActiveNode(node);
2865         auto* eventInfo = TypeInfoHelper::DynamicCast<WebSslErrorEvent>(info);
2866         func->Execute(*eventInfo);
2867         return true;
2868     };
2869     WebModel::GetInstance()->SetOnSslErrorRequest(jsCallback);
2870 }
2871 
OnAllSslErrorRequest(const JSCallbackInfo & args)2872 void JSWeb::OnAllSslErrorRequest(const JSCallbackInfo& args)
2873 {
2874     if (args.Length() < 1 || !args[0]->IsFunction()) {
2875         return;
2876     }
2877     auto frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
2878     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<WebAllSslErrorEvent, 1>>(
2879         JSRef<JSFunc>::Cast(args[0]), WebAllSslErrorEventToJSValue);
2880     auto instanceId = Container::CurrentId();
2881     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
2882                           const BaseEventInfo* info) -> bool {
2883         ContainerScope scope(instanceId);
2884         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx, false);
2885         auto pipelineContext = PipelineContext::GetCurrentContext();
2886         CHECK_NULL_RETURN(pipelineContext, false);
2887         pipelineContext->UpdateCurrentActiveNode(node);
2888         auto* eventInfo = TypeInfoHelper::DynamicCast<WebAllSslErrorEvent>(info);
2889         func->Execute(*eventInfo);
2890         return true;
2891     };
2892     WebModel::GetInstance()->SetOnAllSslErrorRequest(jsCallback);
2893 }
2894 
OnSslSelectCertRequest(const JSCallbackInfo & args)2895 void JSWeb::OnSslSelectCertRequest(const JSCallbackInfo& args)
2896 {
2897     if (args.Length() < 1 || !args[0]->IsFunction()) {
2898         return;
2899     }
2900     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
2901     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<WebSslSelectCertEvent, 1>>(
2902         JSRef<JSFunc>::Cast(args[0]), WebSslSelectCertEventToJSValue);
2903     auto instanceId = Container::CurrentId();
2904     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
2905                           const BaseEventInfo* info) -> bool {
2906         ContainerScope scope(instanceId);
2907         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx, false);
2908         auto pipelineContext = PipelineContext::GetCurrentContext();
2909         CHECK_NULL_RETURN(pipelineContext, false);
2910         pipelineContext->UpdateCurrentActiveNode(node);
2911         auto* eventInfo = TypeInfoHelper::DynamicCast<WebSslSelectCertEvent>(info);
2912         JSRef<JSVal> message = func->ExecuteWithValue(*eventInfo);
2913         if (message->IsBoolean()) {
2914             return message->ToBoolean();
2915         }
2916         return false;
2917     };
2918     WebModel::GetInstance()->SetOnSslSelectCertRequest(jsCallback);
2919 }
2920 
MediaPlayGestureAccess(bool isNeedGestureAccess)2921 void JSWeb::MediaPlayGestureAccess(bool isNeedGestureAccess)
2922 {
2923     WebModel::GetInstance()->SetMediaPlayGestureAccess(isNeedGestureAccess);
2924 }
2925 
OnKeyEvent(const JSCallbackInfo & args)2926 void JSWeb::OnKeyEvent(const JSCallbackInfo& args)
2927 {
2928     if (args.Length() < 1 || !args[0]->IsFunction()) {
2929         return;
2930     }
2931 
2932     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
2933     RefPtr<JsKeyFunction> jsOnKeyEventFunc = AceType::MakeRefPtr<JsKeyFunction>(JSRef<JSFunc>::Cast(args[0]));
2934     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsOnKeyEventFunc), node = frameNode](
2935                           KeyEventInfo& keyEventInfo) {
2936         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
2937         auto pipelineContext = PipelineContext::GetCurrentContext();
2938         CHECK_NULL_VOID(pipelineContext);
2939         pipelineContext->UpdateCurrentActiveNode(node);
2940         func->Execute(keyEventInfo);
2941     };
2942     WebModel::GetInstance()->SetOnKeyEvent(jsCallback);
2943 }
2944 
ReceivedErrorEventToJSValue(const ReceivedErrorEvent & eventInfo)2945 JSRef<JSVal> ReceivedErrorEventToJSValue(const ReceivedErrorEvent& eventInfo)
2946 {
2947     JSRef<JSObject> obj = JSRef<JSObject>::New();
2948 
2949     JSRef<JSObject> requestObj = JSClass<JSWebResourceRequest>::NewInstance();
2950     auto requestEvent = Referenced::Claim(requestObj->Unwrap<JSWebResourceRequest>());
2951     requestEvent->SetErrorEvent(eventInfo);
2952 
2953     JSRef<JSObject> errorObj = JSClass<JSWebResourceError>::NewInstance();
2954     auto errorEvent = Referenced::Claim(errorObj->Unwrap<JSWebResourceError>());
2955     errorEvent->SetEvent(eventInfo);
2956 
2957     obj->SetPropertyObject("request", requestObj);
2958     obj->SetPropertyObject("error", errorObj);
2959 
2960     return JSRef<JSVal>::Cast(obj);
2961 }
2962 
ReceivedHttpErrorEventToJSValue(const ReceivedHttpErrorEvent & eventInfo)2963 JSRef<JSVal> ReceivedHttpErrorEventToJSValue(const ReceivedHttpErrorEvent& eventInfo)
2964 {
2965     JSRef<JSObject> obj = JSRef<JSObject>::New();
2966 
2967     JSRef<JSObject> requestObj = JSClass<JSWebResourceRequest>::NewInstance();
2968     auto requestEvent = Referenced::Claim(requestObj->Unwrap<JSWebResourceRequest>());
2969     requestEvent->SetHttpErrorEvent(eventInfo);
2970 
2971     JSRef<JSObject> responseObj = JSClass<JSWebResourceResponse>::NewInstance();
2972     auto responseEvent = Referenced::Claim(responseObj->Unwrap<JSWebResourceResponse>());
2973     responseEvent->SetEvent(eventInfo);
2974 
2975     obj->SetPropertyObject("request", requestObj);
2976     obj->SetPropertyObject("response", responseObj);
2977 
2978     return JSRef<JSVal>::Cast(obj);
2979 }
2980 
OnErrorReceive(const JSCallbackInfo & args)2981 void JSWeb::OnErrorReceive(const JSCallbackInfo& args)
2982 {
2983     if (!args[0]->IsFunction()) {
2984         return;
2985     }
2986     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
2987     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<ReceivedErrorEvent, 1>>(
2988         JSRef<JSFunc>::Cast(args[0]), ReceivedErrorEventToJSValue);
2989     auto instanceId = Container::CurrentId();
2990     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
2991                           const BaseEventInfo* info) {
2992         ContainerScope scope(instanceId);
2993         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
2994         auto pipelineContext = PipelineContext::GetCurrentContext();
2995         CHECK_NULL_VOID(pipelineContext);
2996         pipelineContext->UpdateCurrentActiveNode(node);
2997         auto* eventInfo = TypeInfoHelper::DynamicCast<ReceivedErrorEvent>(info);
2998         func->Execute(*eventInfo);
2999     };
3000     WebModel::GetInstance()->SetOnErrorReceive(jsCallback);
3001 }
3002 
OnHttpErrorReceive(const JSCallbackInfo & args)3003 void JSWeb::OnHttpErrorReceive(const JSCallbackInfo& args)
3004 {
3005     if (!args[0]->IsFunction()) {
3006         return;
3007     }
3008     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3009     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<ReceivedHttpErrorEvent, 1>>(
3010         JSRef<JSFunc>::Cast(args[0]), ReceivedHttpErrorEventToJSValue);
3011     auto instanceId = Container::CurrentId();
3012     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
3013                           const BaseEventInfo* info) {
3014         ContainerScope scope(instanceId);
3015         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
3016         auto pipelineContext = PipelineContext::GetCurrentContext();
3017         CHECK_NULL_VOID(pipelineContext);
3018         pipelineContext->UpdateCurrentActiveNode(node);
3019         auto* eventInfo = TypeInfoHelper::DynamicCast<ReceivedHttpErrorEvent>(info);
3020         func->Execute(*eventInfo);
3021     };
3022     WebModel::GetInstance()->SetOnHttpErrorReceive(jsCallback);
3023 }
3024 
OnInterceptRequestEventToJSValue(const OnInterceptRequestEvent & eventInfo)3025 JSRef<JSVal> OnInterceptRequestEventToJSValue(const OnInterceptRequestEvent& eventInfo)
3026 {
3027     JSRef<JSObject> obj = JSRef<JSObject>::New();
3028     JSRef<JSObject> requestObj = JSClass<JSWebResourceRequest>::NewInstance();
3029     auto requestEvent = Referenced::Claim(requestObj->Unwrap<JSWebResourceRequest>());
3030     requestEvent->SetOnInterceptRequestEvent(eventInfo);
3031     obj->SetPropertyObject("request", requestObj);
3032     return JSRef<JSVal>::Cast(obj);
3033 }
3034 
OnInterceptRequest(const JSCallbackInfo & args)3035 void JSWeb::OnInterceptRequest(const JSCallbackInfo& args)
3036 {
3037     if ((args.Length() <= 0) || !args[0]->IsFunction()) {
3038         return;
3039     }
3040     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3041     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<OnInterceptRequestEvent, 1>>(
3042         JSRef<JSFunc>::Cast(args[0]), OnInterceptRequestEventToJSValue);
3043     auto instanceId = Container::CurrentId();
3044     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
3045                           const BaseEventInfo* info) -> RefPtr<WebResponse> {
3046         ContainerScope scope(instanceId);
3047         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx, nullptr);
3048         auto pipelineContext = PipelineContext::GetCurrentContext();
3049         CHECK_NULL_RETURN(pipelineContext, nullptr);
3050         pipelineContext->UpdateCurrentActiveNode(node);
3051         auto* eventInfo = TypeInfoHelper::DynamicCast<OnInterceptRequestEvent>(info);
3052         JSRef<JSVal> obj = func->ExecuteWithValue(*eventInfo);
3053         if (!obj->IsObject()) {
3054             return nullptr;
3055         }
3056         auto jsResponse = JSRef<JSObject>::Cast(obj)->Unwrap<JSWebResourceResponse>();
3057         if (jsResponse) {
3058             return jsResponse->GetResponseObj();
3059         }
3060         return nullptr;
3061     };
3062     WebModel::GetInstance()->SetOnInterceptRequest(jsCallback);
3063 }
3064 
OnUrlLoadIntercept(const JSCallbackInfo & args)3065 void JSWeb::OnUrlLoadIntercept(const JSCallbackInfo& args)
3066 {
3067     if (!args[0]->IsFunction()) {
3068         return;
3069     }
3070     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3071     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<UrlLoadInterceptEvent, 1>>(
3072         JSRef<JSFunc>::Cast(args[0]), UrlLoadInterceptEventToJSValue);
3073     auto instanceId = Container::CurrentId();
3074     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
3075                           const BaseEventInfo* info) -> bool {
3076         ContainerScope scope(instanceId);
3077         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx, false);
3078         auto pipelineContext = PipelineContext::GetCurrentContext();
3079         CHECK_NULL_RETURN(pipelineContext, false);
3080         pipelineContext->UpdateCurrentActiveNode(node);
3081         auto* eventInfo = TypeInfoHelper::DynamicCast<UrlLoadInterceptEvent>(info);
3082         JSRef<JSVal> message = func->ExecuteWithValue(*eventInfo);
3083         if (message->IsBoolean()) {
3084             return message->ToBoolean();
3085         }
3086         return false;
3087     };
3088     WebModel::GetInstance()->SetOnUrlLoadIntercept(jsCallback);
3089 }
3090 
OnLoadIntercept(const JSCallbackInfo & args)3091 void JSWeb::OnLoadIntercept(const JSCallbackInfo& args)
3092 {
3093     if (!args[0]->IsFunction()) {
3094         return;
3095     }
3096     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<LoadInterceptEvent, 1>>(
3097         JSRef<JSFunc>::Cast(args[0]), LoadInterceptEventToJSValue);
3098     auto instanceId = Container::CurrentId();
3099 
3100     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3101     auto uiCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
3102                           const BaseEventInfo* info) -> bool {
3103         ContainerScope scope(instanceId);
3104         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx, false);
3105         auto pipelineContext = PipelineContext::GetCurrentContext();
3106         CHECK_NULL_RETURN(pipelineContext, false);
3107         pipelineContext->UpdateCurrentActiveNode(node);
3108         auto* eventInfo = TypeInfoHelper::DynamicCast<LoadInterceptEvent>(info);
3109         JSRef<JSVal> message = func->ExecuteWithValue(*eventInfo);
3110         if (message->IsBoolean()) {
3111             return message->ToBoolean();
3112         }
3113         return false;
3114     };
3115     WebModel::GetInstance()->SetOnLoadIntercept(std::move(uiCallback));
3116 }
3117 
FileSelectorEventToJSValue(const FileSelectorEvent & eventInfo)3118 JSRef<JSVal> FileSelectorEventToJSValue(const FileSelectorEvent& eventInfo)
3119 {
3120     JSRef<JSObject> obj = JSRef<JSObject>::New();
3121 
3122     JSRef<JSObject> paramObj = JSClass<JSFileSelectorParam>::NewInstance();
3123     auto fileSelectorParam = Referenced::Claim(paramObj->Unwrap<JSFileSelectorParam>());
3124     fileSelectorParam->SetParam(eventInfo);
3125 
3126     JSRef<JSObject> resultObj = JSClass<JSFileSelectorResult>::NewInstance();
3127     auto fileSelectorResult = Referenced::Claim(resultObj->Unwrap<JSFileSelectorResult>());
3128     fileSelectorResult->SetResult(eventInfo);
3129 
3130     obj->SetPropertyObject("result", resultObj);
3131     obj->SetPropertyObject("fileSelector", paramObj);
3132     return JSRef<JSVal>::Cast(obj);
3133 }
3134 
OnFileSelectorShow(const JSCallbackInfo & args)3135 void JSWeb::OnFileSelectorShow(const JSCallbackInfo& args)
3136 {
3137     if (!args[0]->IsFunction()) {
3138         return;
3139     }
3140 
3141     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3142     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<FileSelectorEvent, 1>>(
3143         JSRef<JSFunc>::Cast(args[0]), FileSelectorEventToJSValue);
3144     auto instanceId = Container::CurrentId();
3145     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
3146                           const BaseEventInfo* info) -> bool {
3147         ContainerScope scope(instanceId);
3148         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx, false);
3149         auto pipelineContext = PipelineContext::GetCurrentContext();
3150         CHECK_NULL_RETURN(pipelineContext, false);
3151         pipelineContext->UpdateCurrentActiveNode(node);
3152         auto* eventInfo = TypeInfoHelper::DynamicCast<FileSelectorEvent>(info);
3153         JSRef<JSVal> message = func->ExecuteWithValue(*eventInfo);
3154         if (message->IsBoolean()) {
3155             return message->ToBoolean();
3156         }
3157         return false;
3158     };
3159     WebModel::GetInstance()->SetOnFileSelectorShow(jsCallback);
3160 }
3161 
ContextMenuEventToJSValue(const ContextMenuEvent & eventInfo)3162 JSRef<JSVal> ContextMenuEventToJSValue(const ContextMenuEvent& eventInfo)
3163 {
3164     JSRef<JSObject> obj = JSRef<JSObject>::New();
3165 
3166     JSRef<JSObject> paramObj = JSClass<JSContextMenuParam>::NewInstance();
3167     auto contextMenuParam = Referenced::Claim(paramObj->Unwrap<JSContextMenuParam>());
3168     contextMenuParam->SetParam(eventInfo);
3169 
3170     JSRef<JSObject> resultObj = JSClass<JSContextMenuResult>::NewInstance();
3171     auto contextMenuResult = Referenced::Claim(resultObj->Unwrap<JSContextMenuResult>());
3172     contextMenuResult->SetResult(eventInfo);
3173 
3174     obj->SetPropertyObject("result", resultObj);
3175     obj->SetPropertyObject("param", paramObj);
3176     return JSRef<JSVal>::Cast(obj);
3177 }
3178 
OnContextMenuShow(const JSCallbackInfo & args)3179 void JSWeb::OnContextMenuShow(const JSCallbackInfo& args)
3180 {
3181     if (args.Length() < 1 || !args[0]->IsFunction()) {
3182         return;
3183     }
3184     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3185     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<ContextMenuEvent, 1>>(
3186         JSRef<JSFunc>::Cast(args[0]), ContextMenuEventToJSValue);
3187     auto instanceId = Container::CurrentId();
3188     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
3189                           const BaseEventInfo* info) -> bool {
3190         ContainerScope scope(instanceId);
3191         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx, false);
3192         auto pipelineContext = PipelineContext::GetCurrentContext();
3193         CHECK_NULL_RETURN(pipelineContext, false);
3194         pipelineContext->UpdateCurrentActiveNode(node);
3195         auto* eventInfo = TypeInfoHelper::DynamicCast<ContextMenuEvent>(info);
3196         JSRef<JSVal> message = func->ExecuteWithValue(*eventInfo);
3197         if (message->IsBoolean()) {
3198             return message->ToBoolean();
3199         }
3200         return false;
3201     };
3202     WebModel::GetInstance()->SetOnContextMenuShow(jsCallback);
3203 }
3204 
ParseBindSelectionMenuParam(const JSCallbackInfo & info,const JSRef<JSObject> & menuOptions,NG::MenuParam & menuParam)3205 void ParseBindSelectionMenuParam(
3206     const JSCallbackInfo& info, const JSRef<JSObject>& menuOptions, NG::MenuParam& menuParam)
3207 {
3208     auto frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3209     auto onDisappearValue = menuOptions->GetProperty("onDisappear");
3210     if (onDisappearValue->IsFunction()) {
3211         RefPtr<JsFunction> jsOnDisAppearFunc =
3212             AceType::MakeRefPtr<JsFunction>(JSRef<JSObject>(), JSRef<JSFunc>::Cast(onDisappearValue));
3213         auto onDisappear = [execCtx = info.GetExecutionContext(), func = std::move(jsOnDisAppearFunc),
3214                             node = frameNode]() {
3215             JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
3216             ACE_SCORING_EVENT("onDisappear");
3217             PipelineContext::SetCallBackNode(node);
3218             func->Execute();
3219         };
3220         menuParam.onDisappear = std::move(onDisappear);
3221     }
3222 
3223     auto onAppearValue = menuOptions->GetProperty("onAppear");
3224     if (onAppearValue->IsFunction()) {
3225         RefPtr<JsFunction> jsOnAppearFunc =
3226             AceType::MakeRefPtr<JsFunction>(JSRef<JSObject>(), JSRef<JSFunc>::Cast(onAppearValue));
3227         auto onAppear = [execCtx = info.GetExecutionContext(), func = std::move(jsOnAppearFunc),
3228                          node = frameNode]() {
3229             JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
3230             ACE_SCORING_EVENT("onAppear");
3231             PipelineContext::SetCallBackNode(node);
3232             func->Execute();
3233         };
3234         menuParam.onAppear = std::move(onAppear);
3235     }
3236 }
3237 
ParseBindSelectionMenuOptionParam(const JSCallbackInfo & info,const JSRef<JSVal> & args,NG::MenuParam & menuParam,std::function<void ()> & previewBuildFunc)3238 void ParseBindSelectionMenuOptionParam(const JSCallbackInfo& info, const JSRef<JSVal>& args,
3239     NG::MenuParam& menuParam, std::function<void()>& previewBuildFunc)
3240 {
3241     auto menuOptions = JSRef<JSObject>::Cast(args);
3242     ParseBindSelectionMenuParam(info, menuOptions, menuParam);
3243 
3244     auto preview = menuOptions->GetProperty("preview");
3245     if (!preview->IsFunction()) {
3246         return;
3247     }
3248     auto menuType = menuOptions->GetProperty("menuType");
3249     bool isPreviewMenu = menuType->IsNumber() && menuType->ToNumber<int32_t>() == 1;
3250     if (isPreviewMenu) {
3251         menuParam.previewMode = MenuPreviewMode::CUSTOM;
3252         RefPtr<JsFunction> previewBuilderFunc = AceType::MakeRefPtr<JsFunction>(JSRef<JSFunc>::Cast(preview));
3253         CHECK_NULL_VOID(previewBuilderFunc);
3254         auto frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3255         previewBuildFunc = [execCtx = info.GetExecutionContext(), func = std::move(previewBuilderFunc),
3256                             node = frameNode]() {
3257             JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
3258             ACE_SCORING_EVENT("BindSelectionMenuPreviwer");
3259             PipelineContext::SetCallBackNode(node);
3260             func->Execute();
3261         };
3262     }
3263 }
3264 
GetSelectionMenuParam(const JSCallbackInfo & info,ResponseType responseType,std::function<void ()> & previewBuilder)3265 NG::MenuParam GetSelectionMenuParam(
3266     const JSCallbackInfo& info, ResponseType responseType, std::function<void()>& previewBuilder)
3267 {
3268     NG::MenuParam menuParam;
3269     if (info.Length() > SELECTION_MENU_OPTION_PARAM_INDEX && info[SELECTION_MENU_OPTION_PARAM_INDEX]->IsObject()) {
3270         ParseBindSelectionMenuOptionParam(info, info[SELECTION_MENU_OPTION_PARAM_INDEX], menuParam, previewBuilder);
3271     }
3272 
3273     if (responseType != ResponseType::LONG_PRESS) {
3274         menuParam.previewMode = MenuPreviewMode::NONE;
3275         menuParam.menuBindType = MenuBindingType::RIGHT_CLICK;
3276     }
3277     menuParam.contextMenuRegisterType = NG::ContextMenuRegisterType::CUSTOM_TYPE;
3278     menuParam.type = NG::MenuType::CONTEXT_MENU;
3279     NG::PaddingProperty paddings;
3280     paddings.start = NG::CalcLength(PREVIEW_MENU_MARGIN_LEFT);
3281     paddings.end = NG::CalcLength(PREVIEW_MENU_MARGIN_RIGHT);
3282     menuParam.layoutRegionMargin = paddings;
3283     menuParam.disappearScaleToTarget = true;
3284     menuParam.isPreviewContainScale = true;
3285     menuParam.isShow = true;
3286     return menuParam;
3287 }
3288 
BindSelectionMenu(const JSCallbackInfo & info)3289 void JSWeb::BindSelectionMenu(const JSCallbackInfo& info)
3290 {
3291     if (info.Length() < SELECTION_MENU_OPTION_PARAM_INDEX || !info[0]->IsNumber() || !info[1]->IsObject() ||
3292         !info[SELECTION_MENU_CONTENT_PARAM_INDEX]->IsNumber()) {
3293         return;
3294     }
3295     if (info[0]->ToNumber<int32_t>() != static_cast<int32_t>(WebElementType::IMAGE) ||
3296         info[SELECTION_MENU_CONTENT_PARAM_INDEX]->ToNumber<int32_t>() !=
3297         static_cast<int32_t>(ResponseType::LONG_PRESS)) {
3298         TAG_LOGW(AceLogTag::ACE_WEB, "WebElementType or WebResponseType param err");
3299         return;
3300     }
3301     WebElementType elementType = static_cast<WebElementType>(info[0]->ToNumber<int32_t>());
3302     ResponseType responseType =
3303         static_cast<ResponseType>(info[SELECTION_MENU_CONTENT_PARAM_INDEX]->ToNumber<int32_t>());
3304 
3305     // Builder
3306     JSRef<JSObject> menuObj = JSRef<JSObject>::Cast(info[1]);
3307     auto builder = menuObj->GetProperty("builder");
3308     if (!builder->IsFunction()) {
3309         TAG_LOGW(AceLogTag::ACE_WEB, "BindSelectionMenu menu builder param err");
3310         return;
3311     }
3312     auto builderFunc = AceType::MakeRefPtr<JsFunction>(JSRef<JSFunc>::Cast(builder));
3313     CHECK_NULL_VOID(builderFunc);
3314     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3315     std::function<void()> menuBuilder = [execCtx = info.GetExecutionContext(), func = std::move(builderFunc),
3316                                          node = frameNode]() {
3317         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
3318         ACE_SCORING_EVENT("BindSelectionMenu");
3319         PipelineContext::SetCallBackNode(node);
3320         func->Execute();
3321     };
3322 
3323     std::function<void()> previewBuilder = nullptr;
3324     NG::MenuParam menuParam = GetSelectionMenuParam(info, responseType, previewBuilder);
3325     WebModel::GetInstance()->SetNewDragStyle(true);
3326     auto previewSelectionMenuParam = std::make_shared<WebPreviewSelectionMenuParam>(
3327         elementType, responseType, menuBuilder, previewBuilder, menuParam);
3328     WebModel::GetInstance()->SetPreviewSelectionMenu(previewSelectionMenuParam);
3329 }
3330 
OnContextMenuHide(const JSCallbackInfo & args)3331 void JSWeb::OnContextMenuHide(const JSCallbackInfo& args)
3332 {
3333     if (!args[0]->IsFunction()) {
3334         return;
3335     }
3336     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3337     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<ContextMenuHideEvent, 1>>(
3338         JSRef<JSFunc>::Cast(args[0]), ContextMenuHideEventToJSValue);
3339 
3340     auto instanceId = Container::CurrentId();
3341     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
3342                           const BaseEventInfo* info) {
3343         ContainerScope scope(instanceId);
3344         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
3345         auto pipelineContext = PipelineContext::GetCurrentContext();
3346         CHECK_NULL_VOID(pipelineContext);
3347         pipelineContext->UpdateCurrentActiveNode(node);
3348         auto* eventInfo = TypeInfoHelper::DynamicCast<ContextMenuHideEvent>(info);
3349         func->Execute(*eventInfo);
3350     };
3351     WebModel::GetInstance()->SetOnContextMenuHide(jsCallback);
3352 }
3353 
JsEnabled(bool isJsEnabled)3354 void JSWeb::JsEnabled(bool isJsEnabled)
3355 {
3356     WebModel::GetInstance()->SetJsEnabled(isJsEnabled);
3357 }
3358 
ContentAccessEnabled(bool isContentAccessEnabled)3359 void JSWeb::ContentAccessEnabled(bool isContentAccessEnabled)
3360 {
3361 #if !defined(NG_BUILD) && !defined(ANDROID_PLATFORM) && !defined(IOS_PLATFORM)
3362     auto stack = ViewStackProcessor::GetInstance();
3363     auto webComponent = AceType::DynamicCast<WebComponent>(stack->GetMainComponent());
3364     if (!webComponent) {
3365         return;
3366     }
3367     webComponent->SetContentAccessEnabled(isContentAccessEnabled);
3368 #else
3369     TAG_LOGW(AceLogTag::ACE_WEB, "do not support components in new pipeline mode");
3370 #endif
3371 }
3372 
FileAccessEnabled(bool isFileAccessEnabled)3373 void JSWeb::FileAccessEnabled(bool isFileAccessEnabled)
3374 {
3375     WebModel::GetInstance()->SetFileAccessEnabled(isFileAccessEnabled);
3376 }
3377 
OnLineImageAccessEnabled(bool isOnLineImageAccessEnabled)3378 void JSWeb::OnLineImageAccessEnabled(bool isOnLineImageAccessEnabled)
3379 {
3380     WebModel::GetInstance()->SetOnLineImageAccessEnabled(isOnLineImageAccessEnabled);
3381 }
3382 
DomStorageAccessEnabled(bool isDomStorageAccessEnabled)3383 void JSWeb::DomStorageAccessEnabled(bool isDomStorageAccessEnabled)
3384 {
3385     WebModel::GetInstance()->SetDomStorageAccessEnabled(isDomStorageAccessEnabled);
3386 }
3387 
ImageAccessEnabled(bool isImageAccessEnabled)3388 void JSWeb::ImageAccessEnabled(bool isImageAccessEnabled)
3389 {
3390     WebModel::GetInstance()->SetImageAccessEnabled(isImageAccessEnabled);
3391 }
3392 
MixedMode(int32_t mixedMode)3393 void JSWeb::MixedMode(int32_t mixedMode)
3394 {
3395     auto mixedContentMode = MixedModeContent::MIXED_CONTENT_NEVER_ALLOW;
3396     switch (mixedMode) {
3397         case 0:
3398             mixedContentMode = MixedModeContent::MIXED_CONTENT_ALWAYS_ALLOW;
3399             break;
3400         case 1:
3401             mixedContentMode = MixedModeContent::MIXED_CONTENT_COMPATIBILITY_MODE;
3402             break;
3403         default:
3404             mixedContentMode = MixedModeContent::MIXED_CONTENT_NEVER_ALLOW;
3405             break;
3406     }
3407     WebModel::GetInstance()->SetMixedMode(mixedContentMode);
3408 }
3409 
ZoomAccessEnabled(bool isZoomAccessEnabled)3410 void JSWeb::ZoomAccessEnabled(bool isZoomAccessEnabled)
3411 {
3412     WebModel::GetInstance()->SetZoomAccessEnabled(isZoomAccessEnabled);
3413 }
3414 
EnableNativeEmbedMode(bool isEmbedModeEnabled)3415 void JSWeb::EnableNativeEmbedMode(bool isEmbedModeEnabled)
3416 {
3417     WebModel::GetInstance()->SetNativeEmbedModeEnabled(isEmbedModeEnabled);
3418 }
3419 
RegisterNativeEmbedRule(const std::string & tag,const std::string & type)3420 void JSWeb::RegisterNativeEmbedRule(const std::string& tag, const std::string& type)
3421 {
3422     WebModel::GetInstance()->RegisterNativeEmbedRule(tag, type);
3423 }
3424 
GeolocationAccessEnabled(bool isGeolocationAccessEnabled)3425 void JSWeb::GeolocationAccessEnabled(bool isGeolocationAccessEnabled)
3426 {
3427     WebModel::GetInstance()->SetGeolocationAccessEnabled(isGeolocationAccessEnabled);
3428 }
3429 
JavaScriptProxy(const JSCallbackInfo & args)3430 void JSWeb::JavaScriptProxy(const JSCallbackInfo& args)
3431 {
3432 #if !defined(ANDROID_PLATFORM) && !defined(IOS_PLATFORM)
3433     if (args.Length() < 1 || !args[0]->IsObject()) {
3434         return;
3435     }
3436     auto paramObject = JSRef<JSObject>::Cast(args[0]);
3437     auto controllerObj = paramObject->GetProperty("controller");
3438     auto object = JSRef<JSVal>::Cast(paramObject->GetProperty("object"));
3439     auto name = JSRef<JSVal>::Cast(paramObject->GetProperty("name"));
3440     auto methodList = JSRef<JSVal>::Cast(paramObject->GetProperty("methodList"));
3441     auto asyncMethodList = JSRef<JSVal>::Cast(paramObject->GetProperty("asyncMethodList"));
3442     auto permission = JSRef<JSVal>::Cast(paramObject->GetProperty("permission"));
3443     if (!controllerObj->IsObject()) {
3444         return;
3445     }
3446     auto controller = JSRef<JSObject>::Cast(controllerObj);
3447     auto jsProxyFunction = controller->GetProperty("jsProxy");
3448     if (jsProxyFunction->IsFunction()) {
3449         auto jsProxyCallback = [webviewController = controller, func = JSRef<JSFunc>::Cast(jsProxyFunction), object,
3450                                    name, methodList, asyncMethodList, permission]() {
3451             JSRef<JSVal> argv[] = { object, name, methodList, asyncMethodList, permission };
3452             func->Call(webviewController, 5, argv);
3453         };
3454 
3455         WebModel::GetInstance()->SetJsProxyCallback(jsProxyCallback);
3456     }
3457     auto jsWebController = controller->Unwrap<JSWebController>();
3458     if (jsWebController) {
3459         jsWebController->SetJavascriptInterface(args);
3460     }
3461 #endif
3462 }
3463 
UserAgent(const std::string & userAgent)3464 void JSWeb::UserAgent(const std::string& userAgent)
3465 {
3466     WebModel::GetInstance()->SetUserAgent(userAgent);
3467 }
3468 
RenderExitedEventToJSValue(const RenderExitedEvent & eventInfo)3469 JSRef<JSVal> RenderExitedEventToJSValue(const RenderExitedEvent& eventInfo)
3470 {
3471     JSRef<JSObject> obj = JSRef<JSObject>::New();
3472     obj->SetProperty("renderExitReason", eventInfo.GetExitedReason());
3473     return JSRef<JSVal>::Cast(obj);
3474 }
3475 
RefreshAccessedHistoryEventToJSValue(const RefreshAccessedHistoryEvent & eventInfo)3476 JSRef<JSVal> RefreshAccessedHistoryEventToJSValue(const RefreshAccessedHistoryEvent& eventInfo)
3477 {
3478     JSRef<JSObject> obj = JSRef<JSObject>::New();
3479     obj->SetProperty("url", eventInfo.GetVisitedUrl());
3480     obj->SetProperty("isRefreshed", eventInfo.IsRefreshed());
3481     return JSRef<JSVal>::Cast(obj);
3482 }
3483 
OnRenderExited(const JSCallbackInfo & args)3484 void JSWeb::OnRenderExited(const JSCallbackInfo& args)
3485 {
3486     if (!args[0]->IsFunction()) {
3487         return;
3488     }
3489     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3490     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<RenderExitedEvent, 1>>(
3491         JSRef<JSFunc>::Cast(args[0]), RenderExitedEventToJSValue);
3492     auto instanceId = Container::CurrentId();
3493     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
3494                           const BaseEventInfo* info) {
3495         ContainerScope scope(instanceId);
3496         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
3497         auto pipelineContext = PipelineContext::GetCurrentContext();
3498         CHECK_NULL_VOID(pipelineContext);
3499         pipelineContext->UpdateCurrentActiveNode(node);
3500         auto* eventInfo = TypeInfoHelper::DynamicCast<RenderExitedEvent>(info);
3501         func->Execute(*eventInfo);
3502     };
3503     WebModel::GetInstance()->SetRenderExitedId(jsCallback);
3504 }
3505 
OnRefreshAccessedHistory(const JSCallbackInfo & args)3506 void JSWeb::OnRefreshAccessedHistory(const JSCallbackInfo& args)
3507 {
3508     if (!args[0]->IsFunction()) {
3509         return;
3510     }
3511     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3512     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<RefreshAccessedHistoryEvent, 1>>(
3513         JSRef<JSFunc>::Cast(args[0]), RefreshAccessedHistoryEventToJSValue);
3514     auto instanceId = Container::CurrentId();
3515     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
3516                           const BaseEventInfo* info) {
3517         ContainerScope scope(instanceId);
3518         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
3519         auto pipelineContext = PipelineContext::GetCurrentContext();
3520         CHECK_NULL_VOID(pipelineContext);
3521         pipelineContext->UpdateCurrentActiveNode(node);
3522         auto* eventInfo = TypeInfoHelper::DynamicCast<RefreshAccessedHistoryEvent>(info);
3523         func->Execute(*eventInfo);
3524     };
3525     WebModel::GetInstance()->SetRefreshAccessedHistoryId(jsCallback);
3526 }
3527 
CacheMode(int32_t cacheMode)3528 void JSWeb::CacheMode(int32_t cacheMode)
3529 {
3530     auto mode = WebCacheMode::DEFAULT;
3531     switch (cacheMode) {
3532         case 0:
3533             mode = WebCacheMode::DEFAULT;
3534             break;
3535         case 1:
3536             mode = WebCacheMode::USE_CACHE_ELSE_NETWORK;
3537             break;
3538         case 2:
3539             mode = WebCacheMode::USE_NO_CACHE;
3540             break;
3541         case 3:
3542             mode = WebCacheMode::USE_CACHE_ONLY;
3543             break;
3544         default:
3545             mode = WebCacheMode::DEFAULT;
3546             break;
3547     }
3548     WebModel::GetInstance()->SetCacheMode(mode);
3549 }
3550 
OverScrollMode(int overScrollMode)3551 void JSWeb::OverScrollMode(int overScrollMode)
3552 {
3553     auto mode = OverScrollMode::NEVER;
3554     switch (overScrollMode) {
3555         case 0:
3556             mode = OverScrollMode::NEVER;
3557             break;
3558         case 1:
3559             mode = OverScrollMode::ALWAYS;
3560             break;
3561         default:
3562             mode = OverScrollMode::NEVER;
3563             break;
3564     }
3565     WebModel::GetInstance()->SetOverScrollMode(mode);
3566 }
3567 
BlurOnKeyboardHideMode(int blurOnKeyboardHideMode)3568 void JSWeb::BlurOnKeyboardHideMode(int blurOnKeyboardHideMode)
3569 {
3570     auto mode = BlurOnKeyboardHideMode::SILENT;
3571     switch (blurOnKeyboardHideMode) {
3572         case 0:
3573             mode = BlurOnKeyboardHideMode::SILENT;
3574             break;
3575         case 1:
3576             mode = BlurOnKeyboardHideMode::BLUR;
3577             break;
3578         default:
3579             mode = BlurOnKeyboardHideMode::SILENT;
3580             break;
3581     }
3582     WebModel::GetInstance()->SetBlurOnKeyboardHideMode(mode);
3583 }
3584 
OverviewModeAccess(bool isOverviewModeAccessEnabled)3585 void JSWeb::OverviewModeAccess(bool isOverviewModeAccessEnabled)
3586 {
3587     WebModel::GetInstance()->SetOverviewModeAccessEnabled(isOverviewModeAccessEnabled);
3588 }
3589 
FileFromUrlAccess(bool isFileFromUrlAccessEnabled)3590 void JSWeb::FileFromUrlAccess(bool isFileFromUrlAccessEnabled)
3591 {
3592     WebModel::GetInstance()->SetFileFromUrlAccessEnabled(isFileFromUrlAccessEnabled);
3593 }
3594 
DatabaseAccess(bool isDatabaseAccessEnabled)3595 void JSWeb::DatabaseAccess(bool isDatabaseAccessEnabled)
3596 {
3597     WebModel::GetInstance()->SetDatabaseAccessEnabled(isDatabaseAccessEnabled);
3598 }
3599 
TextZoomRatio(int32_t textZoomRatioNum)3600 void JSWeb::TextZoomRatio(int32_t textZoomRatioNum)
3601 {
3602     WebModel::GetInstance()->SetTextZoomRatio(textZoomRatioNum);
3603 }
3604 
WebDebuggingAccessEnabled(bool isWebDebuggingAccessEnabled)3605 void JSWeb::WebDebuggingAccessEnabled(bool isWebDebuggingAccessEnabled)
3606 {
3607     WebModel::GetInstance()->SetWebDebuggingAccessEnabled(isWebDebuggingAccessEnabled);
3608 }
3609 
OnMouse(const JSCallbackInfo & args)3610 void JSWeb::OnMouse(const JSCallbackInfo& args)
3611 {
3612     if (args.Length() < 1 || !args[0]->IsFunction()) {
3613         return;
3614     }
3615 
3616     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3617     RefPtr<JsClickFunction> jsOnMouseFunc = AceType::MakeRefPtr<JsClickFunction>(JSRef<JSFunc>::Cast(args[0]));
3618     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsOnMouseFunc), node = frameNode](
3619                           MouseInfo& info) {
3620         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
3621         auto pipelineContext = PipelineContext::GetCurrentContext();
3622         CHECK_NULL_VOID(pipelineContext);
3623         pipelineContext->UpdateCurrentActiveNode(node);
3624         func->Execute(info);
3625     };
3626     WebModel::GetInstance()->SetOnMouseEvent(jsCallback);
3627 }
3628 
ResourceLoadEventToJSValue(const ResourceLoadEvent & eventInfo)3629 JSRef<JSVal> ResourceLoadEventToJSValue(const ResourceLoadEvent& eventInfo)
3630 {
3631     JSRef<JSObject> obj = JSRef<JSObject>::New();
3632     obj->SetProperty("url", eventInfo.GetOnResourceLoadUrl());
3633     return JSRef<JSVal>::Cast(obj);
3634 }
3635 
OnResourceLoad(const JSCallbackInfo & args)3636 void JSWeb::OnResourceLoad(const JSCallbackInfo& args)
3637 {
3638     if (args.Length() < 1 || !args[0]->IsFunction()) {
3639         return;
3640     }
3641     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3642     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<ResourceLoadEvent, 1>>(
3643         JSRef<JSFunc>::Cast(args[0]), ResourceLoadEventToJSValue);
3644     auto instanceId = Container::CurrentId();
3645     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
3646                           const BaseEventInfo* info) {
3647         ContainerScope scope(instanceId);
3648         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
3649         auto pipelineContext = PipelineContext::GetCurrentContext();
3650         CHECK_NULL_VOID(pipelineContext);
3651         pipelineContext->UpdateCurrentActiveNode(node);
3652         auto* eventInfo = TypeInfoHelper::DynamicCast<ResourceLoadEvent>(info);
3653         func->Execute(*eventInfo);
3654     };
3655     WebModel::GetInstance()->SetResourceLoadId(jsCallback);
3656 }
3657 
ScaleChangeEventToJSValue(const ScaleChangeEvent & eventInfo)3658 JSRef<JSVal> ScaleChangeEventToJSValue(const ScaleChangeEvent& eventInfo)
3659 {
3660     JSRef<JSObject> obj = JSRef<JSObject>::New();
3661     obj->SetProperty("oldScale", eventInfo.GetOnScaleChangeOldScale());
3662     obj->SetProperty("newScale", eventInfo.GetOnScaleChangeNewScale());
3663     return JSRef<JSVal>::Cast(obj);
3664 }
3665 
OnScaleChange(const JSCallbackInfo & args)3666 void JSWeb::OnScaleChange(const JSCallbackInfo& args)
3667 {
3668     if (args.Length() < 1 || !args[0]->IsFunction()) {
3669         return;
3670     }
3671     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3672     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<ScaleChangeEvent, 1>>(
3673         JSRef<JSFunc>::Cast(args[0]), ScaleChangeEventToJSValue);
3674     auto instanceId = Container::CurrentId();
3675     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
3676                           const BaseEventInfo* info) {
3677         ContainerScope scope(instanceId);
3678         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
3679         auto pipelineContext = PipelineContext::GetCurrentContext();
3680         CHECK_NULL_VOID(pipelineContext);
3681         pipelineContext->UpdateCurrentActiveNode(node);
3682         auto* eventInfo = TypeInfoHelper::DynamicCast<ScaleChangeEvent>(info);
3683         func->Execute(*eventInfo);
3684     };
3685     WebModel::GetInstance()->SetScaleChangeId(jsCallback);
3686 }
3687 
ScrollEventToJSValue(const WebOnScrollEvent & eventInfo)3688 JSRef<JSVal> ScrollEventToJSValue(const WebOnScrollEvent& eventInfo)
3689 {
3690     JSRef<JSObject> obj = JSRef<JSObject>::New();
3691     obj->SetProperty("xOffset", eventInfo.GetX());
3692     obj->SetProperty("yOffset", eventInfo.GetY());
3693     return JSRef<JSVal>::Cast(obj);
3694 }
3695 
OnScroll(const JSCallbackInfo & args)3696 void JSWeb::OnScroll(const JSCallbackInfo& args)
3697 {
3698     if (args.Length() < 1 || !args[0]->IsFunction()) {
3699         return;
3700     }
3701 
3702     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3703     auto jsFunc =
3704         AceType::MakeRefPtr<JsEventFunction<WebOnScrollEvent, 1>>(JSRef<JSFunc>::Cast(args[0]), ScrollEventToJSValue);
3705     auto instanceId = Container::CurrentId();
3706     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
3707                           const BaseEventInfo* info) {
3708         ContainerScope scope(instanceId);
3709         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
3710         auto pipelineContext = PipelineContext::GetCurrentContext();
3711         CHECK_NULL_VOID(pipelineContext);
3712         pipelineContext->UpdateCurrentActiveNode(node);
3713         auto* eventInfo = TypeInfoHelper::DynamicCast<WebOnScrollEvent>(info);
3714         func->Execute(*eventInfo);
3715     };
3716     WebModel::GetInstance()->SetScrollId(jsCallback);
3717 }
3718 
PermissionRequestEventToJSValue(const WebPermissionRequestEvent & eventInfo)3719 JSRef<JSVal> PermissionRequestEventToJSValue(const WebPermissionRequestEvent& eventInfo)
3720 {
3721     JSRef<JSObject> obj = JSRef<JSObject>::New();
3722     JSRef<JSObject> permissionObj = JSClass<JSWebPermissionRequest>::NewInstance();
3723     auto permissionEvent = Referenced::Claim(permissionObj->Unwrap<JSWebPermissionRequest>());
3724     permissionEvent->SetEvent(eventInfo);
3725     obj->SetPropertyObject("request", permissionObj);
3726     return JSRef<JSVal>::Cast(obj);
3727 }
3728 
OnPermissionRequest(const JSCallbackInfo & args)3729 void JSWeb::OnPermissionRequest(const JSCallbackInfo& args)
3730 {
3731     if (args.Length() < 1 || !args[0]->IsFunction()) {
3732         return;
3733     }
3734     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3735     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<WebPermissionRequestEvent, 1>>(
3736         JSRef<JSFunc>::Cast(args[0]), PermissionRequestEventToJSValue);
3737     auto instanceId = Container::CurrentId();
3738     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
3739                           const BaseEventInfo* info) {
3740         ContainerScope scope(instanceId);
3741         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
3742         auto pipelineContext = PipelineContext::GetCurrentContext();
3743         CHECK_NULL_VOID(pipelineContext);
3744         pipelineContext->UpdateCurrentActiveNode(node);
3745         auto* eventInfo = TypeInfoHelper::DynamicCast<WebPermissionRequestEvent>(info);
3746         func->Execute(*eventInfo);
3747     };
3748     WebModel::GetInstance()->SetPermissionRequestEventId(jsCallback);
3749 }
3750 
ScreenCaptureRequestEventToJSValue(const WebScreenCaptureRequestEvent & eventInfo)3751 JSRef<JSVal> ScreenCaptureRequestEventToJSValue(const WebScreenCaptureRequestEvent& eventInfo)
3752 {
3753     JSRef<JSObject> obj = JSRef<JSObject>::New();
3754     JSRef<JSObject> requestObj = JSClass<JSScreenCaptureRequest>::NewInstance();
3755     auto requestEvent = Referenced::Claim(requestObj->Unwrap<JSScreenCaptureRequest>());
3756     requestEvent->SetEvent(eventInfo);
3757     obj->SetPropertyObject("handler", requestObj);
3758     return JSRef<JSVal>::Cast(obj);
3759 }
3760 
OnScreenCaptureRequest(const JSCallbackInfo & args)3761 void JSWeb::OnScreenCaptureRequest(const JSCallbackInfo& args)
3762 {
3763     if (args.Length() < 1 || !args[0]->IsFunction()) {
3764         return;
3765     }
3766     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3767     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<WebScreenCaptureRequestEvent, 1>>(
3768         JSRef<JSFunc>::Cast(args[0]), ScreenCaptureRequestEventToJSValue);
3769     auto instanceId = Container::CurrentId();
3770     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
3771                           const BaseEventInfo* info) {
3772         ContainerScope scope(instanceId);
3773         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
3774         auto pipelineContext = PipelineContext::GetCurrentContext();
3775         CHECK_NULL_VOID(pipelineContext);
3776         pipelineContext->UpdateCurrentActiveNode(node);
3777         auto* eventInfo = TypeInfoHelper::DynamicCast<WebScreenCaptureRequestEvent>(info);
3778         func->Execute(*eventInfo);
3779     };
3780     WebModel::GetInstance()->SetScreenCaptureRequestEventId(jsCallback);
3781 }
3782 
BackgroundColor(const JSCallbackInfo & info)3783 void JSWeb::BackgroundColor(const JSCallbackInfo& info)
3784 {
3785     if (info.Length() < 1) {
3786         return;
3787     }
3788     Color backgroundColor;
3789     if (!ParseJsColor(info[0], backgroundColor)) {
3790         backgroundColor = WebModel::GetInstance()->GetDefaultBackgroundColor();
3791     }
3792     WebModel::GetInstance()->SetBackgroundColor(backgroundColor);
3793 }
3794 
InitialScale(float scale)3795 void JSWeb::InitialScale(float scale)
3796 {
3797     WebModel::GetInstance()->InitialScale(scale);
3798 }
3799 
Password(bool password)3800 void JSWeb::Password(bool password) {}
3801 
TableData(bool tableData)3802 void JSWeb::TableData(bool tableData) {}
3803 
OnFileSelectorShowAbandoned(const JSCallbackInfo & args)3804 void JSWeb::OnFileSelectorShowAbandoned(const JSCallbackInfo& args) {}
3805 
WideViewModeAccess(const JSCallbackInfo & args)3806 void JSWeb::WideViewModeAccess(const JSCallbackInfo& args) {}
3807 
WebDebuggingAccess(const JSCallbackInfo & args)3808 void JSWeb::WebDebuggingAccess(const JSCallbackInfo& args) {}
3809 
OnSearchResultReceive(const JSCallbackInfo & args)3810 void JSWeb::OnSearchResultReceive(const JSCallbackInfo& args)
3811 {
3812     if (!args[0]->IsFunction()) {
3813         return;
3814     }
3815     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3816     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<SearchResultReceiveEvent, 1>>(
3817         JSRef<JSFunc>::Cast(args[0]), SearchResultReceiveEventToJSValue);
3818     auto instanceId = Container::CurrentId();
3819     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
3820                           const BaseEventInfo* info) {
3821         ContainerScope scope(instanceId);
3822         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
3823         auto pipelineContext = PipelineContext::GetCurrentContext();
3824         CHECK_NULL_VOID(pipelineContext);
3825         pipelineContext->UpdateCurrentActiveNode(node);
3826         auto* eventInfo = TypeInfoHelper::DynamicCast<SearchResultReceiveEvent>(info);
3827         func->Execute(*eventInfo);
3828     };
3829     WebModel::GetInstance()->SetSearchResultReceiveEventId(jsCallback);
3830 }
3831 
JsOnDragStart(const JSCallbackInfo & info)3832 void JSWeb::JsOnDragStart(const JSCallbackInfo& info)
3833 {
3834     if (info.Length() < 1 || !info[0]->IsFunction()) {
3835         return;
3836     }
3837 
3838     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3839     RefPtr<JsDragFunction> jsOnDragStartFunc = AceType::MakeRefPtr<JsDragFunction>(JSRef<JSFunc>::Cast(info[0]));
3840     auto onDragStartId = [execCtx = info.GetExecutionContext(), func = std::move(jsOnDragStartFunc), node = frameNode](
3841                              const RefPtr<DragEvent>& info, const std::string& extraParams) -> NG::DragDropBaseInfo {
3842         NG::DragDropBaseInfo itemInfo;
3843         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx, itemInfo);
3844         auto pipelineContext = PipelineContext::GetCurrentContext();
3845         CHECK_NULL_RETURN(pipelineContext, itemInfo);
3846         pipelineContext->UpdateCurrentActiveNode(node);
3847         auto ret = func->Execute(info, extraParams);
3848         if (!ret->IsObject()) {
3849             return itemInfo;
3850         }
3851         auto component = ParseDragNode(ret);
3852         if (component) {
3853             itemInfo.node = component;
3854             return itemInfo;
3855         }
3856 
3857         auto builderObj = JSRef<JSObject>::Cast(ret);
3858 #if !defined(WINDOWS_PLATFORM) and !defined(MAC_PLATFORM)
3859         auto pixmap_impl = builderObj->GetProperty("pixelMap");
3860         itemInfo.pixelMap = CreatePixelMapFromNapiValue(pixmap_impl);
3861 #endif
3862 
3863 #if defined(PIXEL_MAP_SUPPORTED)
3864         auto pixmap_ng = builderObj->GetProperty("pixelMap");
3865         itemInfo.pixelMap = CreatePixelMapFromNapiValue(pixmap_ng);
3866 #endif
3867         auto extraInfo = builderObj->GetProperty("extraInfo");
3868         ParseJsString(extraInfo, itemInfo.extraInfo);
3869         component = ParseDragNode(builderObj->GetProperty("builder"));
3870         itemInfo.node = component;
3871         return itemInfo;
3872     };
3873 
3874     WebModel::GetInstance()->SetOnDragStart(std::move(onDragStartId));
3875 }
3876 
JsOnDragEnter(const JSCallbackInfo & info)3877 void JSWeb::JsOnDragEnter(const JSCallbackInfo& info)
3878 {
3879     if (info.Length() < 1 || !info[0]->IsFunction()) {
3880         return;
3881     }
3882 
3883     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3884     RefPtr<JsDragFunction> jsOnDragEnterFunc = AceType::MakeRefPtr<JsDragFunction>(JSRef<JSFunc>::Cast(info[0]));
3885     auto onDragEnterId = [execCtx = info.GetExecutionContext(), func = std::move(jsOnDragEnterFunc), node = frameNode](
3886                              const RefPtr<DragEvent>& info, const std::string& extraParams) {
3887         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
3888         ACE_SCORING_EVENT("onDragEnter");
3889         auto pipelineContext = PipelineContext::GetCurrentContext();
3890         CHECK_NULL_VOID(pipelineContext);
3891         pipelineContext->UpdateCurrentActiveNode(node);
3892         func->Execute(info, extraParams);
3893     };
3894 
3895     WebModel::GetInstance()->SetOnDragEnter(onDragEnterId);
3896 }
3897 
JsOnDragMove(const JSCallbackInfo & info)3898 void JSWeb::JsOnDragMove(const JSCallbackInfo& info)
3899 {
3900     if (info.Length() < 1 || !info[0]->IsFunction()) {
3901         return;
3902     }
3903 
3904     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3905     RefPtr<JsDragFunction> jsOnDragMoveFunc = AceType::MakeRefPtr<JsDragFunction>(JSRef<JSFunc>::Cast(info[0]));
3906     auto onDragMoveId = [execCtx = info.GetExecutionContext(), func = std::move(jsOnDragMoveFunc), node = frameNode](
3907                             const RefPtr<DragEvent>& info, const std::string& extraParams) {
3908         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
3909         ACE_SCORING_EVENT("onDragMove");
3910         auto pipelineContext = PipelineContext::GetCurrentContext();
3911         CHECK_NULL_VOID(pipelineContext);
3912         pipelineContext->UpdateCurrentActiveNode(node);
3913         func->Execute(info, extraParams);
3914     };
3915 
3916     WebModel::GetInstance()->SetOnDragMove(onDragMoveId);
3917 }
3918 
JsOnDragLeave(const JSCallbackInfo & info)3919 void JSWeb::JsOnDragLeave(const JSCallbackInfo& info)
3920 {
3921     if (info.Length() < 1 || !info[0]->IsFunction()) {
3922         return;
3923     }
3924 
3925     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3926     RefPtr<JsDragFunction> jsOnDragLeaveFunc = AceType::MakeRefPtr<JsDragFunction>(JSRef<JSFunc>::Cast(info[0]));
3927     auto onDragLeaveId = [execCtx = info.GetExecutionContext(), func = std::move(jsOnDragLeaveFunc), node = frameNode](
3928                              const RefPtr<DragEvent>& info, const std::string& extraParams) {
3929         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
3930         ACE_SCORING_EVENT("onDragLeave");
3931         auto pipelineContext = PipelineContext::GetCurrentContext();
3932         CHECK_NULL_VOID(pipelineContext);
3933         pipelineContext->UpdateCurrentActiveNode(node);
3934         func->Execute(info, extraParams);
3935     };
3936 
3937     WebModel::GetInstance()->SetOnDragLeave(onDragLeaveId);
3938 }
3939 
JsOnDrop(const JSCallbackInfo & info)3940 void JSWeb::JsOnDrop(const JSCallbackInfo& info)
3941 {
3942     if (info.Length() < 1 || !info[0]->IsFunction()) {
3943         return;
3944     }
3945 
3946     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
3947     RefPtr<JsDragFunction> jsOnDropFunc = AceType::MakeRefPtr<JsDragFunction>(JSRef<JSFunc>::Cast(info[0]));
3948     auto onDropId = [execCtx = info.GetExecutionContext(), func = std::move(jsOnDropFunc), node = frameNode](
3949                         const RefPtr<DragEvent>& info, const std::string& extraParams) {
3950         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
3951         ACE_SCORING_EVENT("onDrop");
3952         auto pipelineContext = PipelineContext::GetCurrentContext();
3953         CHECK_NULL_VOID(pipelineContext);
3954         pipelineContext->UpdateCurrentActiveNode(node);
3955         func->Execute(info, extraParams);
3956     };
3957 
3958     WebModel::GetInstance()->SetOnDrop(onDropId);
3959 }
3960 
PinchSmoothModeEnabled(bool isPinchSmoothModeEnabled)3961 void JSWeb::PinchSmoothModeEnabled(bool isPinchSmoothModeEnabled)
3962 {
3963     WebModel::GetInstance()->SetPinchSmoothModeEnabled(isPinchSmoothModeEnabled);
3964 }
3965 
WindowNewEventToJSValue(const WebWindowNewEvent & eventInfo)3966 JSRef<JSVal> WindowNewEventToJSValue(const WebWindowNewEvent& eventInfo)
3967 {
3968     JSRef<JSObject> obj = JSRef<JSObject>::New();
3969     obj->SetProperty("isAlert", eventInfo.IsAlert());
3970     obj->SetProperty("isUserTrigger", eventInfo.IsUserTrigger());
3971     obj->SetProperty("targetUrl", eventInfo.GetTargetUrl());
3972     JSRef<JSObject> handlerObj = JSClass<JSWebWindowNewHandler>::NewInstance();
3973     auto handler = Referenced::Claim(handlerObj->Unwrap<JSWebWindowNewHandler>());
3974     handler->SetEvent(eventInfo);
3975     obj->SetPropertyObject("handler", handlerObj);
3976     return JSRef<JSVal>::Cast(obj);
3977 }
3978 
HandleWindowNewEvent(const WebWindowNewEvent * eventInfo)3979 bool HandleWindowNewEvent(const WebWindowNewEvent* eventInfo)
3980 {
3981     if (eventInfo == nullptr) {
3982         return false;
3983     }
3984     auto handler = eventInfo->GetWebWindowNewHandler();
3985     if (handler && !handler->IsFrist()) {
3986         int32_t parentId = -1;
3987         auto controller = JSWebWindowNewHandler::PopController(handler->GetId(), &parentId);
3988         if (!controller.IsEmpty()) {
3989             auto getWebIdFunction = controller->GetProperty("innerGetWebId");
3990             if (getWebIdFunction->IsFunction()) {
3991                 auto func = JSRef<JSFunc>::Cast(getWebIdFunction);
3992                 auto webId = func->Call(controller, 0, {});
3993                 handler->SetWebController(webId->ToNumber<int32_t>());
3994             }
3995             auto completeWindowNewFunction = controller->GetProperty("innerCompleteWindowNew");
3996             if (completeWindowNewFunction->IsFunction()) {
3997                 auto func = JSRef<JSFunc>::Cast(completeWindowNewFunction);
3998                 JSRef<JSVal> argv[] = { JSRef<JSVal>::Make(ToJSValue(parentId)) };
3999                 func->Call(controller, 1, argv);
4000             }
4001         }
4002         return false;
4003     }
4004     return true;
4005 }
4006 
OnWindowNew(const JSCallbackInfo & args)4007 void JSWeb::OnWindowNew(const JSCallbackInfo& args)
4008 {
4009     if (args.Length() < 1 || !args[0]->IsFunction()) {
4010         return;
4011     }
4012 
4013     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
4014     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<WebWindowNewEvent, 1>>(
4015         JSRef<JSFunc>::Cast(args[0]), WindowNewEventToJSValue);
4016     auto instanceId = Container::CurrentId();
4017     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
4018                           const std::shared_ptr<BaseEventInfo>& info) {
4019         ContainerScope scope(instanceId);
4020         ACE_SCORING_EVENT("OnWindowNew CallBack");
4021         auto pipelineContext = PipelineContext::GetCurrentContext();
4022         CHECK_NULL_VOID(pipelineContext);
4023         pipelineContext->UpdateCurrentActiveNode(node);
4024         auto* eventInfo = TypeInfoHelper::DynamicCast<WebWindowNewEvent>(info.get());
4025         if (!func || !HandleWindowNewEvent(eventInfo)) {
4026             return;
4027         }
4028         func->Execute(*eventInfo);
4029     };
4030     WebModel::GetInstance()->SetWindowNewEvent(jsCallback);
4031 }
4032 
WindowExitEventToJSValue(const WebWindowExitEvent & eventInfo)4033 JSRef<JSVal> WindowExitEventToJSValue(const WebWindowExitEvent& eventInfo)
4034 {
4035     JSRef<JSObject> obj = JSRef<JSObject>::New();
4036     return JSRef<JSVal>::Cast(obj);
4037 }
4038 
OnWindowExit(const JSCallbackInfo & args)4039 void JSWeb::OnWindowExit(const JSCallbackInfo& args)
4040 {
4041     if (args.Length() < 1 || !args[0]->IsFunction()) {
4042         return;
4043     }
4044     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
4045     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<WebWindowExitEvent, 1>>(
4046         JSRef<JSFunc>::Cast(args[0]), WindowExitEventToJSValue);
4047     auto instanceId = Container::CurrentId();
4048     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
4049                           const BaseEventInfo* info) {
4050         ContainerScope scope(instanceId);
4051         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
4052         auto pipelineContext = PipelineContext::GetCurrentContext();
4053         CHECK_NULL_VOID(pipelineContext);
4054         pipelineContext->UpdateCurrentActiveNode(node);
4055         auto* eventInfo = TypeInfoHelper::DynamicCast<WebWindowExitEvent>(info);
4056         func->Execute(*eventInfo);
4057     };
4058     WebModel::GetInstance()->SetWindowExitEventId(jsCallback);
4059 }
4060 
MultiWindowAccessEnabled(bool isMultiWindowAccessEnable)4061 void JSWeb::MultiWindowAccessEnabled(bool isMultiWindowAccessEnable)
4062 {
4063     WebModel::GetInstance()->SetMultiWindowAccessEnabled(isMultiWindowAccessEnable);
4064 }
4065 
AllowWindowOpenMethod(bool isAllowWindowOpenMethod)4066 void JSWeb::AllowWindowOpenMethod(bool isAllowWindowOpenMethod)
4067 {
4068     WebModel::GetInstance()->SetAllowWindowOpenMethod(isAllowWindowOpenMethod);
4069 }
4070 
WebCursiveFont(const std::string & cursiveFontFamily)4071 void JSWeb::WebCursiveFont(const std::string& cursiveFontFamily)
4072 {
4073     WebModel::GetInstance()->SetWebCursiveFont(cursiveFontFamily);
4074 }
4075 
WebFantasyFont(const std::string & fantasyFontFamily)4076 void JSWeb::WebFantasyFont(const std::string& fantasyFontFamily)
4077 {
4078     WebModel::GetInstance()->SetWebFantasyFont(fantasyFontFamily);
4079 }
4080 
WebFixedFont(const std::string & fixedFontFamily)4081 void JSWeb::WebFixedFont(const std::string& fixedFontFamily)
4082 {
4083     WebModel::GetInstance()->SetWebFixedFont(fixedFontFamily);
4084 }
4085 
WebSansSerifFont(const std::string & sansSerifFontFamily)4086 void JSWeb::WebSansSerifFont(const std::string& sansSerifFontFamily)
4087 {
4088     WebModel::GetInstance()->SetWebSansSerifFont(sansSerifFontFamily);
4089 }
4090 
WebSerifFont(const std::string & serifFontFamily)4091 void JSWeb::WebSerifFont(const std::string& serifFontFamily)
4092 {
4093     WebModel::GetInstance()->SetWebSerifFont(serifFontFamily);
4094 }
4095 
WebStandardFont(const std::string & standardFontFamily)4096 void JSWeb::WebStandardFont(const std::string& standardFontFamily)
4097 {
4098     WebModel::GetInstance()->SetWebStandardFont(standardFontFamily);
4099 }
4100 
DefaultFixedFontSize(int32_t defaultFixedFontSize)4101 void JSWeb::DefaultFixedFontSize(int32_t defaultFixedFontSize)
4102 {
4103     WebModel::GetInstance()->SetDefaultFixedFontSize(defaultFixedFontSize);
4104 }
4105 
DefaultFontSize(int32_t defaultFontSize)4106 void JSWeb::DefaultFontSize(int32_t defaultFontSize)
4107 {
4108     WebModel::GetInstance()->SetDefaultFontSize(defaultFontSize);
4109 }
4110 
DefaultTextEncodingFormat(const JSCallbackInfo & args)4111 void JSWeb::DefaultTextEncodingFormat(const JSCallbackInfo& args)
4112 {
4113     if (args.Length() < 1 || !args[0]->IsString()) {
4114         return;
4115     }
4116     std::string textEncodingFormat = args[0]->ToString();
4117     EraseSpace(textEncodingFormat);
4118     if (textEncodingFormat.empty()) {
4119         WebModel::GetInstance()->SetDefaultTextEncodingFormat("UTF-8");
4120         return;
4121     }
4122     WebModel::GetInstance()->SetDefaultTextEncodingFormat(textEncodingFormat);
4123 }
4124 
MinFontSize(int32_t minFontSize)4125 void JSWeb::MinFontSize(int32_t minFontSize)
4126 {
4127     WebModel::GetInstance()->SetMinFontSize(minFontSize);
4128 }
4129 
MinLogicalFontSize(int32_t minLogicalFontSize)4130 void JSWeb::MinLogicalFontSize(int32_t minLogicalFontSize)
4131 {
4132     WebModel::GetInstance()->SetMinLogicalFontSize(minLogicalFontSize);
4133 }
4134 
BlockNetwork(bool isNetworkBlocked)4135 void JSWeb::BlockNetwork(bool isNetworkBlocked)
4136 {
4137     WebModel::GetInstance()->SetBlockNetwork(isNetworkBlocked);
4138 }
4139 
PageVisibleEventToJSValue(const PageVisibleEvent & eventInfo)4140 JSRef<JSVal> PageVisibleEventToJSValue(const PageVisibleEvent& eventInfo)
4141 {
4142     JSRef<JSObject> obj = JSRef<JSObject>::New();
4143     obj->SetProperty("url", eventInfo.GetUrl());
4144     return JSRef<JSVal>::Cast(obj);
4145 }
4146 
OnPageVisible(const JSCallbackInfo & args)4147 void JSWeb::OnPageVisible(const JSCallbackInfo& args)
4148 {
4149     TAG_LOGI(AceLogTag::ACE_WEB, "JSWeb::OnPageVisible init by developer");
4150     if (!args[0]->IsFunction()) {
4151         return;
4152     }
4153     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
4154     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<PageVisibleEvent, 1>>(
4155         JSRef<JSFunc>::Cast(args[0]), PageVisibleEventToJSValue);
4156 
4157     auto instanceId = Container::CurrentId();
4158     auto uiCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
4159                           const std::shared_ptr<BaseEventInfo>& info) {
4160         TAG_LOGI(AceLogTag::ACE_WEB, "JSWeb::OnPageVisible uiCallback enter");
4161         ContainerScope scope(instanceId);
4162         auto context = PipelineBase::GetCurrentContext();
4163         CHECK_NULL_VOID(context);
4164         context->UpdateCurrentActiveNode(node);
4165         context->PostAsyncEvent([execCtx, postFunc = func, info]() {
4166             JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
4167             TAG_LOGI(AceLogTag::ACE_WEB, "JSWeb::OnPageVisible async event execute");
4168             auto* eventInfo = TypeInfoHelper::DynamicCast<PageVisibleEvent>(info.get());
4169             postFunc->Execute(*eventInfo);
4170         }, "ArkUIWebPageVisible");
4171     };
4172     WebModel::GetInstance()->SetPageVisibleId(std::move(uiCallback));
4173 }
4174 
OnInterceptKeyEvent(const JSCallbackInfo & args)4175 void JSWeb::OnInterceptKeyEvent(const JSCallbackInfo& args)
4176 {
4177     if (args.Length() < 1 || !args[0]->IsFunction()) {
4178         return;
4179     }
4180 
4181     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
4182     RefPtr<JsKeyFunction> jsOnPreKeyEventFunc = AceType::MakeRefPtr<JsKeyFunction>(JSRef<JSFunc>::Cast(args[0]));
4183     auto uiCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsOnPreKeyEventFunc), node = frameNode](
4184                           KeyEventInfo& keyEventInfo) -> bool {
4185         bool result = false;
4186         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx, result);
4187         ACE_SCORING_EVENT("onPreKeyEvent");
4188         auto pipelineContext = PipelineContext::GetCurrentContext();
4189         CHECK_NULL_RETURN(pipelineContext, result);
4190         pipelineContext->UpdateCurrentActiveNode(node);
4191         JSRef<JSVal> obj = func->ExecuteWithValue(keyEventInfo);
4192         if (obj->IsBoolean()) {
4193             result = obj->ToBoolean();
4194         }
4195         return result;
4196     };
4197     WebModel::GetInstance()->SetOnInterceptKeyEventCallback(uiCallback);
4198 }
4199 
DataResubmittedEventToJSValue(const DataResubmittedEvent & eventInfo)4200 JSRef<JSVal> DataResubmittedEventToJSValue(const DataResubmittedEvent& eventInfo)
4201 {
4202     JSRef<JSObject> obj = JSRef<JSObject>::New();
4203     JSRef<JSObject> resultObj = JSClass<JSDataResubmitted>::NewInstance();
4204     auto jsDataResubmitted = Referenced::Claim(resultObj->Unwrap<JSDataResubmitted>());
4205     if (!jsDataResubmitted) {
4206         return JSRef<JSVal>::Cast(obj);
4207     }
4208     jsDataResubmitted->SetHandler(eventInfo.GetHandler());
4209     obj->SetPropertyObject("handler", resultObj);
4210     return JSRef<JSVal>::Cast(obj);
4211 }
4212 
OnDataResubmitted(const JSCallbackInfo & args)4213 void JSWeb::OnDataResubmitted(const JSCallbackInfo& args)
4214 {
4215     if (args.Length() < 1 || !args[0]->IsFunction()) {
4216         return;
4217     }
4218     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<DataResubmittedEvent, 1>>(
4219         JSRef<JSFunc>::Cast(args[0]), DataResubmittedEventToJSValue);
4220 
4221     auto instanceId = Container::CurrentId();
4222     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
4223     auto uiCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
4224                           const std::shared_ptr<BaseEventInfo>& info) {
4225         ContainerScope scope(instanceId);
4226         auto context = PipelineBase::GetCurrentContext();
4227         CHECK_NULL_VOID(context);
4228         context->UpdateCurrentActiveNode(node);
4229         context->PostSyncEvent([execCtx, postFunc = func, info]() {
4230             JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
4231             auto* eventInfo = TypeInfoHelper::DynamicCast<DataResubmittedEvent>(info.get());
4232             postFunc->Execute(*eventInfo);
4233         }, "ArkUIWebDataResubmitted");
4234     };
4235     WebModel::GetInstance()->SetOnDataResubmitted(uiCallback);
4236 }
4237 
GetPixelFormat(NWeb::ImageColorType colorType)4238 Media::PixelFormat GetPixelFormat(NWeb::ImageColorType colorType)
4239 {
4240     Media::PixelFormat pixelFormat;
4241     switch (colorType) {
4242         case NWeb::ImageColorType::COLOR_TYPE_UNKNOWN:
4243             pixelFormat = Media::PixelFormat::UNKNOWN;
4244             break;
4245         case NWeb::ImageColorType::COLOR_TYPE_RGBA_8888:
4246             pixelFormat = Media::PixelFormat::RGBA_8888;
4247             break;
4248         case NWeb::ImageColorType::COLOR_TYPE_BGRA_8888:
4249             pixelFormat = Media::PixelFormat::BGRA_8888;
4250             break;
4251         default:
4252             pixelFormat = Media::PixelFormat::UNKNOWN;
4253             break;
4254     }
4255     return pixelFormat;
4256 }
4257 
GetAlphaType(NWeb::ImageAlphaType alphaType)4258 Media::AlphaType GetAlphaType(NWeb::ImageAlphaType alphaType)
4259 {
4260     Media::AlphaType imageAlphaType;
4261     switch (alphaType) {
4262         case NWeb::ImageAlphaType::ALPHA_TYPE_UNKNOWN:
4263             imageAlphaType = Media::AlphaType::IMAGE_ALPHA_TYPE_UNKNOWN;
4264             break;
4265         case NWeb::ImageAlphaType::ALPHA_TYPE_OPAQUE:
4266             imageAlphaType = Media::AlphaType::IMAGE_ALPHA_TYPE_OPAQUE;
4267             break;
4268         case NWeb::ImageAlphaType::ALPHA_TYPE_PREMULTIPLIED:
4269             imageAlphaType = Media::AlphaType::IMAGE_ALPHA_TYPE_PREMUL;
4270             break;
4271         case NWeb::ImageAlphaType::ALPHA_TYPE_POSTMULTIPLIED:
4272             imageAlphaType = Media::AlphaType::IMAGE_ALPHA_TYPE_UNPREMUL;
4273             break;
4274         default:
4275             imageAlphaType = Media::AlphaType::IMAGE_ALPHA_TYPE_UNKNOWN;
4276             break;
4277     }
4278     return imageAlphaType;
4279 }
4280 
FaviconReceivedEventToJSValue(const FaviconReceivedEvent & eventInfo)4281 JSRef<JSObject> FaviconReceivedEventToJSValue(const FaviconReceivedEvent& eventInfo)
4282 {
4283     JSRef<JSObject> obj = JSRef<JSObject>::New();
4284     auto data = eventInfo.GetHandler()->GetData();
4285     size_t width = eventInfo.GetHandler()->GetWidth();
4286     size_t height = eventInfo.GetHandler()->GetHeight();
4287     int colorType = eventInfo.GetHandler()->GetColorType();
4288     int alphaType = eventInfo.GetHandler()->GetAlphaType();
4289 
4290     Media::InitializationOptions opt;
4291     opt.size.width = static_cast<int32_t>(width);
4292     opt.size.height = static_cast<int32_t>(height);
4293     opt.pixelFormat = GetPixelFormat(NWeb::ImageColorType(colorType));
4294     opt.alphaType = GetAlphaType(NWeb::ImageAlphaType(alphaType));
4295     opt.editable = true;
4296     auto pixelMap = Media::PixelMap::Create(opt);
4297     if (pixelMap == nullptr) {
4298         return JSRef<JSVal>::Cast(obj);
4299     }
4300     uint32_t stride = width << 2;
4301     uint64_t bufferSize = stride * height;
4302     pixelMap->WritePixels(static_cast<const uint8_t*>(data), bufferSize);
4303     std::shared_ptr<Media::PixelMap> pixelMapToJs(pixelMap.release());
4304     auto engine = EngineHelper::GetCurrentEngine();
4305     if (!engine) {
4306         return JSRef<JSVal>::Cast(obj);
4307     }
4308     NativeEngine* nativeEngine = engine->GetNativeEngine();
4309     napi_env env = reinterpret_cast<napi_env>(nativeEngine);
4310     napi_value napiValue = OHOS::Media::PixelMapNapi::CreatePixelMap(env, pixelMapToJs);
4311     auto jsPixelMap = JsConverter::ConvertNapiValueToJsVal(napiValue);
4312     obj->SetPropertyObject("favicon", jsPixelMap);
4313     return JSRef<JSObject>::Cast(obj);
4314 }
4315 
OnFaviconReceived(const JSCallbackInfo & args)4316 void JSWeb::OnFaviconReceived(const JSCallbackInfo& args)
4317 {
4318     if (args.Length() < 1 || !args[0]->IsFunction()) {
4319         return;
4320     }
4321     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
4322     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<FaviconReceivedEvent, 1>>(
4323         JSRef<JSFunc>::Cast(args[0]), FaviconReceivedEventToJSValue);
4324 
4325     auto instanceId = Container::CurrentId();
4326     auto uiCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
4327                           const std::shared_ptr<BaseEventInfo>& info) {
4328         ContainerScope scope(instanceId);
4329         auto context = PipelineBase::GetCurrentContext();
4330         CHECK_NULL_VOID(context);
4331         context->UpdateCurrentActiveNode(node);
4332         context->PostAsyncEvent([execCtx, postFunc = func, info]() {
4333             JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
4334             auto* eventInfo = TypeInfoHelper::DynamicCast<FaviconReceivedEvent>(info.get());
4335             postFunc->Execute(*eventInfo);
4336         }, "ArkUIWebFaviconReceived");
4337     };
4338     WebModel::GetInstance()->SetFaviconReceivedId(uiCallback);
4339 }
4340 
TouchIconUrlEventToJSValue(const TouchIconUrlEvent & eventInfo)4341 JSRef<JSVal> TouchIconUrlEventToJSValue(const TouchIconUrlEvent& eventInfo)
4342 {
4343     JSRef<JSObject> obj = JSRef<JSObject>::New();
4344     obj->SetProperty("url", eventInfo.GetUrl());
4345     obj->SetProperty("precomposed", eventInfo.GetPreComposed());
4346     return JSRef<JSVal>::Cast(obj);
4347 }
4348 
OnTouchIconUrlReceived(const JSCallbackInfo & args)4349 void JSWeb::OnTouchIconUrlReceived(const JSCallbackInfo& args)
4350 {
4351     if (!args[0]->IsFunction()) {
4352         return;
4353     }
4354     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
4355     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<TouchIconUrlEvent, 1>>(
4356         JSRef<JSFunc>::Cast(args[0]), TouchIconUrlEventToJSValue);
4357 
4358     auto instanceId = Container::CurrentId();
4359     auto uiCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
4360                           const std::shared_ptr<BaseEventInfo>& info) {
4361         ContainerScope scope(instanceId);
4362         auto context = PipelineBase::GetCurrentContext();
4363         CHECK_NULL_VOID(context);
4364         context->UpdateCurrentActiveNode(node);
4365         context->PostAsyncEvent([execCtx, postFunc = func, info]() {
4366             JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
4367             auto* eventInfo = TypeInfoHelper::DynamicCast<TouchIconUrlEvent>(info.get());
4368             postFunc->Execute(*eventInfo);
4369         }, "ArkUIWebTouchIconUrlReceived");
4370     };
4371     WebModel::GetInstance()->SetTouchIconUrlId(uiCallback);
4372 }
4373 
DarkMode(int32_t darkMode)4374 void JSWeb::DarkMode(int32_t darkMode)
4375 {
4376     auto mode = WebDarkMode::Off;
4377     switch (darkMode) {
4378         case 0:
4379             mode = WebDarkMode::Off;
4380             break;
4381         case 1:
4382             mode = WebDarkMode::On;
4383             break;
4384         case 2:
4385             mode = WebDarkMode::Auto;
4386             break;
4387         default:
4388             mode = WebDarkMode::Off;
4389             break;
4390     }
4391     WebModel::GetInstance()->SetDarkMode(mode);
4392 }
4393 
ForceDarkAccess(bool access)4394 void JSWeb::ForceDarkAccess(bool access)
4395 {
4396     WebModel::GetInstance()->SetForceDarkAccess(access);
4397 }
4398 
HorizontalScrollBarAccess(bool isHorizontalScrollBarAccessEnabled)4399 void JSWeb::HorizontalScrollBarAccess(bool isHorizontalScrollBarAccessEnabled)
4400 {
4401     WebModel::GetInstance()->SetHorizontalScrollBarAccessEnabled(isHorizontalScrollBarAccessEnabled);
4402 }
4403 
VerticalScrollBarAccess(bool isVerticalScrollBarAccessEnabled)4404 void JSWeb::VerticalScrollBarAccess(bool isVerticalScrollBarAccessEnabled)
4405 {
4406     WebModel::GetInstance()->SetVerticalScrollBarAccessEnabled(isVerticalScrollBarAccessEnabled);
4407 }
4408 
AudioStateChangedEventToJSValue(const AudioStateChangedEvent & eventInfo)4409 JSRef<JSVal> AudioStateChangedEventToJSValue(const AudioStateChangedEvent& eventInfo)
4410 {
4411     JSRef<JSObject> obj = JSRef<JSObject>::New();
4412     obj->SetProperty("playing", eventInfo.IsPlaying());
4413     return JSRef<JSVal>::Cast(obj);
4414 }
4415 
OnAudioStateChanged(const JSCallbackInfo & args)4416 void JSWeb::OnAudioStateChanged(const JSCallbackInfo& args)
4417 {
4418     if (!args[0]->IsFunction()) {
4419         return;
4420     }
4421 
4422     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
4423     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<AudioStateChangedEvent, 1>>(
4424         JSRef<JSFunc>::Cast(args[0]), AudioStateChangedEventToJSValue);
4425 
4426     auto instanceId = Container::CurrentId();
4427     auto uiCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
4428                           const std::shared_ptr<BaseEventInfo>& info) {
4429         ContainerScope scope(instanceId);
4430         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
4431         auto pipelineContext = PipelineContext::GetCurrentContext();
4432         CHECK_NULL_VOID(pipelineContext);
4433         pipelineContext->UpdateCurrentActiveNode(node);
4434         auto* eventInfo = TypeInfoHelper::DynamicCast<AudioStateChangedEvent>(info.get());
4435         func->Execute(*eventInfo);
4436     };
4437     WebModel::GetInstance()->SetAudioStateChangedId(std::move(uiCallback));
4438 }
4439 
MediaOptions(const JSCallbackInfo & args)4440 void JSWeb::MediaOptions(const JSCallbackInfo& args)
4441 {
4442     if (!args[0]->IsObject()) {
4443         return;
4444     }
4445     auto paramObject = JSRef<JSObject>::Cast(args[0]);
4446     auto resumeIntervalObj = paramObject->GetProperty("resumeInterval");
4447     if (resumeIntervalObj->IsNumber()) {
4448         int32_t resumeInterval = resumeIntervalObj->ToNumber<int32_t>();
4449         WebModel::GetInstance()->SetAudioResumeInterval(resumeInterval);
4450     }
4451 
4452     auto audioExclusiveObj = paramObject->GetProperty("audioExclusive");
4453     if (audioExclusiveObj->IsBoolean()) {
4454         bool audioExclusive = audioExclusiveObj->ToBoolean();
4455         WebModel::GetInstance()->SetAudioExclusive(audioExclusive);
4456     }
4457 }
4458 
FirstContentfulPaintEventToJSValue(const FirstContentfulPaintEvent & eventInfo)4459 JSRef<JSVal> FirstContentfulPaintEventToJSValue(const FirstContentfulPaintEvent& eventInfo)
4460 {
4461     JSRef<JSObject> obj = JSRef<JSObject>::New();
4462     obj->SetProperty<int64_t>("navigationStartTick", eventInfo.GetNavigationStartTick());
4463     obj->SetProperty<int64_t>("firstContentfulPaintMs", eventInfo.GetFirstContentfulPaintMs());
4464     return JSRef<JSVal>::Cast(obj);
4465 }
4466 
OnFirstContentfulPaint(const JSCallbackInfo & args)4467 void JSWeb::OnFirstContentfulPaint(const JSCallbackInfo& args)
4468 {
4469     if (!args[0]->IsFunction()) {
4470         return;
4471     }
4472     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
4473     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<FirstContentfulPaintEvent, 1>>(
4474         JSRef<JSFunc>::Cast(args[0]), FirstContentfulPaintEventToJSValue);
4475 
4476     auto instanceId = Container::CurrentId();
4477     auto uiCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
4478                           const std::shared_ptr<BaseEventInfo>& info) {
4479         ContainerScope scope(instanceId);
4480         auto context = PipelineBase::GetCurrentContext();
4481         CHECK_NULL_VOID(context);
4482         context->UpdateCurrentActiveNode(node);
4483         context->PostAsyncEvent([execCtx, postFunc = func, info]() {
4484             JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
4485             auto* eventInfo = TypeInfoHelper::DynamicCast<FirstContentfulPaintEvent>(info.get());
4486             postFunc->Execute(*eventInfo);
4487         }, "ArkUIWebFirstContentfulPaint");
4488     };
4489     WebModel::GetInstance()->SetFirstContentfulPaintId(std::move(uiCallback));
4490 }
4491 
FirstMeaningfulPaintEventToJSValue(const FirstMeaningfulPaintEvent & eventInfo)4492 JSRef<JSVal> FirstMeaningfulPaintEventToJSValue(const FirstMeaningfulPaintEvent& eventInfo)
4493 {
4494     JSRef<JSObject> obj = JSRef<JSObject>::New();
4495     obj->SetProperty("navigationStartTime", eventInfo.GetNavigationStartTime());
4496     obj->SetProperty("firstMeaningfulPaintTime", eventInfo.GetFirstMeaningfulPaintTime());
4497     return JSRef<JSVal>::Cast(obj);
4498 }
4499 
OnFirstMeaningfulPaint(const JSCallbackInfo & args)4500 void JSWeb::OnFirstMeaningfulPaint(const JSCallbackInfo& args)
4501 {
4502     if (args.Length() < 1 || args[0]->IsUndefined() || args[0]->IsNull() || !args[0]->IsFunction()) {
4503         return;
4504     }
4505     auto frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
4506     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<FirstMeaningfulPaintEvent, 1>>(
4507         JSRef<JSFunc>::Cast(args[0]), FirstMeaningfulPaintEventToJSValue);
4508     auto instanceId = Container::CurrentId();
4509     auto uiCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
4510                           const std::shared_ptr<BaseEventInfo>& info) {
4511         ContainerScope scope(instanceId);
4512         auto context = PipelineBase::GetCurrentContext();
4513         CHECK_NULL_VOID(context);
4514         context->UpdateCurrentActiveNode(node);
4515         context->PostAsyncEvent([execCtx, postFunc = func, info]() {
4516             JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
4517             auto* eventInfo = TypeInfoHelper::DynamicCast<FirstMeaningfulPaintEvent>(info.get());
4518             postFunc->Execute(*eventInfo);
4519         }, "ArkUIWebFirstMeaningfulPaint");
4520     };
4521     WebModel::GetInstance()->SetFirstMeaningfulPaintId(std::move(uiCallback));
4522 }
4523 
LargestContentfulPaintEventToJSValue(const LargestContentfulPaintEvent & eventInfo)4524 JSRef<JSVal> LargestContentfulPaintEventToJSValue(const LargestContentfulPaintEvent& eventInfo)
4525 {
4526     JSRef<JSObject> obj = JSRef<JSObject>::New();
4527     obj->SetProperty("navigationStartTime", eventInfo.GetNavigationStartTime());
4528     obj->SetProperty("largestImagePaintTime", eventInfo.GetLargestImagePaintTime());
4529     obj->SetProperty("largestTextPaintTime", eventInfo.GetLargestTextPaintTime());
4530     obj->SetProperty("largestImageLoadStartTime", eventInfo.GetLargestImageLoadStartTime());
4531     obj->SetProperty("largestImageLoadEndTime", eventInfo.GetLargestImageLoadEndTime());
4532     obj->SetProperty("imageBPP", eventInfo.GetImageBPP());
4533     return JSRef<JSVal>::Cast(obj);
4534 }
4535 
OnLargestContentfulPaint(const JSCallbackInfo & args)4536 void JSWeb::OnLargestContentfulPaint(const JSCallbackInfo& args)
4537 {
4538     if (args.Length() < 1 || args[0]->IsUndefined() || args[0]->IsNull() || !args[0]->IsFunction()) {
4539         return;
4540     }
4541     auto frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
4542     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<LargestContentfulPaintEvent, 1>>(
4543         JSRef<JSFunc>::Cast(args[0]), LargestContentfulPaintEventToJSValue);
4544     auto instanceId = Container::CurrentId();
4545     auto uiCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
4546                           const std::shared_ptr<BaseEventInfo>& info) {
4547         ContainerScope scope(instanceId);
4548         auto context = PipelineBase::GetCurrentContext();
4549         CHECK_NULL_VOID(context);
4550         context->UpdateCurrentActiveNode(node);
4551         context->PostAsyncEvent([execCtx, postFunc = func, info]() {
4552             JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
4553             auto* eventInfo = TypeInfoHelper::DynamicCast<LargestContentfulPaintEvent>(info.get());
4554             postFunc->Execute(*eventInfo);
4555         }, "ArkUIWebLargestContentfulPaint");
4556     };
4557     WebModel::GetInstance()->SetLargestContentfulPaintId(std::move(uiCallback));
4558 }
4559 
SafeBrowsingCheckResultEventToJSValue(const SafeBrowsingCheckResultEvent & eventInfo)4560 JSRef<JSVal> SafeBrowsingCheckResultEventToJSValue(const SafeBrowsingCheckResultEvent& eventInfo)
4561 {
4562     JSRef<JSObject> obj = JSRef<JSObject>::New();
4563     obj->SetProperty("threatType", eventInfo.GetThreatType());
4564     return JSRef<JSVal>::Cast(obj);
4565 }
4566 
OnSafeBrowsingCheckResult(const JSCallbackInfo & args)4567 void JSWeb::OnSafeBrowsingCheckResult(const JSCallbackInfo& args)
4568 {
4569     if (args.Length() < 1 || !args[0]->IsFunction()) {
4570         return;
4571     }
4572     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
4573     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<SafeBrowsingCheckResultEvent, 1>>(
4574         JSRef<JSFunc>::Cast(args[0]), SafeBrowsingCheckResultEventToJSValue);
4575 
4576     auto instanceId = Container::CurrentId();
4577     auto uiCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
4578                           const std::shared_ptr<BaseEventInfo>& info) {
4579         ContainerScope scope(instanceId);
4580         auto context = PipelineBase::GetCurrentContext();
4581         CHECK_NULL_VOID(context);
4582         context->UpdateCurrentActiveNode(node);
4583         context->PostAsyncEvent([execCtx, postFunc = func, info]() {
4584             JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
4585             auto* eventInfo = TypeInfoHelper::DynamicCast<SafeBrowsingCheckResultEvent>(info.get());
4586             postFunc->Execute(*eventInfo);
4587         }, "ArkUIWebSafeBrowsingCheckResult");
4588     };
4589     WebModel::GetInstance()->SetSafeBrowsingCheckResultId(std::move(uiCallback));
4590 }
4591 
NavigationEntryCommittedEventToJSValue(const NavigationEntryCommittedEvent & eventInfo)4592 JSRef<JSVal> NavigationEntryCommittedEventToJSValue(const NavigationEntryCommittedEvent& eventInfo)
4593 {
4594     JSRef<JSObject> obj = JSRef<JSObject>::New();
4595     obj->SetProperty("isMainFrame", eventInfo.IsMainFrame());
4596     obj->SetProperty("isSameDocument", eventInfo.IsSameDocument());
4597     obj->SetProperty("didReplaceEntry", eventInfo.DidReplaceEntry());
4598     obj->SetProperty("navigationType", static_cast<int>(eventInfo.GetNavigationType()));
4599     obj->SetProperty("url", eventInfo.GetUrl());
4600     return JSRef<JSVal>::Cast(obj);
4601 }
4602 
OnNavigationEntryCommitted(const JSCallbackInfo & args)4603 void JSWeb::OnNavigationEntryCommitted(const JSCallbackInfo& args)
4604 {
4605     if (!args[0]->IsFunction()) {
4606         return;
4607     }
4608     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
4609     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<NavigationEntryCommittedEvent, 1>>(
4610         JSRef<JSFunc>::Cast(args[0]), NavigationEntryCommittedEventToJSValue);
4611 
4612     auto instanceId = Container::CurrentId();
4613     auto uiCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
4614                           const std::shared_ptr<BaseEventInfo>& info) {
4615         ContainerScope scope(instanceId);
4616         auto context = PipelineBase::GetCurrentContext();
4617         CHECK_NULL_VOID(context);
4618         context->UpdateCurrentActiveNode(node);
4619         context->PostAsyncEvent([execCtx, postFunc = func, info]() {
4620             JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
4621             auto* eventInfo = TypeInfoHelper::DynamicCast<NavigationEntryCommittedEvent>(info.get());
4622             postFunc->Execute(*eventInfo);
4623         }, "ArkUIWebNavigationEntryCommitted");
4624     };
4625     WebModel::GetInstance()->SetNavigationEntryCommittedId(std::move(uiCallback));
4626 }
4627 
IntelligentTrackingPreventionResultEventToJSValue(const IntelligentTrackingPreventionResultEvent & eventInfo)4628 JSRef<JSVal> IntelligentTrackingPreventionResultEventToJSValue(
4629     const IntelligentTrackingPreventionResultEvent& eventInfo)
4630 {
4631     JSRef<JSObject> obj = JSRef<JSObject>::New();
4632     obj->SetProperty("host", eventInfo.GetHost());
4633     obj->SetProperty("trackerHost", eventInfo.GetTrackerHost());
4634     return JSRef<JSVal>::Cast(obj);
4635 }
4636 
OnIntelligentTrackingPreventionResult(const JSCallbackInfo & args)4637 void JSWeb::OnIntelligentTrackingPreventionResult(const JSCallbackInfo& args)
4638 {
4639     if (args.Length() < 1 || !args[0]->IsFunction()) {
4640         return;
4641     }
4642     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
4643     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<IntelligentTrackingPreventionResultEvent, 1>>(
4644         JSRef<JSFunc>::Cast(args[0]), IntelligentTrackingPreventionResultEventToJSValue);
4645 
4646     auto instanceId = Container::CurrentId();
4647     auto uiCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
4648                           const std::shared_ptr<BaseEventInfo>& info) {
4649         ContainerScope scope(instanceId);
4650         auto context = PipelineBase::GetCurrentContext();
4651         CHECK_NULL_VOID(context);
4652         context->UpdateCurrentActiveNode(node);
4653         context->PostAsyncEvent([execCtx, postFunc = func, info]() {
4654             JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
4655             auto* eventInfo = TypeInfoHelper::DynamicCast<IntelligentTrackingPreventionResultEvent>(info.get());
4656             postFunc->Execute(*eventInfo);
4657         }, "ArkUIWebIntelligentTrackingPreventionResult");
4658     };
4659     WebModel::GetInstance()->SetIntelligentTrackingPreventionResultId(std::move(uiCallback));
4660 }
4661 
OnControllerAttached(const JSCallbackInfo & args)4662 void JSWeb::OnControllerAttached(const JSCallbackInfo& args)
4663 {
4664     if (!args[0]->IsFunction()) {
4665         return;
4666     }
4667     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
4668     auto jsFunc = AceType::MakeRefPtr<JsFunction>(JSRef<JSFunc>::Cast(args[0]));
4669     auto instanceId = Container::CurrentId();
4670     auto uiCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode]() {
4671         ContainerScope scope(instanceId);
4672         auto context = PipelineBase::GetCurrentContext();
4673         CHECK_NULL_VOID(context);
4674         context->UpdateCurrentActiveNode(node);
4675         context->PostSyncEvent([execCtx, postFunc = func]() {
4676             JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
4677             postFunc->Execute();
4678         }, "ArkUIWebControllerAttached");
4679     };
4680     WebModel::GetInstance()->SetOnControllerAttached(std::move(uiCallback));
4681 }
4682 
EmbedLifecycleChangeToJSValue(const NativeEmbedDataInfo & eventInfo)4683 JSRef<JSVal> EmbedLifecycleChangeToJSValue(const NativeEmbedDataInfo& eventInfo)
4684 {
4685     JSRef<JSObject> obj = JSRef<JSObject>::New();
4686     obj->SetProperty("status", static_cast<int32_t>(eventInfo.GetStatus()));
4687     obj->SetProperty("surfaceId", eventInfo.GetSurfaceId());
4688     obj->SetProperty("embedId", eventInfo.GetEmbedId());
4689 
4690     JSRef<JSObjTemplate> objectTemplate = JSRef<JSObjTemplate>::New();
4691     JSRef<JSObject> requestObj = objectTemplate->NewInstance();
4692     requestObj->SetProperty("id", eventInfo.GetEmebdInfo().id);
4693     requestObj->SetProperty("type", eventInfo.GetEmebdInfo().type);
4694     requestObj->SetProperty("src", eventInfo.GetEmebdInfo().src);
4695     requestObj->SetProperty("tag", eventInfo.GetEmebdInfo().tag);
4696     requestObj->SetProperty("width", eventInfo.GetEmebdInfo().width);
4697     requestObj->SetProperty("height", eventInfo.GetEmebdInfo().height);
4698     requestObj->SetProperty("url", eventInfo.GetEmebdInfo().url);
4699 
4700     JSRef<JSObject> positionObj = objectTemplate->NewInstance();
4701     positionObj->SetProperty("x", eventInfo.GetEmebdInfo().x);
4702     positionObj->SetProperty("y", eventInfo.GetEmebdInfo().y);
4703     requestObj->SetPropertyObject("position", positionObj);
4704 
4705     auto params = eventInfo.GetEmebdInfo().params;
4706     JSRef<JSObject> paramsObj = objectTemplate->NewInstance();
4707     for (const auto& item : params) {
4708         paramsObj->SetProperty(item.first.c_str(), item.second.c_str());
4709     }
4710     requestObj->SetPropertyObject("params", paramsObj);
4711 
4712     obj->SetPropertyObject("info", requestObj);
4713 
4714     return JSRef<JSVal>::Cast(obj);
4715 }
4716 
EmbedVisibilityChangeToJSValue(const NativeEmbedVisibilityInfo & visibilityInfo)4717 JSRef<JSVal> EmbedVisibilityChangeToJSValue(const NativeEmbedVisibilityInfo& visibilityInfo)
4718 {
4719     JSRef<JSObject> obj = JSRef<JSObject>::New();
4720     obj->SetProperty("visibility", visibilityInfo.GetVisibility());
4721     obj->SetProperty("embedId", visibilityInfo.GetEmbedId());
4722 
4723     return JSRef<JSVal>::Cast(obj);
4724 }
4725 
OnNativeEmbedLifecycleChange(const JSCallbackInfo & args)4726 void JSWeb::OnNativeEmbedLifecycleChange(const JSCallbackInfo& args)
4727 {
4728     if (args.Length() < 1 || !args[0]->IsFunction()) {
4729         return;
4730     }
4731     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<NativeEmbedDataInfo, 1>>(
4732         JSRef<JSFunc>::Cast(args[0]), EmbedLifecycleChangeToJSValue);
4733     auto instanceId = Container::CurrentId();
4734     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId](
4735                             const BaseEventInfo* info) {
4736         ContainerScope scope(instanceId);
4737         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
4738         auto* eventInfo = TypeInfoHelper::DynamicCast<NativeEmbedDataInfo>(info);
4739         func->Execute(*eventInfo);
4740     };
4741     WebModel::GetInstance()->SetNativeEmbedLifecycleChangeId(jsCallback);
4742 }
4743 
OnNativeEmbedVisibilityChange(const JSCallbackInfo & args)4744 void JSWeb::OnNativeEmbedVisibilityChange(const JSCallbackInfo& args)
4745 {
4746     if (args.Length() < 1 || !args[0]->IsFunction()) {
4747         return;
4748     }
4749     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<NativeEmbedVisibilityInfo, 1>>(
4750         JSRef<JSFunc>::Cast(args[0]), EmbedVisibilityChangeToJSValue);
4751     auto instanceId = Container::CurrentId();
4752     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId](
4753                             const BaseEventInfo* info) {
4754         ContainerScope scope(instanceId);
4755         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
4756         auto* eventInfo = TypeInfoHelper::DynamicCast<NativeEmbedVisibilityInfo>(info);
4757         func->Execute(*eventInfo);
4758     };
4759     WebModel::GetInstance()->SetNativeEmbedVisibilityChangeId(jsCallback);
4760 }
4761 
CreateTouchInfo(const TouchLocationInfo & touchInfo,TouchEventInfo & info)4762 JSRef<JSObject> CreateTouchInfo(const TouchLocationInfo& touchInfo, TouchEventInfo& info)
4763 {
4764     JSRef<JSObjTemplate> objectTemplate = JSRef<JSObjTemplate>::New();
4765     objectTemplate->SetInternalFieldCount(1);
4766     JSRef<JSObject> touchInfoObj = objectTemplate->NewInstance();
4767     const OHOS::Ace::Offset& globalLocation = touchInfo.GetGlobalLocation();
4768     const OHOS::Ace::Offset& localLocation = touchInfo.GetLocalLocation();
4769     const OHOS::Ace::Offset& screenLocation = touchInfo.GetScreenLocation();
4770     touchInfoObj->SetProperty<int32_t>("type", static_cast<int32_t>(touchInfo.GetTouchType()));
4771     touchInfoObj->SetProperty<int32_t>("id", touchInfo.GetFingerId());
4772     touchInfoObj->SetProperty<double>("displayX", screenLocation.GetX());
4773     touchInfoObj->SetProperty<double>("displayY", screenLocation.GetY());
4774     touchInfoObj->SetProperty<double>("windowX", globalLocation.GetX());
4775     touchInfoObj->SetProperty<double>("windowY", globalLocation.GetY());
4776     touchInfoObj->SetProperty<double>("screenX", globalLocation.GetX());
4777     touchInfoObj->SetProperty<double>("screenY", globalLocation.GetY());
4778     touchInfoObj->SetProperty<double>("x", localLocation.GetX());
4779     touchInfoObj->SetProperty<double>("y", localLocation.GetY());
4780     touchInfoObj->Wrap<TouchEventInfo>(&info);
4781     return touchInfoObj;
4782 }
4783 
NativeEmbeadTouchToJSValue(const NativeEmbeadTouchInfo & eventInfo)4784 JSRef<JSVal> NativeEmbeadTouchToJSValue(const NativeEmbeadTouchInfo& eventInfo)
4785 {
4786     JSRef<JSObject> obj = JSRef<JSObject>::New();
4787     obj->SetProperty("embedId", eventInfo.GetEmbedId());
4788     auto info = eventInfo.GetTouchEventInfo();
4789     JSRef<JSObjTemplate> objectTemplate = JSRef<JSObjTemplate>::New();
4790     JSRef<JSObject> eventObj = objectTemplate->NewInstance();
4791     JSRef<JSArray> touchArr = JSRef<JSArray>::New();
4792     JSRef<JSArray> changeTouchArr = JSRef<JSArray>::New();
4793     eventObj->SetProperty("source", static_cast<int32_t>(info.GetSourceDevice()));
4794     eventObj->SetProperty("timestamp", static_cast<double>(GetSysTimestamp()));
4795     auto target = CreateEventTargetObject(info);
4796     eventObj->SetPropertyObject("target", target);
4797     eventObj->SetProperty("pressure", info.GetForce());
4798     eventObj->SetProperty("sourceTool", static_cast<int32_t>(info.GetSourceTool()));
4799     eventObj->SetProperty("targetDisplayId", static_cast<int32_t>(info.GetTargetDisplayId()));
4800     eventObj->SetProperty("deviceId", static_cast<int64_t>(info.GetDeviceId()));
4801 
4802     if (info.GetChangedTouches().empty()) {
4803         return JSRef<JSVal>::Cast(obj);
4804     }
4805     uint32_t index = 0;
4806     TouchLocationInfo changeTouch = info.GetChangedTouches().back();
4807     JSRef<JSObject> changeTouchElement = CreateTouchInfo(changeTouch, info);
4808     changeTouchArr->SetValueAt(index, changeTouchElement);
4809     if (info.GetChangedTouches().size() > 0) {
4810         eventObj->SetProperty("type", static_cast<int32_t>(changeTouch.GetTouchType()));
4811     }
4812 
4813     const std::list<TouchLocationInfo>& touchList = info.GetTouches();
4814     for (const TouchLocationInfo& location : touchList) {
4815         if (location.GetFingerId() == changeTouch.GetFingerId()) {
4816             JSRef<JSObject> touchElement = CreateTouchInfo(changeTouch, info);
4817             touchArr->SetValueAt(index++, touchElement);
4818         } else {
4819             JSRef<JSObject> touchElement = CreateTouchInfo(location, info);
4820             touchArr->SetValueAt(index++, touchElement);
4821         }
4822     }
4823     eventObj->SetPropertyObject("touches", touchArr);
4824     eventObj->SetPropertyObject("changedTouches", changeTouchArr);
4825     obj->SetPropertyObject("touchEvent", eventObj);
4826     JSRef<JSObject> requestObj = JSClass<JSNativeEmbedGestureRequest>::NewInstance();
4827     auto requestEvent = Referenced::Claim(requestObj->Unwrap<JSNativeEmbedGestureRequest>());
4828     requestEvent->SetResult(eventInfo.GetResult());
4829     obj->SetPropertyObject("result", requestObj);
4830     return JSRef<JSVal>::Cast(obj);
4831 }
4832 
OnNativeEmbedGestureEvent(const JSCallbackInfo & args)4833 void JSWeb::OnNativeEmbedGestureEvent(const JSCallbackInfo& args)
4834 {
4835     if (args.Length() < 1 || !args[0]->IsFunction()) {
4836         return;
4837     }
4838     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<NativeEmbeadTouchInfo, 1>>(
4839         JSRef<JSFunc>::Cast(args[0]), NativeEmbeadTouchToJSValue);
4840     auto instanceId = Container::CurrentId();
4841     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId](
4842                             const BaseEventInfo* info) {
4843         ContainerScope scope(instanceId);
4844         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
4845         auto* eventInfo = TypeInfoHelper::DynamicCast<NativeEmbeadTouchInfo>(info);
4846         func->Execute(*eventInfo);
4847     };
4848     WebModel::GetInstance()->SetNativeEmbedGestureEventId(jsCallback);
4849 }
4850 
4851 
OverScrollEventToJSValue(const WebOnOverScrollEvent & eventInfo)4852 JSRef<JSVal> OverScrollEventToJSValue(const WebOnOverScrollEvent& eventInfo)
4853 {
4854     JSRef<JSObject> obj = JSRef<JSObject>::New();
4855     obj->SetProperty("xOffset", eventInfo.GetX());
4856     obj->SetProperty("yOffset", eventInfo.GetY());
4857     return JSRef<JSVal>::Cast(obj);
4858 }
4859 
OnOverScroll(const JSCallbackInfo & args)4860 void JSWeb::OnOverScroll(const JSCallbackInfo& args)
4861 {
4862     if (args.Length() < 1 || !args[0]->IsFunction()) {
4863         return;
4864     }
4865     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
4866     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<WebOnOverScrollEvent, 1>>(
4867         JSRef<JSFunc>::Cast(args[0]), OverScrollEventToJSValue);
4868     auto instanceId = Container::CurrentId();
4869     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
4870                           const BaseEventInfo* info) {
4871         ContainerScope scope(instanceId);
4872         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
4873         auto pipelineContext = PipelineContext::GetCurrentContext();
4874         CHECK_NULL_VOID(pipelineContext);
4875         pipelineContext->UpdateCurrentActiveNode(node);
4876         auto* eventInfo = TypeInfoHelper::DynamicCast<WebOnOverScrollEvent>(info);
4877         func->Execute(*eventInfo);
4878     };
4879     WebModel::GetInstance()->SetOverScrollId(jsCallback);
4880 }
4881 
SetLayoutMode(int32_t layoutMode)4882 void JSWeb::SetLayoutMode(int32_t layoutMode)
4883 {
4884     auto mode = WebLayoutMode::NONE;
4885     switch (layoutMode) {
4886         case 0:
4887             mode = WebLayoutMode::NONE;
4888             break;
4889         case 1:
4890             mode = WebLayoutMode::FIT_CONTENT;
4891             break;
4892         default:
4893             mode = WebLayoutMode::NONE;
4894             break;
4895     }
4896     WebModel::GetInstance()->SetLayoutMode(mode);
4897 }
4898 
SetNestedScroll(const JSCallbackInfo & args)4899 void JSWeb::SetNestedScroll(const JSCallbackInfo& args)
4900 {
4901     NestedScrollOptionsExt nestedOpt = {
4902         .scrollUp = NestedScrollMode::SELF_FIRST,
4903         .scrollDown = NestedScrollMode::SELF_FIRST,
4904         .scrollLeft = NestedScrollMode::SELF_FIRST,
4905         .scrollRight = NestedScrollMode::SELF_FIRST,
4906     };
4907     if (args.Length() < 1 || !args[0]->IsObject()) {
4908         WebModel::GetInstance()->SetNestedScrollExt(nestedOpt);
4909         return;
4910     }
4911     JSRef<JSObject> obj = JSRef<JSObject>::Cast(args[0]);
4912     int32_t froward = -1;
4913     JSViewAbstract::ParseJsInt32(obj->GetProperty("scrollForward"), froward);
4914     if (CheckNestedScrollMode(froward)) {
4915         nestedOpt.scrollDown = static_cast<NestedScrollMode>(froward);
4916         nestedOpt.scrollRight = static_cast<NestedScrollMode>(froward);
4917     }
4918     int32_t backward = -1;
4919     JSViewAbstract::ParseJsInt32(obj->GetProperty("scrollBackward"), backward);
4920     if (CheckNestedScrollMode(backward)) {
4921         nestedOpt.scrollUp = static_cast<NestedScrollMode>(backward);
4922         nestedOpt.scrollLeft = static_cast<NestedScrollMode>(backward);
4923     }
4924     int32_t scrollUp = -1;
4925     JSViewAbstract::ParseJsInt32(obj->GetProperty("scrollUp"), scrollUp);
4926     if (CheckNestedScrollMode(scrollUp)) {
4927         nestedOpt.scrollUp = static_cast<NestedScrollMode>(scrollUp);
4928     }
4929     int32_t scrollDown = -1;
4930     JSViewAbstract::ParseJsInt32(obj->GetProperty("scrollDown"), scrollDown);
4931     if (CheckNestedScrollMode(scrollDown)) {
4932         nestedOpt.scrollDown = static_cast<NestedScrollMode>(scrollDown);
4933     }
4934     int32_t scrollLeft = -1;
4935     JSViewAbstract::ParseJsInt32(obj->GetProperty("scrollLeft"), scrollLeft);
4936     if (CheckNestedScrollMode(scrollLeft)) {
4937         nestedOpt.scrollLeft = static_cast<NestedScrollMode>(scrollLeft);
4938     }
4939     int32_t scrollRight = -1;
4940     JSViewAbstract::ParseJsInt32(obj->GetProperty("scrollRight"), scrollRight);
4941     if (CheckNestedScrollMode(scrollRight)) {
4942         nestedOpt.scrollRight = static_cast<NestedScrollMode>(scrollRight);
4943     }
4944     WebModel::GetInstance()->SetNestedScrollExt(nestedOpt);
4945     args.ReturnSelf();
4946 }
4947 
CheckNestedScrollMode(const int32_t & modeValue)4948 bool JSWeb::CheckNestedScrollMode(const int32_t& modeValue)
4949 {
4950     return modeValue >= static_cast<int32_t>(NestedScrollMode::SELF_ONLY) &&
4951            modeValue <= static_cast<int32_t>(NestedScrollMode::PARALLEL);
4952 }
4953 
SetMetaViewport(const JSCallbackInfo & args)4954 void JSWeb::SetMetaViewport(const JSCallbackInfo& args)
4955 {
4956     if (args.Length() < 1 || !args[0]->IsBoolean()) {
4957         return;
4958     }
4959     bool enabled = args[0]->ToBoolean();
4960     WebModel::GetInstance()->SetMetaViewport(enabled);
4961 }
4962 
ParseScriptItems(const JSCallbackInfo & args,ScriptItems & scriptItems,ScriptItemsByOrder & scriptItemsByOrder)4963 void JSWeb::ParseScriptItems(
4964     const JSCallbackInfo& args, ScriptItems& scriptItems, ScriptItemsByOrder& scriptItemsByOrder)
4965 {
4966     if (args.Length() != 1 || args[0]->IsUndefined() || args[0]->IsNull() || !args[0]->IsArray()) {
4967         return;
4968     }
4969     auto paramArray = JSRef<JSArray>::Cast(args[0]);
4970     size_t length = paramArray->Length();
4971     if (length == 0) {
4972         return;
4973     }
4974     std::string script;
4975     std::vector<std::string> scriptRules;
4976     for (size_t i = 0; i < length; i++) {
4977         auto item = paramArray->GetValueAt(i);
4978         if (!item->IsObject()) {
4979             return;
4980         }
4981         auto itemObject = JSRef<JSObject>::Cast(item);
4982         JSRef<JSVal> jsScript = itemObject->GetProperty("script");
4983         JSRef<JSVal> jsScriptRules = itemObject->GetProperty("scriptRules");
4984         if (!jsScriptRules->IsArray() || JSRef<JSArray>::Cast(jsScriptRules)->Length() == 0) {
4985             return;
4986         }
4987         if (!JSViewAbstract::ParseJsString(jsScript, script)) {
4988             return;
4989         }
4990         scriptRules.clear();
4991         if (!JSViewAbstract::ParseJsStrArray(jsScriptRules, scriptRules)) {
4992             return;
4993         }
4994         if (scriptItems.find(script) == scriptItems.end()) {
4995             scriptItems.insert(std::make_pair(script, scriptRules));
4996             scriptItemsByOrder.emplace_back(script);
4997         }
4998     }
4999 }
5000 
JavaScriptOnDocumentStart(const JSCallbackInfo & args)5001 void JSWeb::JavaScriptOnDocumentStart(const JSCallbackInfo& args)
5002 {
5003     ScriptItems scriptItems;
5004     ScriptItemsByOrder scriptItemsByOrder;
5005     ParseScriptItems(args, scriptItems, scriptItemsByOrder);
5006 
5007     WebModel::GetInstance()->JavaScriptOnDocumentStart(scriptItems);
5008 }
5009 
JavaScriptOnDocumentEnd(const JSCallbackInfo & args)5010 void JSWeb::JavaScriptOnDocumentEnd(const JSCallbackInfo& args)
5011 {
5012     ScriptItems scriptItems;
5013     ScriptItemsByOrder scriptItemsByOrder;
5014     ParseScriptItems(args, scriptItems, scriptItemsByOrder);
5015 
5016     WebModel::GetInstance()->JavaScriptOnDocumentEnd(scriptItems);
5017 }
5018 
RunJavaScriptOnDocumentStart(const JSCallbackInfo & args)5019 void JSWeb::RunJavaScriptOnDocumentStart(const JSCallbackInfo& args)
5020 {
5021     ScriptItems scriptItems;
5022     ScriptItemsByOrder scriptItemsByOrder;
5023     ParseScriptItems(args, scriptItems, scriptItemsByOrder);
5024 
5025     WebModel::GetInstance()->JavaScriptOnDocumentStartByOrder(scriptItems, scriptItemsByOrder);
5026 }
5027 
RunJavaScriptOnDocumentEnd(const JSCallbackInfo & args)5028 void JSWeb::RunJavaScriptOnDocumentEnd(const JSCallbackInfo& args)
5029 {
5030     ScriptItems scriptItems;
5031     ScriptItemsByOrder scriptItemsByOrder;
5032     ParseScriptItems(args, scriptItems, scriptItemsByOrder);
5033 
5034     WebModel::GetInstance()->JavaScriptOnDocumentEndByOrder(scriptItems, scriptItemsByOrder);
5035 }
5036 
RunJavaScriptOnHeadEnd(const JSCallbackInfo & args)5037 void JSWeb::RunJavaScriptOnHeadEnd(const JSCallbackInfo& args)
5038 {
5039     ScriptItems scriptItems;
5040     ScriptItemsByOrder scriptItemsByOrder;
5041     ParseScriptItems(args, scriptItems, scriptItemsByOrder);
5042 
5043     WebModel::GetInstance()->JavaScriptOnHeadReadyByOrder(scriptItems, scriptItemsByOrder);
5044 }
5045 
OnOverrideUrlLoading(const JSCallbackInfo & args)5046 void JSWeb::OnOverrideUrlLoading(const JSCallbackInfo& args)
5047 {
5048     if (args.Length() < 1 || !args[0]->IsFunction()) {
5049         return;
5050     }
5051     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<LoadOverrideEvent, 1>>(
5052         JSRef<JSFunc>::Cast(args[0]), LoadOverrideEventToJSValue);
5053     auto instanceId = Container::CurrentId();
5054 
5055     auto frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
5056     auto uiCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
5057                           const BaseEventInfo* info) -> bool {
5058         ContainerScope scope(instanceId);
5059         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx, false);
5060         auto pipelineContext = PipelineContext::GetCurrentContext();
5061         CHECK_NULL_RETURN(pipelineContext, false);
5062         pipelineContext->UpdateCurrentActiveNode(node);
5063         auto* eventInfo = TypeInfoHelper::DynamicCast<LoadOverrideEvent>(info);
5064         JSRef<JSVal> message = func->ExecuteWithValue(*eventInfo);
5065         if (message->IsBoolean()) {
5066             return message->ToBoolean();
5067         }
5068         return false;
5069     };
5070     WebModel::GetInstance()->SetOnOverrideUrlLoading(std::move(uiCallback));
5071 }
5072 
CopyOption(int32_t copyOption)5073 void JSWeb::CopyOption(int32_t copyOption)
5074 {
5075     auto mode = CopyOptions::Local;
5076     switch (copyOption) {
5077         case static_cast<int32_t>(CopyOptions::None):
5078             mode = CopyOptions::None;
5079             break;
5080         case static_cast<int32_t>(CopyOptions::InApp):
5081             mode = CopyOptions::InApp;
5082             break;
5083         case static_cast<int32_t>(CopyOptions::Local):
5084             mode = CopyOptions::Local;
5085             break;
5086         case static_cast<int32_t>(CopyOptions::Distributed):
5087             mode = CopyOptions::Distributed;
5088             break;
5089         default:
5090             mode = CopyOptions::Local;
5091             break;
5092     }
5093     WebModel::GetInstance()->SetCopyOptionMode(mode);
5094 }
5095 
TextAutosizing(const JSCallbackInfo & args)5096 void JSWeb::TextAutosizing(const JSCallbackInfo& args)
5097 {
5098     if (args.Length() < 1 || !args[0]->IsBoolean()) {
5099         return;
5100     }
5101     bool isTextAutosizing = args[0]->ToBoolean();
5102     WebModel::GetInstance()->SetTextAutosizing(isTextAutosizing);
5103 }
5104 
EnableNativeVideoPlayer(const JSCallbackInfo & args)5105 void JSWeb::EnableNativeVideoPlayer(const JSCallbackInfo& args)
5106 {
5107     if (args.Length() < 1 || !args[0]->IsObject()) {
5108         return;
5109     }
5110     auto paramObject = JSRef<JSObject>::Cast(args[0]);
5111     std::optional<bool> enable;
5112     std::optional<bool> shouldOverlay;
5113     JSRef<JSVal> enableJsValue = paramObject->GetProperty("enable");
5114     if (enableJsValue->IsBoolean()) {
5115         enable = enableJsValue->ToBoolean();
5116     }
5117     JSRef<JSVal> shouldOverlayJsValue = paramObject->GetProperty("shouldOverlay");
5118     if (shouldOverlayJsValue->IsBoolean()) {
5119         shouldOverlay = shouldOverlayJsValue->ToBoolean();
5120     }
5121     if (!enable || !shouldOverlay) {
5122         // invalid NativeVideoPlayerConfig
5123         return;
5124     }
5125     WebModel::GetInstance()->SetNativeVideoPlayerConfig(*enable, *shouldOverlay);
5126 }
5127 
RenderProcessNotRespondingToJSValue(const RenderProcessNotRespondingEvent & eventInfo)5128 JSRef<JSVal> RenderProcessNotRespondingToJSValue(const RenderProcessNotRespondingEvent& eventInfo)
5129 {
5130     JSRef<JSObject> obj = JSRef<JSObject>::New();
5131     obj->SetProperty("jsStack", eventInfo.GetJsStack());
5132     obj->SetProperty("pid", eventInfo.GetPid());
5133     obj->SetProperty("reason", eventInfo.GetReason());
5134     return JSRef<JSVal>::Cast(obj);
5135 }
5136 
OnRenderProcessNotResponding(const JSCallbackInfo & args)5137 void JSWeb::OnRenderProcessNotResponding(const JSCallbackInfo& args)
5138 {
5139     if (args.Length() < 1 || !args[0]->IsFunction()) {
5140         return;
5141     }
5142     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
5143     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<RenderProcessNotRespondingEvent, 1>>(
5144         JSRef<JSFunc>::Cast(args[0]), RenderProcessNotRespondingToJSValue);
5145     auto instanceId = Container::CurrentId();
5146     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
5147                           const BaseEventInfo* info) {
5148         ContainerScope scope(instanceId);
5149         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
5150         auto pipelineContext = PipelineContext::GetCurrentContext();
5151         CHECK_NULL_VOID(pipelineContext);
5152         pipelineContext->UpdateCurrentActiveNode(node);
5153         auto* eventInfo = TypeInfoHelper::DynamicCast<RenderProcessNotRespondingEvent>(info);
5154         func->Execute(*eventInfo);
5155     };
5156     WebModel::GetInstance()->SetRenderProcessNotRespondingId(jsCallback);
5157 }
5158 
RenderProcessRespondingEventToJSValue(const RenderProcessRespondingEvent & eventInfo)5159 JSRef<JSVal> RenderProcessRespondingEventToJSValue(const RenderProcessRespondingEvent& eventInfo)
5160 {
5161     JSRef<JSObject> obj = JSRef<JSObject>::New();
5162     return JSRef<JSVal>::Cast(obj);
5163 }
5164 
OnRenderProcessResponding(const JSCallbackInfo & args)5165 void JSWeb::OnRenderProcessResponding(const JSCallbackInfo& args)
5166 {
5167     if (args.Length() < 1 || !args[0]->IsFunction()) {
5168         return;
5169     }
5170     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
5171     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<RenderProcessRespondingEvent, 1>>(
5172         JSRef<JSFunc>::Cast(args[0]), RenderProcessRespondingEventToJSValue);
5173     auto instanceId = Container::CurrentId();
5174     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
5175                           const BaseEventInfo* info) {
5176         ContainerScope scope(instanceId);
5177         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
5178         auto pipelineContext = PipelineContext::GetCurrentContext();
5179         CHECK_NULL_VOID(pipelineContext);
5180         pipelineContext->UpdateCurrentActiveNode(node);
5181         auto* eventInfo = TypeInfoHelper::DynamicCast<RenderProcessRespondingEvent>(info);
5182         func->Execute(*eventInfo);
5183     };
5184     WebModel::GetInstance()->SetRenderProcessRespondingId(jsCallback);
5185 }
5186 
ViewportFitChangedToJSValue(const ViewportFitChangedEvent & eventInfo)5187 JSRef<JSVal> ViewportFitChangedToJSValue(const ViewportFitChangedEvent& eventInfo)
5188 {
5189     JSRef<JSObject> obj = JSRef<JSObject>::New();
5190     obj->SetProperty("viewportFit", eventInfo.GetViewportFit());
5191     return JSRef<JSVal>::Cast(obj);
5192 }
5193 
OnViewportFitChanged(const JSCallbackInfo & args)5194 void JSWeb::OnViewportFitChanged(const JSCallbackInfo& args)
5195 {
5196     if (args.Length() < 1 || !args[0]->IsFunction()) {
5197         return;
5198     }
5199     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
5200     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<ViewportFitChangedEvent, 1>>(
5201         JSRef<JSFunc>::Cast(args[0]), ViewportFitChangedToJSValue);
5202     auto instanceId = Container::CurrentId();
5203     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
5204                           const BaseEventInfo* info) {
5205         ContainerScope scope(instanceId);
5206         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
5207         auto pipelineContext = PipelineContext::GetCurrentContext();
5208         CHECK_NULL_VOID(pipelineContext);
5209         pipelineContext->UpdateCurrentActiveNode(node);
5210         auto* eventInfo = TypeInfoHelper::DynamicCast<ViewportFitChangedEvent>(info);
5211         func->Execute(*eventInfo);
5212     };
5213     WebModel::GetInstance()->SetViewportFitChangedId(jsCallback);
5214 }
5215 
SelectionMenuOptions(const JSCallbackInfo & args)5216 void JSWeb::SelectionMenuOptions(const JSCallbackInfo& args)
5217 {
5218     if (args.Length() != 1 || args[0]->IsUndefined() || args[0]->IsNull() || !args[0]->IsArray()) {
5219         return;
5220     }
5221     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
5222     auto instanceId = Container::CurrentId();
5223     auto menuItamArray = JSRef<JSArray>::Cast(args[0]);
5224     WebMenuOptionsParam optionParam;
5225     NG::MenuOptionsParam menuOption;
5226     for (size_t i = 0; i < menuItamArray->Length(); i++) {
5227         auto menuItem = menuItamArray->GetValueAt(i);
5228         if (!menuItem->IsObject()) {
5229             return;
5230         }
5231         auto menuItemObject = JSRef<JSObject>::Cast(menuItem);
5232         auto jsContent = menuItemObject->GetProperty("content");
5233         auto jsStartIcon = menuItemObject->GetProperty("startIcon");
5234         std::string content;
5235         if (!ParseJsMedia(jsContent, content)) {
5236             return;
5237         }
5238         menuOption.content = content;
5239         std::string icon;
5240         menuOption.icon.reset();
5241         if (ParseJsMedia(jsStartIcon, icon)) {
5242             menuOption.icon = icon;
5243         }
5244         auto jsAction = menuItemObject->GetProperty("action");
5245         if (jsAction.IsEmpty() || !jsAction->IsFunction()) {
5246             return;
5247         }
5248         auto jsFunc = AceType::MakeRefPtr<JsFunction>(JSRef<JSFunc>::Cast(jsAction));
5249         auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc),
5250                             instanceId, node = frameNode](const std::string selectInfo) {
5251             ContainerScope scope(instanceId);
5252             JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
5253             auto pipelineContext = PipelineContext::GetCurrentContext();
5254             CHECK_NULL_VOID(pipelineContext);
5255             pipelineContext->UpdateCurrentActiveNode(node);
5256             pipelineContext->SetCallBackNode(node);
5257             auto newSelectInfo = JSRef<JSVal>::Make(ToJSValue(selectInfo));
5258             func->ExecuteJS(1, &newSelectInfo);
5259         };
5260         menuOption.action = std::move(jsCallback);
5261         optionParam.menuOption.push_back(menuOption);
5262     }
5263     WebModel::GetInstance()->SetSelectionMenuOptions(std::move(optionParam));
5264 }
5265 
OnAdsBlocked(const JSCallbackInfo & args)5266 void JSWeb::OnAdsBlocked(const JSCallbackInfo& args)
5267 {
5268     if (args.Length() < 1 || !args[0]->IsFunction()) {
5269         return;
5270     }
5271 
5272     WeakPtr<NG::FrameNode> frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
5273     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<AdsBlockedEvent, 1>>(
5274         JSRef<JSFunc>::Cast(args[0]), AdsBlockedEventToJSValue);
5275     auto instanceId = Container::CurrentId();
5276     auto jsCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
5277                           const BaseEventInfo* info) {
5278         ContainerScope scope(instanceId);
5279         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
5280         auto pipelineContext = PipelineContext::GetCurrentContext();
5281         CHECK_NULL_VOID(pipelineContext);
5282         pipelineContext->UpdateCurrentActiveNode(node);
5283         auto* eventInfo = TypeInfoHelper::DynamicCast<AdsBlockedEvent>(info);
5284         func->Execute(*eventInfo);
5285     };
5286     WebModel::GetInstance()->SetAdsBlockedEventId(jsCallback);
5287 }
5288 
InterceptKeyboardEventToJSValue(const InterceptKeyboardEvent & eventInfo)5289 JSRef<JSVal> InterceptKeyboardEventToJSValue(const InterceptKeyboardEvent& eventInfo)
5290 {
5291     JSRef<JSObject> obj = JSRef<JSObject>::New();
5292     JSRef<JSObject> webKeyboardControllerObj = JSClass<JSWebKeyboardController>::NewInstance();
5293     auto webKeyboardController = Referenced::Claim(webKeyboardControllerObj->Unwrap<JSWebKeyboardController>());
5294     webKeyboardController->SeWebKeyboardController(eventInfo.GetCustomKeyboardHandler());
5295     obj->SetPropertyObject("controller", webKeyboardControllerObj);
5296 
5297     JSRef<JSObjTemplate> objectTemplate = JSRef<JSObjTemplate>::New();
5298     JSRef<JSObject> attributesObj = objectTemplate->NewInstance();
5299     for (const auto& item : eventInfo.GetAttributesMap()) {
5300         attributesObj->SetProperty(item.first.c_str(), item.second.c_str());
5301     }
5302     obj->SetPropertyObject("attributes", attributesObj);
5303     return JSRef<JSVal>::Cast(obj);
5304 }
5305 
ParseJsCustomKeyboardOption(const JsiExecutionContext & context,const JSRef<JSVal> & keyboardOpt,WebKeyboardOption & keyboardOption)5306 void JSWeb::ParseJsCustomKeyboardOption(const JsiExecutionContext& context, const JSRef<JSVal>& keyboardOpt,
5307     WebKeyboardOption& keyboardOption)
5308 {
5309     TAG_LOGI(AceLogTag::ACE_WEB, "WebCustomKeyboard ParseJsCustomKeyboardOption enter");
5310     if (!keyboardOpt->IsObject()) {
5311         return;
5312     }
5313 
5314     JSRef<JSObject> keyboradOptObj = JSRef<JSObject>::Cast(keyboardOpt);
5315     auto useSystemKeyboardObj = keyboradOptObj->GetProperty("useSystemKeyboard");
5316     if (useSystemKeyboardObj->IsNull() || !useSystemKeyboardObj->IsBoolean()) {
5317         return;
5318     }
5319 
5320     bool isSystemKeyboard = useSystemKeyboardObj->ToBoolean();
5321     keyboardOption.isSystemKeyboard_ = isSystemKeyboard;
5322     TAG_LOGI(AceLogTag::ACE_WEB, "WebCustomKeyboard ParseJsCustomKeyboardOption isSystemKeyboard is %{public}d",
5323         isSystemKeyboard);
5324     if (isSystemKeyboard) {
5325         auto enterKeyTypeObj = keyboradOptObj->GetProperty("enterKeyType");
5326         if (enterKeyTypeObj->IsNull() || !enterKeyTypeObj->IsNumber()) {
5327             return;
5328         }
5329         int32_t enterKeyType = enterKeyTypeObj->ToNumber<int32_t>();
5330         keyboardOption.enterKeyTpye_ = enterKeyType;
5331         TAG_LOGI(AceLogTag::ACE_WEB, "WebCustomKeyboard ParseJsCustomKeyboardOption \
5332             isSystemKeyboard is %{public}d, enterKeyType is %{public}d", isSystemKeyboard, enterKeyType);
5333     } else {
5334         auto builder = keyboradOptObj->GetProperty("customKeyboard");
5335         if (builder->IsNull()) {
5336             TAG_LOGE(AceLogTag::ACE_WEB, "WebCustomKeyboard ParseJsCustomKeyboardOption" \
5337                 ", parse customKeyboard, builder is null");
5338             return;
5339         }
5340 
5341         if (!builder->IsFunction()) {
5342             TAG_LOGE(AceLogTag::ACE_WEB, "WebCustomKeyboard ParseJsCustomKeyboardOption" \
5343                 ", parse customKeyboard, builder is invalid");
5344             return;
5345         }
5346 
5347         auto builderFunc = AceType::MakeRefPtr<JsFunction>(JSRef<JSFunc>::Cast(builder));
5348         CHECK_NULL_VOID(builderFunc);
5349         WeakPtr<NG::FrameNode> targetNode =
5350             AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
5351         auto buildFunc = [execCtx = context, func = std::move(builderFunc), node = targetNode]() {
5352             JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
5353             ACE_SCORING_EVENT("WebCustomKeyboard");
5354             PipelineContext::SetCallBackNode(node);
5355             func->Execute();
5356         };
5357         keyboardOption.customKeyboardBuilder_ = buildFunc;
5358         TAG_LOGI(AceLogTag::ACE_WEB, "WebCustomKeyboard ParseJsCustomKeyboardOption" \
5359             ", isSystemKeyboard is %{public}d, parseCustomBuilder end", isSystemKeyboard);
5360     }
5361 }
5362 
OnInterceptKeyboardAttach(const JSCallbackInfo & args)5363 void JSWeb::OnInterceptKeyboardAttach(const JSCallbackInfo& args)
5364 {
5365     TAG_LOGI(AceLogTag::ACE_WEB, "WebCustomKeyboard OnInterceptKeyboardAttach register enter");
5366     if (args.Length() < 1 || !args[0]->IsFunction()) {
5367         return;
5368     }
5369     auto jsFunc = AceType::MakeRefPtr<JsEventFunction<InterceptKeyboardEvent, 1>>(
5370         JSRef<JSFunc>::Cast(args[0]), InterceptKeyboardEventToJSValue);
5371     auto instanceId = Container::CurrentId();
5372 
5373     auto frameNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
5374     auto uiCallback = [execCtx = args.GetExecutionContext(), func = std::move(jsFunc), instanceId, node = frameNode](
5375                           const BaseEventInfo* info) -> WebKeyboardOption {
5376         TAG_LOGI(AceLogTag::ACE_WEB, "WebCustomKeyboard OnInterceptKeyboardAttach invoke enter");
5377         ContainerScope scope(instanceId);
5378         WebKeyboardOption opt;
5379         JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx, opt);
5380         auto pipelineContext = PipelineContext::GetCurrentContext();
5381         CHECK_NULL_RETURN(pipelineContext, opt);
5382         pipelineContext->UpdateCurrentActiveNode(node);
5383         auto* eventInfo = TypeInfoHelper::DynamicCast<InterceptKeyboardEvent>(info);
5384         JSRef<JSVal> keyboardOpt = func->ExecuteWithValue(*eventInfo);
5385         ParseJsCustomKeyboardOption(execCtx, keyboardOpt, opt);
5386         return opt;
5387     };
5388     WebModel::GetInstance()->SetOnInterceptKeyboardAttach(std::move(uiCallback));
5389 }
5390 
ForceDisplayScrollBar(const JSCallbackInfo & args)5391 void JSWeb::ForceDisplayScrollBar(const JSCallbackInfo& args)
5392 {
5393     if (args.Length() < 1 || !args[0]->IsBoolean()) {
5394         return;
5395     }
5396     bool isEnabled = args[0]->ToBoolean();
5397     WebModel::GetInstance()->SetOverlayScrollbarEnabled(isEnabled);
5398 }
5399 
KeyboardAvoidMode(int32_t mode)5400 void JSWeb::KeyboardAvoidMode(int32_t mode)
5401 {
5402     if (mode < static_cast<int32_t>(WebKeyboardAvoidMode::RESIZE_VISUAL) ||
5403         mode > static_cast<int32_t>(WebKeyboardAvoidMode::DEFAULT)) {
5404         TAG_LOGE(AceLogTag::ACE_WEB, "KeyboardAvoidMode param err");
5405         return;
5406     }
5407     WebKeyboardAvoidMode avoidMode = static_cast<WebKeyboardAvoidMode>(mode);
5408     WebModel::GetInstance()->SetKeyboardAvoidMode(avoidMode);
5409 }
5410 
EditMenuOptions(const JSCallbackInfo & info)5411 void JSWeb::EditMenuOptions(const JSCallbackInfo& info)
5412 {
5413     NG::OnCreateMenuCallback onCreateMenuCallback;
5414     NG::OnMenuItemClickCallback onMenuItemClick;
5415     JSViewAbstract::ParseEditMenuOptions(info, onCreateMenuCallback, onMenuItemClick);
5416     WebModel::GetInstance()->SetEditMenuOptions(std::move(onCreateMenuCallback), std::move(onMenuItemClick));
5417 }
5418 
EnableHapticFeedback(const JSCallbackInfo & args)5419 void JSWeb::EnableHapticFeedback(const JSCallbackInfo& args)
5420 {
5421     if (args.Length() < 1 || !args[0]->IsBoolean()) {
5422         return;
5423     }
5424     bool isEnabled = args[0]->ToBoolean();
5425     WebModel::GetInstance()->SetEnabledHapticFeedback(isEnabled);
5426 }
5427 
OptimizeParserBudgetEnabled(bool enable)5428 void JSWeb::OptimizeParserBudgetEnabled(bool enable)
5429 {
5430     WebModel::GetInstance()->SetOptimizeParserBudgetEnabled(enable);
5431 }
5432 } // namespace OHOS::Ace::Framework
5433