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