• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "frameworks/bridge/declarative_frontend/engine/jsi/jsi_declarative_engine.h"
17 
18 #include <mutex>
19 #include <optional>
20 #include <regex>
21 #include <unistd.h>
22 
23 #include "base/utils/utils.h"
24 #ifdef WINDOWS_PLATFORM
25 #include <algorithm>
26 #endif
27 
28 #include "scope_manager/native_scope_manager.h"
29 
30 #include "base/base64/base64_util.h"
31 #include "base/i18n/localization.h"
32 #include "base/log/ace_trace.h"
33 #include "base/log/event_report.h"
34 #include "core/common/ace_application_info.h"
35 #include "core/common/ace_view.h"
36 #include "core/common/card_scope.h"
37 #include "core/common/connect_server_manager.h"
38 #include "core/common/container.h"
39 #include "core/common/container_scope.h"
40 #include "core/components_v2/inspector/inspector_constants.h"
41 #include "frameworks/bridge/card_frontend/card_frontend_declarative.h"
42 #include "frameworks/bridge/card_frontend/form_frontend_declarative.h"
43 #include "frameworks/bridge/common/utils/engine_helper.h"
44 #include "frameworks/bridge/declarative_frontend/engine/js_converter.h"
45 #include "frameworks/bridge/declarative_frontend/engine/js_ref_ptr.h"
46 #include "frameworks/bridge/declarative_frontend/engine/js_types.h"
47 #include "frameworks/bridge/declarative_frontend/engine/jsi/jsi_declarative_group_js_bridge.h"
48 #include "frameworks/bridge/declarative_frontend/engine/jsi/jsi_types.h"
49 #include "frameworks/bridge/declarative_frontend/engine/jsi/modules/jsi_context_module.h"
50 #include "frameworks/bridge/declarative_frontend/engine/jsi/modules/jsi_module_manager.h"
51 #include "frameworks/bridge/declarative_frontend/engine/jsi/modules/jsi_syscap_module.h"
52 #include "frameworks/bridge/declarative_frontend/engine/jsi/modules/jsi_timer_module.h"
53 #include "frameworks/bridge/declarative_frontend/jsview/js_local_storage.h"
54 #include "frameworks/bridge/declarative_frontend/jsview/js_view_register.h"
55 #include "frameworks/bridge/declarative_frontend/jsview/js_xcomponent.h"
56 #include "frameworks/bridge/declarative_frontend/view_stack_processor.h"
57 #include "frameworks/bridge/js_frontend/engine/common/js_api_perf.h"
58 #include "frameworks/bridge/js_frontend/engine/common/runtime_constants.h"
59 #include "frameworks/bridge/js_frontend/engine/jsi/ark_js_runtime.h"
60 #include "frameworks/bridge/js_frontend/engine/jsi/ark_js_value.h"
61 #include "frameworks/bridge/js_frontend/engine/jsi/jsi_base_utils.h"
62 #include "frameworks/core/components/xcomponent/xcomponent_component_client.h"
63 #include "frameworks/core/components_ng/base/view_stack_processor.h"
64 #include "frameworks/core/components_ng/pattern/xcomponent/xcomponent_pattern.h"
65 
66 #if defined(PREVIEW)
67 extern const char _binary_jsMockSystemPlugin_abc_start[];
68 extern const char _binary_jsMockSystemPlugin_abc_end[];
69 #endif
70 extern const char _binary_stateMgmt_abc_start[];
71 extern const char _binary_stateMgmt_abc_end[];
72 extern const char _binary_jsEnumStyle_abc_start[];
73 extern const char _binary_jsEnumStyle_abc_end[];
74 
75 namespace OHOS::Ace::Framework {
76 namespace {
77 
78 #if defined(ANDROID_PLATFORM)
79 const std::string ARK_DEBUGGER_LIB_PATH = "libark_debugger.so";
80 #elif defined(APP_USE_ARM)
81 const std::string ARK_DEBUGGER_LIB_PATH = "/system/lib/libark_debugger.z.so";
82 #else
83 const std::string ARK_DEBUGGER_LIB_PATH = "/system/lib64/libark_debugger.z.so";
84 #endif
85 const std::string FORM_ES_MODULE_CARD_PATH = "ets/widgets.abc";
86 const std::string FORM_ES_MODULE_PATH = "ets/modules.abc";
87 
88 const std::string ASSET_PATH_PREFIX = "/data/storage/el1/bundle/";
89 
90 constexpr uint32_t PREFIX_LETTER_NUMBER = 4;
91 std::mutex loadFormMutex_;
92 
93 // native implementation for js function: perfutil.print()
JsPerfPrint(const shared_ptr<JsRuntime> & runtime,const shared_ptr<JsValue> & thisObj,const std::vector<shared_ptr<JsValue>> & argv,int32_t argc)94 shared_ptr<JsValue> JsPerfPrint(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj,
95     const std::vector<shared_ptr<JsValue>>& argv, int32_t argc)
96 {
97     std::string ret = JsApiPerf::GetInstance().PrintToLogs();
98     return runtime->NewString(ret);
99 }
100 
101 // native implementation for js function: perfutil.sleep()
JsPerfSleep(const shared_ptr<JsRuntime> & runtime,const shared_ptr<JsValue> & thisObj,const std::vector<shared_ptr<JsValue>> & argv,int32_t argc)102 shared_ptr<JsValue> JsPerfSleep(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj,
103     const std::vector<shared_ptr<JsValue>>& argv, int32_t argc)
104 {
105     int32_t valInt = argv[0]->ToInt32(runtime);
106     usleep(valInt);
107     return runtime->NewNull();
108 }
109 
110 // native implementation for js function: perfutil.begin()
JsPerfBegin(const shared_ptr<JsRuntime> & runtime,const shared_ptr<JsValue> & thisObj,const std::vector<shared_ptr<JsValue>> & argv,int32_t argc)111 shared_ptr<JsValue> JsPerfBegin(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj,
112     const std::vector<shared_ptr<JsValue>>& argv, int32_t argc)
113 {
114     int64_t currentTime = GetMicroTickCount();
115     JsApiPerf::GetInstance().InsertJsBeginLog(argv[0]->ToString(runtime), currentTime);
116     return runtime->NewNull();
117 }
118 
119 // native implementation for js function: perfutil.end()
JsPerfEnd(const shared_ptr<JsRuntime> & runtime,const shared_ptr<JsValue> & thisObj,const std::vector<shared_ptr<JsValue>> & argv,int32_t argc)120 shared_ptr<JsValue> JsPerfEnd(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj,
121     const std::vector<shared_ptr<JsValue>>& argv, int32_t argc)
122 {
123     int64_t currentTime = GetMicroTickCount();
124     JsApiPerf::GetInstance().InsertJsEndLog(argv[0]->ToString(runtime), currentTime);
125     return runtime->NewNull();
126 }
127 
RequireNativeModule(const shared_ptr<JsRuntime> & runtime,const shared_ptr<JsValue> & thisObj,const std::vector<shared_ptr<JsValue>> & argv,int32_t argc)128 shared_ptr<JsValue> RequireNativeModule(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj,
129     const std::vector<shared_ptr<JsValue>>& argv, int32_t argc)
130 {
131     std::string moduleName = argv[0]->ToString(runtime);
132 
133     // has already init module object
134     shared_ptr<JsValue> global = runtime->GetGlobal();
135     shared_ptr<JsValue> moduleObject = global->GetProperty(runtime, moduleName);
136     if (moduleObject != nullptr && moduleObject->IsObject(runtime)) {
137         LOGE("has already init moduleObject %{private}s", moduleName.c_str());
138         return moduleObject;
139     }
140 
141     // init module object first time
142     shared_ptr<JsValue> newObject = runtime->NewObject();
143     if (ModuleManager::GetInstance()->InitModule(runtime, newObject, moduleName)) {
144         global->SetProperty(runtime, moduleName, newObject);
145         return newObject;
146     }
147 
148     return runtime->NewNull();
149 }
150 } // namespace
151 
152 // -----------------------
153 // Start JsiDeclarativeEngineInstance
154 // -----------------------
155 std::map<std::string, std::string> JsiDeclarativeEngineInstance::mediaResourceFileMap_;
156 
157 std::unique_ptr<JsonValue> JsiDeclarativeEngineInstance::currentConfigResourceData_;
158 
159 bool JsiDeclarativeEngineInstance::isModulePreloaded_ = false;
160 bool JsiDeclarativeEngineInstance::isModuleInitialized_ = false;
161 shared_ptr<JsRuntime> JsiDeclarativeEngineInstance::globalRuntime_;
162 
163 // for async task callback executed after this instance has been destroyed.
164 thread_local void* cardRuntime_;
165 thread_local shared_ptr<JsRuntime> localRuntime_;
166 
167 // ArkTsCard start
168 thread_local bool isUnique_ = false;
169 // ArkTsCard end
170 
~JsiDeclarativeEngineInstance()171 JsiDeclarativeEngineInstance::~JsiDeclarativeEngineInstance()
172 {
173     CHECK_RUN_ON(JS);
174     LOG_DESTROY();
175 
176     if (runningPage_) {
177         runningPage_->OnJsEngineDestroy();
178     }
179 
180     if (stagingPage_) {
181         stagingPage_->OnJsEngineDestroy();
182     }
183 
184     if (runtime_) {
185         runtime_->RegisterUncaughtExceptionHandler(nullptr);
186         runtime_->Reset();
187     }
188     runtime_.reset();
189     runtime_ = nullptr;
190 }
191 
InitJsEnv(bool debuggerMode,const std::unordered_map<std::string,void * > & extraNativeObject,const shared_ptr<JsRuntime> & runtime)192 bool JsiDeclarativeEngineInstance::InitJsEnv(bool debuggerMode,
193     const std::unordered_map<std::string, void*>& extraNativeObject, const shared_ptr<JsRuntime>& runtime)
194 {
195     CHECK_RUN_ON(JS);
196     ACE_SCOPED_TRACE("JsiDeclarativeEngineInstance::InitJsEnv");
197     if (runtime != nullptr) {
198         LOGD("JsiDeclarativeEngineInstance InitJsEnv usingSharedRuntime");
199         runtime_ = runtime;
200         usingSharedRuntime_ = true;
201     } else {
202         LOGD("JsiDeclarativeEngineInstance InitJsEnv not usingSharedRuntime, create own");
203         runtime_.reset(new ArkJSRuntime());
204     }
205 
206     if (runtime_ == nullptr) {
207         LOGE("Js Engine cannot allocate JSI JSRuntime");
208         EventReport::SendJsException(JsExcepType::JS_ENGINE_INIT_ERR);
209         return false;
210     }
211 
212     runtime_->SetLogPrint(PrintLog);
213     std::string libraryPath = "";
214     if (debuggerMode) {
215         libraryPath = ARK_DEBUGGER_LIB_PATH;
216         SetDebuggerPostTask();
217     }
218     if (!usingSharedRuntime_ && !runtime_->Initialize(libraryPath, isDebugMode_, instanceId_)) {
219         LOGE("Js Engine initialize runtime failed");
220         return false;
221     }
222 
223     runtime_->SetEmbedderData(this);
224     runtime_->RegisterUncaughtExceptionHandler(JsiBaseUtils::ReportJsErrorEvent);
225 
226 #if !defined(PREVIEW)
227     for (const auto& [key, value] : extraNativeObject) {
228         shared_ptr<JsValue> nativeValue = runtime_->NewNativePointer(value);
229         runtime_->GetGlobal()->SetProperty(runtime_, key, nativeValue);
230     }
231 
232     runtime_->StartDebugger();
233 #endif
234 
235     LocalScope scope(std::static_pointer_cast<ArkJSRuntime>(runtime_)->GetEcmaVm());
236     if (!isModulePreloaded_ || !usingSharedRuntime_ || IsPlugin()) {
237         InitGlobalObjectTemplate();
238     }
239 
240     // no need to initialize functions on global when use shared runtime
241     if (usingSharedRuntime_ && isModuleInitialized_ && !isUnique_) { // ArtTsCard
242         LOGI("InitJsEnv SharedRuntime has initialized, skip...");
243     } else {
244         InitGroupJsBridge();
245         if (!isModulePreloaded_ || !usingSharedRuntime_ || IsPlugin() || isUnique_) { // ArtTsCard
246             InitConsoleModule();
247             InitAceModule();
248             InitJsExportsUtilObject();
249             InitJsNativeModuleObject();
250             InitPerfUtilModule();
251             InitJsContextModuleObject();
252         }
253     }
254 
255     if (usingSharedRuntime_) {
256         isModuleInitialized_ = true;
257     }
258 
259     // load resourceConfig
260     currentConfigResourceData_ = JsonUtil::CreateArray(true);
261     frontendDelegate_->LoadResourceConfiguration(mediaResourceFileMap_, currentConfigResourceData_);
262     isEngineInstanceInitialized_ = true;
263     return true;
264 }
265 
FireJsEvent(const std::string & eventStr)266 bool JsiDeclarativeEngineInstance::FireJsEvent(const std::string& eventStr)
267 {
268     return true;
269 }
270 
InitAceModule()271 void JsiDeclarativeEngineInstance::InitAceModule()
272 {
273     if (isUnique_ == false) {
274         uint8_t* codeStart;
275         int32_t codeLength;
276         codeStart = (uint8_t*)_binary_stateMgmt_abc_start;
277         codeLength = _binary_stateMgmt_abc_end - _binary_stateMgmt_abc_start;
278         bool stateMgmtResult = runtime_->EvaluateJsCode(codeStart, codeLength);
279         if (!stateMgmtResult) {
280             LOGE("EvaluateJsCode stateMgmt failed");
281         }
282         bool jsEnumStyleResult = runtime_->EvaluateJsCode(
283             (uint8_t*)_binary_jsEnumStyle_abc_start, _binary_jsEnumStyle_abc_end - _binary_jsEnumStyle_abc_start);
284         if (!jsEnumStyleResult) {
285             LOGE("EvaluateJsCode jsEnumStyle failed");
286         }
287     }
288 #if defined(PREVIEW)
289     std::string jsMockSystemPluginString(_binary_jsMockSystemPlugin_abc_start,
290         _binary_jsMockSystemPlugin_abc_end - _binary_jsMockSystemPlugin_abc_start);
291     bool jsMockSystemPlugin =
292         runtime_->EvaluateJsCode((uint8_t*)(jsMockSystemPluginString.c_str()), jsMockSystemPluginString.length());
293     if (!jsMockSystemPlugin) {
294         LOGE("EvaluateJsCode jsMockSystemPlugin failed");
295     }
296 #endif
297 }
298 
OHOS_ACE_PreloadAceModule(void * runtime)299 extern "C" ACE_FORCE_EXPORT void OHOS_ACE_PreloadAceModule(void* runtime)
300 {
301     LOGI("Ace ark lib loaded, PreloadAceModule.");
302     JsiDeclarativeEngineInstance::PreloadAceModule(runtime);
303 }
304 
PreloadAceModule(void * runtime)305 void JsiDeclarativeEngineInstance::PreloadAceModule(void* runtime)
306 {
307     if (isModulePreloaded_ && !IsPlugin()) {
308         LOGE("PreloadAceModule already preloaded");
309         return;
310     }
311     auto sharedRuntime = reinterpret_cast<NativeEngine*>(runtime);
312 
313     if (!sharedRuntime) {
314         LOGE("PreloadAceModule null runtime");
315         return;
316     }
317     std::shared_ptr<ArkJSRuntime> arkRuntime = std::make_shared<ArkJSRuntime>();
318     auto nativeArkEngine = static_cast<ArkNativeEngine*>(sharedRuntime);
319     EcmaVM* vm = const_cast<EcmaVM*>(nativeArkEngine->GetEcmaVm());
320     if (vm == nullptr) {
321         LOGE("PreloadAceModule NativeDeclarativeEngine Initialize, vm is null");
322         return;
323     }
324     if (!arkRuntime->InitializeFromExistVM(vm)) {
325         LOGE("PreloadAceModule Ark Engine initialize runtime failed");
326         return;
327     }
328     LocalScope scope(vm);
329     globalRuntime_ = arkRuntime;
330     // preload js views
331     JsRegisterViews(JSNApi::GetGlobalObject(vm));
332 
333     // preload aceConsole
334     shared_ptr<JsValue> global = arkRuntime->GetGlobal();
335     shared_ptr<JsValue> aceConsoleObj = arkRuntime->NewObject();
336     aceConsoleObj->SetProperty(arkRuntime, "log", arkRuntime->NewFunction(JsiBaseUtils::JsInfoLogPrint));
337     aceConsoleObj->SetProperty(arkRuntime, "debug", arkRuntime->NewFunction(JsiBaseUtils::JsDebugLogPrint));
338     aceConsoleObj->SetProperty(arkRuntime, "info", arkRuntime->NewFunction(JsiBaseUtils::JsInfoLogPrint));
339     aceConsoleObj->SetProperty(arkRuntime, "warn", arkRuntime->NewFunction(JsiBaseUtils::JsWarnLogPrint));
340     aceConsoleObj->SetProperty(arkRuntime, "error", arkRuntime->NewFunction(JsiBaseUtils::JsErrorLogPrint));
341     global->SetProperty(arkRuntime, "aceConsole", aceConsoleObj);
342 
343     // preload aceTrace
344     shared_ptr<JsValue> aceTraceObj = arkRuntime->NewObject();
345     aceTraceObj->SetProperty(arkRuntime, "begin", arkRuntime->NewFunction(JsiBaseUtils::JsTraceBegin));
346     aceTraceObj->SetProperty(arkRuntime, "end", arkRuntime->NewFunction(JsiBaseUtils::JsTraceEnd));
347     global->SetProperty(arkRuntime, "aceTrace", aceTraceObj);
348 
349     // preload getContext
350     JsiContextModule::GetInstance()->InitContextModule(arkRuntime, global);
351 
352     // preload perfutil
353     shared_ptr<JsValue> perfObj = arkRuntime->NewObject();
354     perfObj->SetProperty(arkRuntime, "printlog", arkRuntime->NewFunction(JsPerfPrint));
355     perfObj->SetProperty(arkRuntime, "sleep", arkRuntime->NewFunction(JsPerfSleep));
356     perfObj->SetProperty(arkRuntime, "begin", arkRuntime->NewFunction(JsPerfBegin));
357     perfObj->SetProperty(arkRuntime, "end", arkRuntime->NewFunction(JsPerfEnd));
358     global->SetProperty(arkRuntime, "perfutil", perfObj);
359 
360     // preload exports and requireNative
361     shared_ptr<JsValue> exportsUtilObj = arkRuntime->NewObject();
362     global->SetProperty(arkRuntime, "exports", exportsUtilObj);
363     global->SetProperty(arkRuntime, "requireNativeModule", arkRuntime->NewFunction(RequireNativeModule));
364 
365     // preload js enums
366     bool jsEnumStyleResult = arkRuntime->EvaluateJsCode(
367         (uint8_t*)_binary_jsEnumStyle_abc_start, _binary_jsEnumStyle_abc_end - _binary_jsEnumStyle_abc_start);
368     if (!jsEnumStyleResult) {
369         LOGE("EvaluateJsCode jsEnumStyle failed");
370         globalRuntime_ = nullptr;
371         return;
372     }
373 
374     // preload state management
375     uint8_t* codeStart;
376     int32_t codeLength;
377     codeStart = (uint8_t*)_binary_stateMgmt_abc_start;
378     codeLength = _binary_stateMgmt_abc_end - _binary_stateMgmt_abc_start;
379     bool evalResult = arkRuntime->EvaluateJsCode(codeStart, codeLength);
380     if (!evalResult) {
381         LOGE("PreloadAceModule EvaluateJsCode stateMgmt failed");
382     }
383 
384     isModulePreloaded_ = evalResult;
385     globalRuntime_ = nullptr;
386     LOGI("PreloadAceModule loaded:%{public}d", isModulePreloaded_);
387     localRuntime_ = arkRuntime;
388     cardRuntime_ = runtime;
389 }
390 
InitConsoleModule()391 void JsiDeclarativeEngineInstance::InitConsoleModule()
392 {
393     ACE_SCOPED_TRACE("JsiDeclarativeEngineInstance::InitConsoleModule");
394     LOGD("JsiDeclarativeEngineInstance InitConsoleModule");
395     shared_ptr<JsValue> global = runtime_->GetGlobal();
396 
397     // app log method
398     if (!usingSharedRuntime_) {
399         shared_ptr<JsValue> consoleObj = runtime_->NewObject();
400         consoleObj->SetProperty(runtime_, "log", runtime_->NewFunction(JsiBaseUtils::AppInfoLogPrint));
401         consoleObj->SetProperty(runtime_, "debug", runtime_->NewFunction(JsiBaseUtils::AppDebugLogPrint));
402         consoleObj->SetProperty(runtime_, "info", runtime_->NewFunction(JsiBaseUtils::AppInfoLogPrint));
403         consoleObj->SetProperty(runtime_, "warn", runtime_->NewFunction(JsiBaseUtils::AppWarnLogPrint));
404         consoleObj->SetProperty(runtime_, "error", runtime_->NewFunction(JsiBaseUtils::AppErrorLogPrint));
405         global->SetProperty(runtime_, "console", consoleObj);
406     }
407 
408     if (isModulePreloaded_ && usingSharedRuntime_ && !IsPlugin() && !isUnique_) { // ArkTsCard
409         LOGD("console module has already preloaded");
410         return;
411     }
412 
413     // js framework log method
414     shared_ptr<JsValue> aceConsoleObj = runtime_->NewObject();
415     aceConsoleObj->SetProperty(runtime_, "log", runtime_->NewFunction(JsiBaseUtils::JsInfoLogPrint));
416     aceConsoleObj->SetProperty(runtime_, "debug", runtime_->NewFunction(JsiBaseUtils::JsDebugLogPrint));
417     aceConsoleObj->SetProperty(runtime_, "info", runtime_->NewFunction(JsiBaseUtils::JsInfoLogPrint));
418     aceConsoleObj->SetProperty(runtime_, "warn", runtime_->NewFunction(JsiBaseUtils::JsWarnLogPrint));
419     aceConsoleObj->SetProperty(runtime_, "error", runtime_->NewFunction(JsiBaseUtils::JsErrorLogPrint));
420     global->SetProperty(runtime_, "aceConsole", aceConsoleObj);
421 
422     // js framework trace method
423     shared_ptr<JsValue> aceTraceObj = runtime_->NewObject();
424     aceTraceObj->SetProperty(runtime_, "begin", runtime_->NewFunction(JsiBaseUtils::JsTraceBegin));
425     aceTraceObj->SetProperty(runtime_, "end", runtime_->NewFunction(JsiBaseUtils::JsTraceEnd));
426     global->SetProperty(runtime_, "aceTrace", aceTraceObj);
427 }
428 
InitConsoleModule(ArkNativeEngine * engine)429 void JsiDeclarativeEngineInstance::InitConsoleModule(ArkNativeEngine* engine)
430 {
431     ACE_SCOPED_TRACE("JsiDeclarativeEngineInstance::RegisterConsoleModule");
432     LOGD("JsiDeclarativeEngineInstance RegisterConsoleModule to nativeEngine");
433     NativeValue* global = engine->GetGlobal();
434     if (global->TypeOf() != NATIVE_OBJECT) {
435         LOGE("global is not NativeObject");
436         return;
437     }
438     auto nativeGlobal = reinterpret_cast<NativeObject*>(global->GetInterface(NativeObject::INTERFACE_ID));
439 
440     // app log method
441     NativeValue* console = engine->CreateObject();
442     auto consoleObj = reinterpret_cast<NativeObject*>(console->GetInterface(NativeObject::INTERFACE_ID));
443     consoleObj->SetProperty("log", engine->CreateFunction("log", strlen("log"), AppInfoLogPrint, nullptr));
444     consoleObj->SetProperty("debug", engine->CreateFunction("debug", strlen("debug"), AppDebugLogPrint, nullptr));
445     consoleObj->SetProperty("info", engine->CreateFunction("info", strlen("info"), AppInfoLogPrint, nullptr));
446     consoleObj->SetProperty("warn", engine->CreateFunction("warn", strlen("warn"), AppWarnLogPrint, nullptr));
447     consoleObj->SetProperty("error", engine->CreateFunction("error", strlen("error"), AppErrorLogPrint, nullptr));
448     nativeGlobal->SetProperty("console", console);
449 }
450 
InitPerfUtilModule()451 void JsiDeclarativeEngineInstance::InitPerfUtilModule()
452 {
453     ACE_SCOPED_TRACE("JsiDeclarativeEngineInstance::InitPerfUtilModule");
454     LOGD("JsiDeclarativeEngineInstance InitPerfUtilModule");
455     shared_ptr<JsValue> perfObj = runtime_->NewObject();
456     perfObj->SetProperty(runtime_, "printlog", runtime_->NewFunction(JsPerfPrint));
457     perfObj->SetProperty(runtime_, "sleep", runtime_->NewFunction(JsPerfSleep));
458     perfObj->SetProperty(runtime_, "begin", runtime_->NewFunction(JsPerfBegin));
459     perfObj->SetProperty(runtime_, "end", runtime_->NewFunction(JsPerfEnd));
460 
461     shared_ptr<JsValue> global = runtime_->GetGlobal();
462     global->SetProperty(runtime_, "perfutil", perfObj);
463 }
464 
InitJsExportsUtilObject()465 void JsiDeclarativeEngineInstance::InitJsExportsUtilObject()
466 {
467     shared_ptr<JsValue> exportsUtilObj = runtime_->NewObject();
468     shared_ptr<JsValue> global = runtime_->GetGlobal();
469     global->SetProperty(runtime_, "exports", exportsUtilObj);
470 }
471 
InitJsNativeModuleObject()472 void JsiDeclarativeEngineInstance::InitJsNativeModuleObject()
473 {
474     shared_ptr<JsValue> global = runtime_->GetGlobal();
475     global->SetProperty(runtime_, "requireNativeModule", runtime_->NewFunction(RequireNativeModule));
476     auto context = PipelineBase::GetCurrentContext();
477     CHECK_NULL_VOID(context);
478     if (!usingSharedRuntime_) {
479         if (!context->IsFormRender()) {
480             JsiTimerModule::GetInstance()->InitTimerModule(runtime_, global);
481         } else {
482             LOGI("Not supported TimerModule when form render");
483         }
484 
485         JsiSyscapModule::GetInstance()->InitSyscapModule(runtime_, global);
486     }
487 }
488 
InitJsContextModuleObject()489 void JsiDeclarativeEngineInstance::InitJsContextModuleObject()
490 {
491     JsiContextModule::GetInstance()->InitContextModule(runtime_, runtime_->GetGlobal());
492 }
493 
InitGlobalObjectTemplate()494 void JsiDeclarativeEngineInstance::InitGlobalObjectTemplate()
495 {
496     auto runtime = std::static_pointer_cast<ArkJSRuntime>(runtime_);
497     JsRegisterViews(JSNApi::GetGlobalObject(runtime->GetEcmaVm()));
498 }
499 
InitGroupJsBridge()500 void JsiDeclarativeEngineInstance::InitGroupJsBridge()
501 {
502     auto groupJsBridge = DynamicCast<JsiDeclarativeGroupJsBridge>(frontendDelegate_->GetGroupJsBridge());
503     if (groupJsBridge == nullptr || groupJsBridge->InitializeGroupJsBridge(runtime_) == JS_CALL_FAIL) {
504         LOGE("Js Engine Initialize GroupJsBridge failed!");
505         EventReport::SendJsException(JsExcepType::JS_ENGINE_INIT_ERR);
506     }
507 }
508 
RootViewHandle(panda::Local<panda::ObjectRef> value)509 void JsiDeclarativeEngineInstance::RootViewHandle(panda::Local<panda::ObjectRef> value)
510 {
511     LOGD("RootViewHandle");
512     RefPtr<JsAcePage> page = JsiDeclarativeEngineInstance::GetStagingPage(Container::CurrentId());
513     if (page != nullptr) {
514         auto arkRuntime = std::static_pointer_cast<ArkJSRuntime>(GetCurrentRuntime());
515         if (!arkRuntime) {
516             LOGE("ark engine is null");
517             return;
518         }
519         auto engine = EngineHelper::GetCurrentEngine();
520         auto jsiEngine = AceType::DynamicCast<JsiDeclarativeEngine>(engine);
521         if (!jsiEngine) {
522             LOGE("jsiEngine is null");
523             return;
524         }
525         auto engineInstance = jsiEngine->GetEngineInstance();
526         if (engineInstance == nullptr) {
527             LOGE("engineInstance is nullptr");
528             return;
529         }
530         engineInstance->SetRootView(page->GetPageId(), panda::Global<panda::ObjectRef>(arkRuntime->GetEcmaVm(), value));
531     }
532 }
533 
DestroyRootViewHandle(int32_t pageId)534 void JsiDeclarativeEngineInstance::DestroyRootViewHandle(int32_t pageId)
535 {
536     CHECK_RUN_ON(JS);
537     JAVASCRIPT_EXECUTION_SCOPE_STATIC;
538     if (rootViewMap_.count(pageId) != 0) {
539         auto arkRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime_);
540         if (!arkRuntime) {
541             LOGE("ark engine is null");
542             return;
543         }
544         panda::Local<panda::ObjectRef> rootView = rootViewMap_[pageId].ToLocal(arkRuntime->GetEcmaVm());
545         auto* jsView = static_cast<JSView*>(rootView->GetNativePointerField(0));
546         if (jsView != nullptr) {
547             jsView->Destroy(nullptr);
548         }
549         rootViewMap_[pageId].FreeGlobalHandleAddr();
550         rootViewMap_.erase(pageId);
551     }
552 }
553 
DestroyAllRootViewHandle()554 void JsiDeclarativeEngineInstance::DestroyAllRootViewHandle()
555 {
556     CHECK_RUN_ON(JS);
557     JAVASCRIPT_EXECUTION_SCOPE_STATIC;
558     if (rootViewMap_.size() > 0) {
559         LOGI("DestroyAllRootViewHandle release left %{private}zu views ", rootViewMap_.size());
560     }
561     auto arkRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime_);
562     if (!arkRuntime) {
563         LOGE("ark engine is null");
564         return;
565     }
566     for (const auto& pair : rootViewMap_) {
567         auto globalRootView = pair.second;
568         panda::Local<panda::ObjectRef> rootView = globalRootView.ToLocal(arkRuntime->GetEcmaVm());
569         auto* jsView = static_cast<JSView*>(rootView->GetNativePointerField(0));
570         if (jsView != nullptr) {
571             jsView->Destroy(nullptr);
572         }
573         globalRootView.FreeGlobalHandleAddr();
574     }
575     rootViewMap_.clear();
576 }
577 
FlushReload()578 void JsiDeclarativeEngineInstance::FlushReload()
579 {
580     CHECK_RUN_ON(JS);
581     JAVASCRIPT_EXECUTION_SCOPE_STATIC;
582     if (rootViewMap_.empty()) {
583         LOGW("FlushReload release left %{private}zu views ", rootViewMap_.size());
584         return;
585     }
586     auto arkRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime_);
587     if (!arkRuntime) {
588         LOGE("ark runtime is null");
589         return;
590     }
591     for (const auto& pair : rootViewMap_) {
592         auto globalRootView = pair.second;
593         panda::Local<panda::ObjectRef> rootView = globalRootView.ToLocal(arkRuntime->GetEcmaVm());
594         auto* jsView = static_cast<JSView*>(rootView->GetNativePointerField(0));
595         if (jsView != nullptr) {
596             jsView->MarkNeedUpdate();
597         }
598     }
599     LOGI("JSI engine finished flush reload");
600 }
601 
GetI18nStringResource(const std::string & targetStringKey,const std::string & targetStringValue)602 std::unique_ptr<JsonValue> JsiDeclarativeEngineInstance::GetI18nStringResource(
603     const std::string& targetStringKey, const std::string& targetStringValue)
604 {
605     auto resourceI18nFileNum = currentConfigResourceData_->GetArraySize();
606     for (int i = 0; i < resourceI18nFileNum; i++) {
607         auto priorResource = currentConfigResourceData_->GetArrayItem(i);
608         if ((priorResource->Contains(targetStringKey))) {
609             auto valuePair = priorResource->GetValue(targetStringKey);
610             if (valuePair->Contains(targetStringValue)) {
611                 return valuePair->GetValue(targetStringValue);
612             }
613         }
614     }
615 
616     return JsonUtil::Create(true);
617 }
618 
GetMediaResource(const std::string & targetFileName)619 std::string JsiDeclarativeEngineInstance::GetMediaResource(const std::string& targetFileName)
620 {
621     auto iter = mediaResourceFileMap_.find(targetFileName);
622 
623     if (iter != mediaResourceFileMap_.end()) {
624         return iter->second;
625     }
626 
627     return std::string();
628 }
629 
GetRunningPage(int32_t instanceId)630 RefPtr<JsAcePage> JsiDeclarativeEngineInstance::GetRunningPage(int32_t instanceId)
631 {
632     auto engine = EngineHelper::GetEngine(instanceId);
633     auto jsiEngine = AceType::DynamicCast<JsiDeclarativeEngine>(engine);
634     if (!jsiEngine) {
635         LOGE("jsiEngine is null");
636         return nullptr;
637     }
638     auto engineInstance = jsiEngine->GetEngineInstance();
639     if (engineInstance == nullptr) {
640         LOGE("engineInstance is nullptr");
641         return nullptr;
642     }
643     return engineInstance->GetRunningPage();
644 }
645 
GetStagingPage(int32_t instanceId)646 RefPtr<JsAcePage> JsiDeclarativeEngineInstance::GetStagingPage(int32_t instanceId)
647 {
648     auto engine = EngineHelper::GetEngine(instanceId);
649     auto jsiEngine = AceType::DynamicCast<JsiDeclarativeEngine>(engine);
650     if (!jsiEngine) {
651         LOGE("jsiEngine is null");
652         return nullptr;
653     }
654     auto engineInstance = jsiEngine->GetEngineInstance();
655     LOGD("GetStagingPage id:%{public}d", instanceId);
656     if (engineInstance == nullptr) {
657         LOGE("engineInstance is nullptr");
658         return nullptr;
659     }
660     return engineInstance->GetStagingPage();
661 }
662 
GetCurrentRuntime()663 shared_ptr<JsRuntime> JsiDeclarativeEngineInstance::GetCurrentRuntime()
664 {
665     auto jsRuntime = InnerGetCurrentRuntime();
666     if (isUnique_ && jsRuntime) {
667         return jsRuntime;
668     }
669 
670     // ArkTsCard
671     if (isUnique_ && localRuntime_) {
672         return localRuntime_;
673     }
674 
675     // Preload
676     if (globalRuntime_) {
677         return globalRuntime_;
678     }
679 
680     return jsRuntime == nullptr ? localRuntime_ : jsRuntime;
681 }
682 
InnerGetCurrentRuntime()683 shared_ptr<JsRuntime> JsiDeclarativeEngineInstance::InnerGetCurrentRuntime()
684 {
685     auto engine = EngineHelper::GetCurrentEngine();
686     auto jsiEngine = AceType::DynamicCast<JsiDeclarativeEngine>(engine);
687     if (!jsiEngine) {
688         LOGE("jsiEngine is null");
689         return nullptr;
690     }
691 
692     auto engineInstance = jsiEngine->GetEngineInstance();
693     if (engineInstance == nullptr) {
694         LOGE("engineInstance is nullptr");
695         return nullptr;
696     }
697 
698     if (isUnique_ && !engineInstance->IsEngineInstanceInitialized()) {
699         LOGI("engineInstance is not Initialized");
700         return nullptr;
701     }
702 
703     return engineInstance->GetJsRuntime();
704 }
705 
PostJsTask(const shared_ptr<JsRuntime> & runtime,std::function<void ()> && task)706 void JsiDeclarativeEngineInstance::PostJsTask(const shared_ptr<JsRuntime>& runtime, std::function<void()>&& task)
707 {
708     LOGD("PostJsTask");
709     if (runtime == nullptr) {
710         LOGE("jsRuntime is nullptr");
711         return;
712     }
713     auto engineInstance = static_cast<JsiDeclarativeEngineInstance*>(runtime->GetEmbedderData());
714     if (engineInstance == nullptr) {
715         LOGE("engineInstance is nullptr");
716         return;
717     }
718     engineInstance->GetDelegate()->PostJsTask(std::move(task));
719 }
720 
TriggerPageUpdate(const shared_ptr<JsRuntime> & runtime)721 void JsiDeclarativeEngineInstance::TriggerPageUpdate(const shared_ptr<JsRuntime>& runtime)
722 {
723     LOGD("TriggerPageUpdate");
724     CHECK_NULL_VOID(runtime);
725     auto engineInstance = static_cast<JsiDeclarativeEngineInstance*>(runtime->GetEmbedderData());
726     CHECK_NULL_VOID(engineInstance);
727     auto page = engineInstance->GetRunningPage();
728     CHECK_NULL_VOID(page);
729     engineInstance->GetDelegate()->TriggerPageUpdate(page->GetPageId());
730 }
731 
GetPipelineContext(const shared_ptr<JsRuntime> & runtime)732 RefPtr<PipelineBase> JsiDeclarativeEngineInstance::GetPipelineContext(const shared_ptr<JsRuntime>& runtime)
733 {
734     LOGD("GetPipelineContext");
735     if (runtime == nullptr) {
736         LOGE("jsRuntime is nullptr");
737         return nullptr;
738     }
739     auto engineInstance = static_cast<JsiDeclarativeEngineInstance*>(runtime->GetEmbedderData());
740     if (engineInstance == nullptr) {
741         LOGE("engineInstance is nullptr");
742         return nullptr;
743     }
744     return engineInstance->GetDelegate()->GetPipelineContext();
745 }
746 
FlushCommandBuffer(void * context,const std::string & command)747 void JsiDeclarativeEngineInstance::FlushCommandBuffer(void* context, const std::string& command)
748 {
749     return;
750 }
751 
IsPlugin()752 bool JsiDeclarativeEngineInstance::IsPlugin()
753 {
754     return (ContainerScope::CurrentId() >= MIN_PLUGIN_SUBCONTAINER_ID);
755 }
756 
SetDebuggerPostTask()757 void JsiDeclarativeEngineInstance::SetDebuggerPostTask()
758 {
759     auto weakDelegate = AceType::WeakClaim(AceType::RawPtr(frontendDelegate_));
760     auto&& postTask = [weakDelegate](std::function<void()>&& task) {
761         auto delegate = weakDelegate.Upgrade();
762         if (delegate == nullptr) {
763             LOGE("delegate is nullptr");
764             return;
765         }
766         delegate->PostJsTask(std::move(task));
767     };
768     std::static_pointer_cast<ArkJSRuntime>(runtime_)->SetDebuggerPostTask(postTask);
769 }
770 
RegisterFaPlugin()771 void JsiDeclarativeEngineInstance::RegisterFaPlugin()
772 {
773     shared_ptr<JsValue> global = runtime_->GetGlobal();
774     shared_ptr<JsValue> requireNapiFunc = global->GetProperty(runtime_, "requireNapi");
775     if (!requireNapiFunc || !requireNapiFunc->IsFunction(runtime_)) {
776         LOGW("requireNapi func not found");
777     }
778     std::vector<shared_ptr<JsValue>> argv = { runtime_->NewString("FeatureAbility") };
779     requireNapiFunc->Call(runtime_, global, argv, argv.size());
780 }
781 
782 // -----------------------
783 // Start JsiDeclarativeEngine
784 // -----------------------
~JsiDeclarativeEngine()785 JsiDeclarativeEngine::~JsiDeclarativeEngine()
786 {
787     CHECK_RUN_ON(JS);
788     LOG_DESTROY();
789 }
790 
Destroy()791 void JsiDeclarativeEngine::Destroy()
792 {
793     LOGI("JsiDeclarativeEngine Destroy");
794     CHECK_RUN_ON(JS);
795 
796 #ifdef USE_ARK_ENGINE
797     JSLocalStorage::RemoveStorage(instanceId_);
798     JsiContextModule::RemoveContext(instanceId_);
799 #endif
800 
801     engineInstance_->GetDelegate()->RemoveTaskObserver();
802     engineInstance_->DestroyAllRootViewHandle();
803     if (isUnique_) {
804         RunFullGarbageCollection();
805     }
806 
807     if (!runtime_ && nativeEngine_ != nullptr) {
808 #if !defined(PREVIEW)
809         nativeEngine_->CancelCheckUVLoop();
810 #endif
811         nativeEngine_->DeleteEngine();
812         delete nativeEngine_;
813         nativeEngine_ = nullptr;
814     }
815 }
816 
Initialize(const RefPtr<FrontendDelegate> & delegate)817 bool JsiDeclarativeEngine::Initialize(const RefPtr<FrontendDelegate>& delegate)
818 {
819     CHECK_RUN_ON(JS);
820     ACE_SCOPED_TRACE("JsiDeclarativeEngine::Initialize");
821     LOGI("JsiDeclarativeEngine Initialize");
822     ACE_DCHECK(delegate);
823     engineInstance_ = AceType::MakeRefPtr<JsiDeclarativeEngineInstance>(delegate);
824     auto sharedRuntime = reinterpret_cast<NativeEngine*>(runtime_);
825     std::shared_ptr<ArkJSRuntime> arkRuntime;
826     EcmaVM* vm = nullptr;
827     if (!sharedRuntime) {
828         LOGI("Initialize will not use sharedRuntime");
829     } else {
830         LOGI("Initialize will use sharedRuntime");
831         arkRuntime = std::make_shared<ArkJSRuntime>();
832         if (isUnique_ && reinterpret_cast<NativeEngine*>(cardRuntime_) != nullptr) {
833             sharedRuntime = reinterpret_cast<NativeEngine*>(cardRuntime_);
834         }
835         auto nativeArkEngine = static_cast<ArkNativeEngine*>(sharedRuntime);
836         vm = const_cast<EcmaVM*>(nativeArkEngine->GetEcmaVm());
837         if (vm == nullptr) {
838             LOGE("NativeDeclarativeEngine Initialize, vm is null");
839             return false;
840         }
841         if (!arkRuntime->InitializeFromExistVM(vm)) {
842             LOGE("Ark Engine initialize runtime failed");
843             return false;
844         }
845         nativeEngine_ = nativeArkEngine;
846     }
847     engineInstance_->SetInstanceId(instanceId_);
848     engineInstance_->SetDebugMode(NeedDebugBreakPoint());
849     bool result = engineInstance_->InitJsEnv(IsDebugVersion(), GetExtraNativeObject(), arkRuntime);
850     if (!result) {
851         LOGE("JsiDeclarativeEngine Initialize, init js env failed");
852         return false;
853     }
854 
855     auto runtime = engineInstance_->GetJsRuntime();
856     vm = vm ? vm : const_cast<EcmaVM*>(std::static_pointer_cast<ArkJSRuntime>(runtime)->GetEcmaVm());
857     if (vm == nullptr) {
858         LOGE("JsiDeclarativeEngine Initialize, vm is null");
859         return false;
860     }
861 
862     if (nativeEngine_ == nullptr) {
863         nativeEngine_ = new ArkNativeEngine(vm, static_cast<void*>(this));
864     }
865     engineInstance_->SetNativeEngine(nativeEngine_);
866     if (!sharedRuntime) {
867         SetPostTask(nativeEngine_);
868 #if !defined(PREVIEW)
869         nativeEngine_->CheckUVLoop();
870 #endif
871 
872         if (delegate && delegate->GetAssetManager()) {
873             std::vector<std::string> packagePath = delegate->GetAssetManager()->GetLibPath();
874             auto appLibPathKey = delegate->GetAssetManager()->GetAppLibPathKey();
875             if (!packagePath.empty()) {
876                 auto arkNativeEngine = static_cast<ArkNativeEngine*>(nativeEngine_);
877                 arkNativeEngine->SetPackagePath(appLibPathKey, packagePath);
878             }
879         }
880 
881         RegisterWorker();
882         engineInstance_->RegisterFaPlugin();
883     } else {
884         LOGI("Using sharedRuntime, UVLoop handled by AbilityRuntime");
885     }
886 
887     return result;
888 }
889 
SetPostTask(NativeEngine * nativeEngine)890 void JsiDeclarativeEngine::SetPostTask(NativeEngine* nativeEngine)
891 {
892     LOGI("SetPostTask");
893     auto weakDelegate = AceType::WeakClaim(AceType::RawPtr(engineInstance_->GetDelegate()));
894     auto&& postTask = [weakDelegate, weakEngine = AceType::WeakClaim(this), id = instanceId_](bool needSync) {
895         auto delegate = weakDelegate.Upgrade();
896         if (delegate == nullptr) {
897             LOGE("delegate is nullptr");
898             return;
899         }
900         delegate->PostJsTask([weakEngine, needSync, id]() {
901             auto jsEngine = weakEngine.Upgrade();
902             if (jsEngine == nullptr) {
903                 LOGW("jsEngine is nullptr");
904                 return;
905             }
906             auto nativeEngine = jsEngine->GetNativeEngine();
907             if (nativeEngine == nullptr) {
908                 return;
909             }
910             ContainerScope scope(id);
911             nativeEngine->Loop(LOOP_NOWAIT, needSync);
912         });
913     };
914     nativeEngine_->SetPostTask(postTask);
915 }
916 
RegisterInitWorkerFunc()917 void JsiDeclarativeEngine::RegisterInitWorkerFunc()
918 {
919     auto weakInstance = AceType::WeakClaim(AceType::RawPtr(engineInstance_));
920     bool debugVersion = IsDebugVersion();
921     bool debugMode = NeedDebugBreakPoint();
922     std::string libraryPath = "";
923     if (debugVersion) {
924         libraryPath = ARK_DEBUGGER_LIB_PATH;
925     }
926     auto&& initWorkerFunc = [weakInstance, debugMode, libraryPath](NativeEngine* nativeEngine) {
927         LOGI("WorkerCore RegisterInitWorkerFunc called");
928         if (nativeEngine == nullptr) {
929             LOGE("nativeEngine is nullptr");
930             return;
931         }
932         auto arkNativeEngine = static_cast<ArkNativeEngine*>(nativeEngine);
933         if (arkNativeEngine == nullptr) {
934             LOGE("arkNativeEngine is nullptr");
935             return;
936         }
937         auto instance = weakInstance.Upgrade();
938         if (instance == nullptr) {
939             LOGE("instance is nullptr");
940             return;
941         }
942 #ifdef OHOS_PLATFORM
943         ConnectServerManager::Get().AddInstance(gettid());
944         auto vm = const_cast<EcmaVM*>(arkNativeEngine->GetEcmaVm());
945         auto workerPostTask = [nativeEngine](std::function<void()>&& callback) {
946             nativeEngine->CallDebuggerPostTaskFunc(std::move(callback));
947         };
948         panda::JSNApi::StartDebugger(libraryPath.c_str(), vm, debugMode, gettid(), workerPostTask);
949 #endif
950         instance->InitConsoleModule(arkNativeEngine);
951 
952         std::vector<uint8_t> buffer((uint8_t*)_binary_jsEnumStyle_abc_start, (uint8_t*)_binary_jsEnumStyle_abc_end);
953         auto stateMgmtResult = arkNativeEngine->RunBufferScript(buffer);
954         if (stateMgmtResult == nullptr) {
955             LOGE("init worker error");
956         }
957     };
958     nativeEngine_->SetInitWorkerFunc(initWorkerFunc);
959 }
960 
961 #ifdef OHOS_PLATFORM
RegisterOffWorkerFunc()962 void JsiDeclarativeEngine::RegisterOffWorkerFunc()
963 {
964     auto weakInstance = AceType::WeakClaim(AceType::RawPtr(engineInstance_));
965     bool debugVersion = IsDebugVersion();
966     auto&& offWorkerFunc = [debugVersion](NativeEngine* nativeEngine) {
967         LOGI("WorkerCore RegisterOffWorkerFunc called");
968         if (!debugVersion) {
969             return;
970         }
971         if (nativeEngine == nullptr) {
972             LOGE("nativeEngine is nullptr");
973             return;
974         }
975         auto arkNativeEngine = static_cast<ArkNativeEngine*>(nativeEngine);
976         if (arkNativeEngine == nullptr) {
977             LOGE("arkNativeEngine is nullptr");
978             return;
979         }
980         ConnectServerManager::Get().RemoveInstance(gettid());
981         auto vm = const_cast<EcmaVM*>(arkNativeEngine->GetEcmaVm());
982         panda::JSNApi::StopDebugger(vm);
983     };
984     nativeEngine_->SetOffWorkerFunc(offWorkerFunc);
985 }
986 #endif
987 
RegisterAssetFunc()988 void JsiDeclarativeEngine::RegisterAssetFunc()
989 {
990     auto weakDelegate = AceType::WeakClaim(AceType::RawPtr(engineInstance_->GetDelegate()));
991     auto&& assetFunc = [weakDelegate](const std::string& uri, std::vector<uint8_t>& content, std::string& ami) {
992         LOGI("WorkerCore RegisterAssetFunc called");
993         auto delegate = weakDelegate.Upgrade();
994         if (delegate == nullptr) {
995             LOGE("delegate is nullptr");
996             return;
997         }
998         size_t index = uri.find_last_of(".");
999         if (index == std::string::npos) {
1000             LOGE("invalid uri");
1001         } else {
1002             delegate->GetResourceData(uri.substr(0, index) + ".abc", content, ami);
1003         }
1004     };
1005     nativeEngine_->SetGetAssetFunc(assetFunc);
1006 }
1007 
RegisterWorker()1008 void JsiDeclarativeEngine::RegisterWorker()
1009 {
1010     RegisterInitWorkerFunc();
1011 #ifdef OHOS_PLATFORM
1012     RegisterOffWorkerFunc();
1013 #endif
1014     RegisterAssetFunc();
1015 }
1016 
ExecuteAbc(const std::string & fileName)1017 bool JsiDeclarativeEngine::ExecuteAbc(const std::string& fileName)
1018 {
1019     auto runtime = engineInstance_->GetJsRuntime();
1020     auto delegate = engineInstance_->GetDelegate();
1021     std::vector<uint8_t> content;
1022     if (!delegate->GetAssetContent(fileName, content)) {
1023         LOGD("GetAssetContent \"%{public}s\" failed.", fileName.c_str());
1024         return true;
1025     }
1026 #ifdef OHOS_PLATFORM
1027     const std::string abcPath = delegate->GetAssetPath(fileName).append(fileName);
1028 #else
1029     const std::string& abcPath = fileName;
1030 #endif
1031     if (!runtime->EvaluateJsCode(content.data(), content.size(), abcPath, needUpdate_)) {
1032         LOGE("EvaluateJsCode \"%{public}s\" failed.", fileName.c_str());
1033         return false;
1034     }
1035     return true;
1036 }
1037 
ExecuteCardAbc(const std::string & fileName,int64_t cardId)1038 bool JsiDeclarativeEngine::ExecuteCardAbc(const std::string& fileName, int64_t cardId)
1039 {
1040     auto runtime = engineInstance_->GetJsRuntime();
1041     CHECK_NULL_RETURN(runtime, false);
1042 
1043     auto container = Container::Current();
1044     CHECK_NULL_RETURN(container, false);
1045 
1046     LOGI("JsiDeclarativeEngine::ExecuteCardAbc fileName = %{public}s", fileName.c_str());
1047     CardScope cardScope(cardId);
1048     std::string abcPath;
1049     std::vector<uint8_t> content;
1050     if (container->IsFRSCardContainer()) {
1051         LOGI("ExecuteCardAbc In FRS");
1052         auto frontEnd = AceType::DynamicCast<FormFrontendDeclarative>(container->GetCardFrontend(cardId).Upgrade());
1053         CHECK_NULL_RETURN(frontEnd, false);
1054         auto delegate = frontEnd->GetDelegate();
1055         CHECK_NULL_RETURN(delegate, false);
1056         if (frontEnd->IsBundle()) {
1057             if (!delegate->GetAssetContent(fileName, content)) {
1058                 LOGE("EvaluateJsCode GetAssetContent \"%{public}s\" failed.", fileName.c_str());
1059                 return false;
1060             }
1061             abcPath = delegate->GetAssetPath(fileName).append(fileName);
1062             if (!runtime->EvaluateJsCode(content.data(), content.size(), abcPath)) {
1063                 LOGE("ExecuteCardAbc EvaluateJsCode \"%{public}s\" failed.", fileName.c_str());
1064                 return false;
1065             }
1066             return true;
1067         }
1068         if (!delegate->GetAssetContent(FORM_ES_MODULE_CARD_PATH, content)) {
1069             LOGE("EvaluateJsCode GetAssetContent \"%{public}s\" failed.", FORM_ES_MODULE_CARD_PATH.c_str());
1070             return false;
1071         }
1072         const std::string bundleName = frontEnd->GetBundleName();
1073         const std::string moduleName = frontEnd->GetModuleName();
1074 #ifdef PREVIEW
1075         const std::string assetPath = delegate->GetAssetPath(FORM_ES_MODULE_CARD_PATH).append(FORM_ES_MODULE_CARD_PATH);
1076 #else
1077         const std::string assetPath =
1078             ASSET_PATH_PREFIX + bundleName + "/" + moduleName + "/" + FORM_ES_MODULE_CARD_PATH;
1079 #endif
1080         LOGI("bundleName = %{public}s, moduleName = %{public}s, assetPath = %{public}s", bundleName.c_str(),
1081             moduleName.c_str(), assetPath.c_str());
1082         auto arkRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1083         CHECK_NULL_RETURN(arkRuntime, false);
1084         arkRuntime->SetBundleName(bundleName);
1085         arkRuntime->SetAssetPath(assetPath);
1086         arkRuntime->SetBundle(false);
1087         arkRuntime->SetModuleName(moduleName);
1088         abcPath = fileName;
1089         if (fileName.rfind("ets/", 0) == 0) {
1090             abcPath = fileName.substr(PREFIX_LETTER_NUMBER);
1091         }
1092         LOGI("JsiDeclarativeEngine::ExecuteCardAbc abcPath = %{public}s", abcPath.c_str());
1093         {
1094             std::lock_guard<std::mutex> lock(loadFormMutex_);
1095             if (!arkRuntime->ExecuteModuleBuffer(content.data(), content.size(), abcPath, true)) {
1096                 LOGE("ExecuteCardAbc ExecuteModuleBuffer \"%{public}s\" failed.", fileName.c_str());
1097                 return false;
1098             }
1099         }
1100         return true;
1101     } else {
1102         LOGI("ExecuteCardAbc In HOST");
1103         auto frontEnd = AceType::DynamicCast<CardFrontendDeclarative>(container->GetCardFrontend(cardId).Upgrade());
1104         CHECK_NULL_RETURN(frontEnd, false);
1105         auto delegate = frontEnd->GetDelegate();
1106         CHECK_NULL_RETURN(delegate, false);
1107         if (!delegate->GetAssetContent(fileName, content)) {
1108             LOGE("EvaluateJsCode GetAssetContent \"%{public}s\" failed.", fileName.c_str());
1109             return false;
1110         }
1111         abcPath = delegate->GetAssetPath(fileName).append(fileName);
1112     }
1113 
1114     LOGI("JsiDeclarativeEngine::ExecuteCardAbc abcPath = %{public}s", abcPath.c_str());
1115     if (!runtime->EvaluateJsCode(content.data(), content.size(), abcPath)) {
1116         LOGE("ExecuteCardAbc EvaluateJsCode \"%{public}s\" failed.", fileName.c_str());
1117         return false;
1118     }
1119     return true;
1120 }
1121 
LoadJs(const std::string & url,const RefPtr<JsAcePage> & page,bool isMainPage)1122 void JsiDeclarativeEngine::LoadJs(const std::string& url, const RefPtr<JsAcePage>& page, bool isMainPage)
1123 {
1124     ACE_SCOPED_TRACE("JsiDeclarativeEngine::LoadJs");
1125     LOGI("JsiDeclarativeEngine LoadJs page:%{public}d", page->GetPageId());
1126     ACE_DCHECK(engineInstance_);
1127     engineInstance_->SetStagingPage(page);
1128     if (isMainPage) {
1129         ACE_DCHECK(!engineInstance_->GetRunningPage());
1130         engineInstance_->SetRunningPage(page);
1131     }
1132     auto runtime = engineInstance_->GetJsRuntime();
1133     auto delegate = engineInstance_->GetDelegate();
1134     auto vm = const_cast<EcmaVM*>(std::static_pointer_cast<ArkJSRuntime>(runtime)->GetEcmaVm());
1135     // get source map
1136     std::string jsSourceMap;
1137     if (JSNApi::IsBundle(vm)) {
1138         if (delegate->GetAssetContent(url + ".map", jsSourceMap)) {
1139             page->SetPageMap(jsSourceMap);
1140         } else {
1141             LOGW("js source map load failed!");
1142         }
1143     }
1144     // get js bundle content
1145     shared_ptr<JsValue> jsCode = runtime->NewUndefined();
1146     shared_ptr<JsValue> jsAppCode = runtime->NewUndefined();
1147     const char js_ext[] = ".js";
1148     const char bin_ext[] = ".abc";
1149     auto pos = url.rfind(js_ext);
1150     if (pos != std::string::npos && pos == url.length() - (sizeof(js_ext) - 1)) {
1151         std::string urlName = url.substr(0, pos) + bin_ext;
1152         if (isMainPage) {
1153 #if !defined(PREVIEW)
1154             if (LoadJsWithModule(urlName)) {
1155                 return;
1156             }
1157 #endif
1158             if (!ExecuteAbc("commons.abc")) {
1159                 return;
1160             }
1161             if (!ExecuteAbc("vendors.abc")) {
1162                 return;
1163             }
1164             std::string appMap;
1165             if (delegate->GetAssetContent("app.js.map", appMap)) {
1166                 page->SetAppMap(appMap);
1167             } else {
1168                 LOGW("app map load failed!");
1169             }
1170             if (!ExecuteAbc("app.abc")) {
1171                 LOGW("ExecuteJsBin \"app.js\" failed.");
1172             } else {
1173                 CallAppFunc("onCreate");
1174             }
1175         }
1176 #if !defined(PREVIEW)
1177         if (LoadJsWithModule(urlName)) {
1178             return;
1179         }
1180         if (!ExecuteAbc(urlName)) {
1181             return;
1182         }
1183 #else
1184         if (!assetPath_.empty() && !isBundle_) {
1185             auto arkRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1186             arkRuntime->SetBundleName(bundleName_);
1187             arkRuntime->SetAssetPath(assetPath_);
1188             arkRuntime->SetBundle(isBundle_);
1189             arkRuntime->SetModuleName(moduleName_);
1190             std::vector<uint8_t> content;
1191             if (!delegate->GetAssetContent("modules.abc", content)) {
1192                 LOGE("GetAssetContent \"%{public}s\" failed.", urlName.c_str());
1193                 return;
1194             }
1195             if (!arkRuntime->ExecuteModuleBuffer(content.data(), content.size(), urlName)) {
1196                 LOGE("EvaluateJsCode \"%{public}s\" failed.", urlName.c_str());
1197                 return;
1198             }
1199         } else {
1200             ExecuteAbc(urlName);
1201         }
1202 #endif
1203     }
1204 }
1205 
LoadJsWithModule(std::string & urlName,const std::function<void (const std::string &,int32_t)> & errorCallback)1206 bool JsiDeclarativeEngine::LoadJsWithModule(std::string& urlName,
1207     const std::function<void(const std::string&, int32_t)>& errorCallback)
1208 {
1209     auto container = Container::Current();
1210     CHECK_NULL_RETURN(container, false);
1211     if (container->IsModule()) {
1212         const std::string assetPath = ASSET_PATH_PREFIX +
1213             container->GetModuleName() + "/" + FORM_ES_MODULE_PATH;
1214         auto runtime = std::static_pointer_cast<ArkJSRuntime>(engineInstance_->GetJsRuntime());
1215         runtime->SetAssetPath(assetPath);
1216         urlName = container->GetModuleName() + "/ets/" + urlName;
1217         if (!runtime->ExecuteJsBin(urlName, errorCallback)) {
1218             LOGE("ExecuteJsBin %{private}s failed.", urlName.c_str());
1219         }
1220         return true;
1221     }
1222     return false;
1223 }
1224 
1225 // Load the app.js file of the FA model in NG structure.
LoadFaAppSource()1226 bool JsiDeclarativeEngine::LoadFaAppSource()
1227 {
1228     ACE_SCOPED_TRACE("JsiDeclarativeEngine::LoadFaAppSource");
1229     if (!ExecuteAbc("commons.abc")) {
1230         return false;
1231     }
1232     if (!ExecuteAbc("vendors.abc")) {
1233         return false;
1234     }
1235     if (!ExecuteAbc("app.abc")) {
1236         LOGW("ExecuteJsBin \"app.js\" failed.");
1237         return false;
1238     }
1239     CallAppFunc("onCreate");
1240     return true;
1241 }
1242 
1243 // Load the js file of the page in NG structure..
LoadPageSource(const std::string & url,const std::function<void (const std::string &,int32_t)> & errorCallback)1244 bool JsiDeclarativeEngine::LoadPageSource(const std::string& url,
1245     const std::function<void(const std::string&, int32_t)>& errorCallback)
1246 {
1247     ACE_SCOPED_TRACE("JsiDeclarativeEngine::LoadPageSource");
1248     LOGI("JsiDeclarativeEngine LoadJs %{private}s page", url.c_str());
1249     ACE_DCHECK(engineInstance_);
1250     // get js bundle content
1251     const char jsExt[] = ".js";
1252     const char binExt[] = ".abc";
1253     std::optional<std::string> urlName;
1254     auto pos = url.rfind(jsExt);
1255     if (pos != std::string::npos && pos == url.length() - (sizeof(jsExt) - 1)) {
1256         urlName = url.substr(0, pos) + binExt;
1257     }
1258     if (!urlName.has_value()) {
1259         LOGE("fail to find abc file");
1260         return false;
1261     }
1262 
1263 #if !defined(PREVIEW)
1264     if (LoadJsWithModule(urlName.value(), errorCallback)) {
1265         return true;
1266     }
1267 #else
1268     auto runtime = engineInstance_->GetJsRuntime();
1269     auto delegate = engineInstance_->GetDelegate();
1270     if (!assetPath_.empty() && !isBundle_) {
1271         auto arkRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1272         arkRuntime->SetBundleName(bundleName_);
1273         arkRuntime->SetAssetPath(assetPath_);
1274         arkRuntime->SetBundle(isBundle_);
1275         arkRuntime->SetModuleName(moduleName_);
1276         std::vector<uint8_t> content;
1277         if (!delegate->GetAssetContent("modules.abc", content)) {
1278             LOGE("GetAssetContent \"%{public}s\" failed.", urlName.value().c_str());
1279             return false;
1280         }
1281         if (!arkRuntime->ExecuteModuleBuffer(content.data(), content.size(), urlName.value())) {
1282             LOGE("EvaluateJsCode \"%{public}s\" failed.", urlName.value().c_str());
1283             return false;
1284         }
1285         return true;
1286     }
1287 #endif
1288     return ExecuteAbc(urlName.value());
1289 }
1290 
LoadCard(const std::string & url,int64_t cardId)1291 bool JsiDeclarativeEngine::LoadCard(const std::string& url, int64_t cardId)
1292 {
1293     ACE_SCOPED_TRACE("JsiDeclarativeEngine::LoadCard");
1294     return ExecuteCardAbc(url, cardId);
1295 }
1296 
1297 #if defined(PREVIEW)
ReplaceJSContent(const std::string & url,const std::string componentName)1298 void JsiDeclarativeEngine::ReplaceJSContent(const std::string& url, const std::string componentName)
1299 {
1300     ACE_DCHECK(engineInstance_);
1301     if (engineInstance_ == nullptr) {
1302         LOGE("engineInstance is nullptr");
1303         return;
1304     }
1305     auto runtime = engineInstance_->GetJsRuntime();
1306     std::static_pointer_cast<ArkJSRuntime>(runtime)->SetPreviewFlag(true);
1307     std::static_pointer_cast<ArkJSRuntime>(runtime)->SetRequiredComponent(componentName);
1308     engineInstance_->GetDelegate()->Replace(url, "");
1309 }
1310 
GetNewComponentWithJsCode(const std::string & jsCode,const std::string & viewID)1311 RefPtr<Component> JsiDeclarativeEngine::GetNewComponentWithJsCode(const std::string& jsCode, const std::string& viewID)
1312 {
1313     std::string dest;
1314     if (!Base64Util::Decode(jsCode, dest)) {
1315         return nullptr;
1316     }
1317 
1318     ViewStackProcessor::GetInstance()->ClearStack();
1319     ViewStackProcessor::GetInstance()->PushKey(viewID);
1320     bool result = engineInstance_->InitAceModule((uint8_t*)dest.data(), dest.size());
1321     ViewStackProcessor::GetInstance()->PopKey();
1322     if (!result) {
1323         return nullptr;
1324     }
1325     auto component = ViewStackProcessor::GetInstance()->GetNewComponent();
1326     return component;
1327 }
1328 
ExecuteJsForFastPreview(const std::string & jsCode,const std::string & viewID)1329 bool JsiDeclarativeEngine::ExecuteJsForFastPreview(const std::string& jsCode, const std::string& viewID)
1330 {
1331     std::string dest;
1332     if (!Base64Util::Decode(jsCode, dest)) {
1333         return false;
1334     }
1335     NG::ViewStackProcessor::GetInstance()->ClearStack();
1336     NG::ViewStackProcessor::GetInstance()->PushKey(viewID);
1337     bool result = engineInstance_->InitAceModule((uint8_t*)dest.data(), dest.size());
1338     NG::ViewStackProcessor::GetInstance()->PopKey();
1339     return result;
1340 }
1341 
1342 #endif
1343 
UpdateRunningPage(const RefPtr<JsAcePage> & page)1344 void JsiDeclarativeEngine::UpdateRunningPage(const RefPtr<JsAcePage>& page)
1345 {
1346     LOGD("JsiDeclarativeEngine UpdateRunningPage");
1347     ACE_DCHECK(engineInstance_);
1348     engineInstance_->SetRunningPage(page);
1349 }
1350 
UpdateStagingPage(const RefPtr<JsAcePage> & page)1351 void JsiDeclarativeEngine::UpdateStagingPage(const RefPtr<JsAcePage>& page)
1352 {
1353     LOGI("JsiDeclarativeEngine UpdateStagingPage %{public}d", page->GetPageId());
1354     ACE_DCHECK(engineInstance_);
1355     engineInstance_->SetStagingPage(page);
1356 }
1357 
ResetStagingPage()1358 void JsiDeclarativeEngine::ResetStagingPage()
1359 {
1360     LOGD("JsiDeclarativeEngine ResetStagingPage");
1361     ACE_DCHECK(engineInstance_);
1362     auto runningPage = engineInstance_->GetRunningPage();
1363     engineInstance_->ResetStagingPage(runningPage);
1364 }
1365 
SetJsMessageDispatcher(const RefPtr<JsMessageDispatcher> & dispatcher)1366 void JsiDeclarativeEngine::SetJsMessageDispatcher(const RefPtr<JsMessageDispatcher>& dispatcher)
1367 {
1368     LOGD("JsiDeclarativeEngine SetJsMessageDispatcher");
1369     ACE_DCHECK(engineInstance_);
1370     engineInstance_->SetJsMessageDispatcher(dispatcher);
1371 }
1372 
FireAsyncEvent(const std::string & eventId,const std::string & param)1373 void JsiDeclarativeEngine::FireAsyncEvent(const std::string& eventId, const std::string& param)
1374 {
1375     LOGD("JsiDeclarativeEngine FireAsyncEvent");
1376     std::string callBuf = std::string("[{\"args\": [\"")
1377                               .append(eventId)
1378                               .append("\",")
1379                               .append(param)
1380                               .append("], \"method\":\"fireEvent\"}]");
1381     LOGD("FireASyncEvent string: %{private}s", callBuf.c_str());
1382 
1383     ACE_DCHECK(engineInstance_);
1384     if (!engineInstance_->FireJsEvent(callBuf.c_str())) {
1385         LOGE("Js Engine FireSyncEvent FAILED!");
1386     }
1387 }
1388 
FireSyncEvent(const std::string & eventId,const std::string & param)1389 void JsiDeclarativeEngine::FireSyncEvent(const std::string& eventId, const std::string& param)
1390 {
1391     LOGD("JsiDeclarativeEngine FireSyncEvent");
1392     std::string callBuf = std::string("[{\"args\": [\"")
1393                               .append(eventId)
1394                               .append("\",")
1395                               .append(param)
1396                               .append("], \"method\":\"fireEventSync\"}]");
1397     LOGD("FireSyncEvent string: %{private}s", callBuf.c_str());
1398 
1399     ACE_DCHECK(engineInstance_);
1400     if (!engineInstance_->FireJsEvent(callBuf.c_str())) {
1401         LOGE("Js Engine FireSyncEvent FAILED!");
1402     }
1403 }
1404 
InitXComponent(const std::string & componentId)1405 void JsiDeclarativeEngine::InitXComponent(const std::string& componentId)
1406 {
1407     ACE_DCHECK(engineInstance_);
1408     std::tie(nativeXComponentImpl_, nativeXComponent_) =
1409         XComponentClient::GetInstance().GetNativeXComponentFromXcomponentsMap(componentId);
1410 }
1411 
FireExternalEvent(const std::string & componentId,const uint32_t nodeId,const bool isDestroy)1412 void JsiDeclarativeEngine::FireExternalEvent(
1413     const std::string& componentId, const uint32_t nodeId, const bool isDestroy)
1414 {
1415     CHECK_RUN_ON(JS);
1416     if (Container::IsCurrentUseNewPipeline()) {
1417         ACE_DCHECK(engineInstance_);
1418         auto xcFrameNode = NG::FrameNode::GetFrameNode(V2::XCOMPONENT_ETS_TAG, static_cast<int32_t>(nodeId));
1419         if (!xcFrameNode) {
1420             LOGE("FireExternalEvent xcFrameNode is null.");
1421             return;
1422         }
1423         auto xcPattern = DynamicCast<NG::XComponentPattern>(xcFrameNode->GetPattern());
1424         CHECK_NULL_VOID(xcPattern);
1425 
1426         void* nativeWindow = nullptr;
1427 
1428         nativeWindow = xcPattern->GetNativeWindow();
1429 
1430         std::weak_ptr<OH_NativeXComponent> weakNativeXComponent;
1431         RefPtr<OHOS::Ace::NativeXComponentImpl> nativeXComponentImpl = nullptr;
1432 
1433         std::tie(nativeXComponentImpl, weakNativeXComponent) = xcPattern->GetNativeXComponent();
1434         auto nativeXComponent = weakNativeXComponent.lock();
1435         CHECK_NULL_VOID(nativeXComponent);
1436         CHECK_NULL_VOID(nativeXComponentImpl);
1437 
1438         if (!nativeWindow) {
1439             LOGE("FireExternalEvent nativeWindow invalid");
1440             return;
1441         }
1442         nativeXComponentImpl->SetSurface(nativeWindow);
1443         nativeXComponentImpl->SetXComponentId(componentId);
1444 
1445         auto* arkNativeEngine = static_cast<ArkNativeEngine*>(nativeEngine_);
1446         if (arkNativeEngine == nullptr) {
1447             LOGE("FireExternalEvent arkNativeEngine is nullptr");
1448             return;
1449         }
1450 
1451         std::string arguments;
1452         auto soPath = xcPattern->GetSoPath().value_or("");
1453         auto runtime = engineInstance_->GetJsRuntime();
1454         shared_ptr<ArkJSRuntime> pandaRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1455         LocalScope scope(pandaRuntime->GetEcmaVm());
1456         auto objXComp = arkNativeEngine->LoadModuleByName(xcPattern->GetLibraryName(), true, arguments,
1457             OH_NATIVE_XCOMPONENT_OBJ, reinterpret_cast<void*>(nativeXComponent.get()), soPath);
1458         if (objXComp.IsEmpty() || pandaRuntime->HasPendingException()) {
1459             LOGE("LoadModuleByName failed.");
1460             return;
1461         }
1462 
1463         renderContext_ = runtime->NewObject();
1464         auto renderContext = std::static_pointer_cast<ArkJSValue>(renderContext_);
1465         renderContext->SetValue(pandaRuntime, objXComp);
1466 
1467         auto objContext = JsiObject(objXComp);
1468         JSRef<JSObject> obj = JSRef<JSObject>::Make(objContext);
1469         OHOS::Ace::Framework::XComponentClient::GetInstance().AddJsValToJsValMap(componentId, obj);
1470 
1471         auto task = [weak = WeakClaim(this), weakPattern = AceType::WeakClaim(AceType::RawPtr(xcPattern))]() {
1472             auto pattern = weakPattern.Upgrade();
1473             if (!pattern) {
1474                 return;
1475             }
1476             auto bridge = weak.Upgrade();
1477             if (bridge) {
1478 #ifdef XCOMPONENT_SUPPORTED
1479                 pattern->NativeXComponentInit();
1480 #endif
1481             }
1482         };
1483 
1484         auto delegate = engineInstance_->GetDelegate();
1485         if (!delegate) {
1486             LOGE("Delegate is null");
1487             return;
1488         }
1489         delegate->PostSyncTaskToPage(task);
1490         return;
1491     }
1492     if (isDestroy) {
1493         XComponentComponentClient::GetInstance().DeleteFromXcomponentsMapById(componentId);
1494         XComponentClient::GetInstance().DeleteControllerFromJSXComponentControllersMap(componentId);
1495         XComponentClient::GetInstance().DeleteFromNativeXcomponentsMapById(componentId);
1496         XComponentClient::GetInstance().DeleteFromJsValMapById(componentId);
1497         return;
1498     }
1499     InitXComponent(componentId);
1500     RefPtr<XComponentComponent> xcomponent =
1501         XComponentComponentClient::GetInstance().GetXComponentFromXcomponentsMap(componentId);
1502     if (!xcomponent) {
1503         LOGE("FireExternalEvent xcomponent is null.");
1504         return;
1505     }
1506 
1507     void* nativeWindow = nullptr;
1508 #ifdef OHOS_STANDARD_SYSTEM
1509     nativeWindow = const_cast<void*>(xcomponent->GetNativeWindow());
1510 #else
1511     auto container = Container::Current();
1512     if (!container) {
1513         LOGE("FireExternalEvent Current container null");
1514         return;
1515     }
1516     auto nativeView = static_cast<AceView*>(container->GetView());
1517     if (!nativeView) {
1518         LOGE("FireExternalEvent nativeView null");
1519         return;
1520     }
1521     auto textureId = static_cast<int64_t>(xcomponent->GetTextureId());
1522     nativeWindow = const_cast<void*>(nativeView->GetNativeWindowById(textureId));
1523 #endif
1524 
1525     if (!nativeWindow) {
1526         LOGE("FireExternalEvent nativeWindow invalid");
1527         return;
1528     }
1529     nativeXComponentImpl_->SetSurface(nativeWindow);
1530     nativeXComponentImpl_->SetXComponentId(xcomponent->GetId());
1531 
1532     auto arkNativeEngine = static_cast<ArkNativeEngine*>(nativeEngine_);
1533     if (arkNativeEngine == nullptr) {
1534         LOGE("FireExternalEvent arkNativeEngine is nullptr");
1535         return;
1536     }
1537 
1538     std::string arguments;
1539     auto soPath = xcomponent->GetSoPath().value_or("");
1540     auto runtime = engineInstance_->GetJsRuntime();
1541     shared_ptr<ArkJSRuntime> pandaRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1542     LocalScope scope(pandaRuntime->GetEcmaVm());
1543     auto objXComp = arkNativeEngine->LoadModuleByName(xcomponent->GetLibraryName(), true, arguments,
1544         OH_NATIVE_XCOMPONENT_OBJ, reinterpret_cast<void*>(nativeXComponent_), soPath);
1545     if (objXComp.IsEmpty() || pandaRuntime->HasPendingException()) {
1546         LOGE("LoadModuleByName failed.");
1547         return;
1548     }
1549 
1550     renderContext_ = runtime->NewObject();
1551     auto renderContext = std::static_pointer_cast<ArkJSValue>(renderContext_);
1552     renderContext->SetValue(pandaRuntime, objXComp);
1553 
1554     auto objContext = JsiObject(objXComp);
1555     JSRef<JSObject> obj = JSRef<JSObject>::Make(objContext);
1556     XComponentClient::GetInstance().AddJsValToJsValMap(componentId, obj);
1557 
1558     auto task = [weak = WeakClaim(this), xcomponent]() {
1559         auto pool = xcomponent->GetTaskPool();
1560         if (!pool) {
1561             return;
1562         }
1563         auto bridge = weak.Upgrade();
1564         if (bridge) {
1565 #ifdef XCOMPONENT_SUPPORTED
1566             pool->NativeXComponentInit(
1567                 bridge->nativeXComponent_, AceType::WeakClaim(AceType::RawPtr(bridge->nativeXComponentImpl_)));
1568 #endif
1569         }
1570     };
1571 
1572     auto delegate = engineInstance_->GetDelegate();
1573     if (!delegate) {
1574         LOGE("Delegate is null");
1575         return;
1576     }
1577     delegate->PostSyncTaskToPage(task);
1578 }
1579 
TimerCallback(const std::string & callbackId,const std::string & delay,bool isInterval)1580 void JsiDeclarativeEngine::TimerCallback(const std::string& callbackId, const std::string& delay, bool isInterval)
1581 {
1582     TimerCallJs(callbackId);
1583     auto runtime = JsiDeclarativeEngineInstance::GetCurrentRuntime();
1584     if (!runtime) {
1585         LOGE("get runtime failed");
1586         return;
1587     }
1588     auto instance = static_cast<JsiDeclarativeEngineInstance*>(runtime->GetEmbedderData());
1589     if (instance == nullptr) {
1590         LOGE("get jsi engine instance failed");
1591         return;
1592     }
1593     auto delegate = instance->GetDelegate();
1594     if (!delegate) {
1595         LOGE("get frontend delegate failed");
1596         return;
1597     }
1598 
1599     if (isInterval) {
1600         delegate->WaitTimer(callbackId, delay, isInterval, false);
1601     } else {
1602         JsiTimerModule::GetInstance()->RemoveCallBack(std::stoi(callbackId));
1603         delegate->ClearTimer(callbackId);
1604     }
1605 }
1606 
TimerCallJs(const std::string & callbackId) const1607 void JsiDeclarativeEngine::TimerCallJs(const std::string& callbackId) const
1608 {
1609     shared_ptr<JsValue> func;
1610     std::vector<shared_ptr<JsValue>> params;
1611     if (!JsiTimerModule::GetInstance()->GetCallBack(std::stoi(callbackId), func, params)) {
1612         LOGE("get callback failed");
1613         return;
1614     }
1615     auto runtime = JsiDeclarativeEngineInstance::GetCurrentRuntime();
1616     if (func) {
1617         func->Call(runtime, runtime->GetGlobal(), params, params.size());
1618     }
1619 }
1620 
DestroyPageInstance(int32_t pageId)1621 void JsiDeclarativeEngine::DestroyPageInstance(int32_t pageId)
1622 {
1623     LOGI("JsiDeclarativeEngine DestroyPageInstance %{public}d", pageId);
1624     ACE_DCHECK(engineInstance_);
1625 
1626     engineInstance_->DestroyRootViewHandle(pageId);
1627 }
1628 
DestroyApplication(const std::string & packageName)1629 void JsiDeclarativeEngine::DestroyApplication(const std::string& packageName)
1630 {
1631     LOGI("JsiDeclarativeEngine DestroyApplication, packageName %{public}s", packageName.c_str());
1632     if (engineInstance_) {
1633         shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1634         CallAppFunc("onDestroy");
1635     }
1636 }
1637 
UpdateApplicationState(const std::string & packageName,Frontend::State state)1638 void JsiDeclarativeEngine::UpdateApplicationState(const std::string& packageName, Frontend::State state)
1639 {
1640     LOGI("JsiDeclarativeEngine UpdateApplicationState, packageName %{public}s, state: %{public}d", packageName.c_str(),
1641         static_cast<int32_t>(state));
1642     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1643     if (!runtime) {
1644         LOGE("update app state failed, runtime is null.");
1645         return;
1646     }
1647     switch (state) {
1648         case Frontend::State::ON_SHOW:
1649             CallAppFunc("onShow");
1650             break;
1651         case Frontend::State::ON_HIDE:
1652             CallAppFunc("onHide");
1653             break;
1654         case Frontend::State::ON_ACTIVE:
1655             CallAppFunc("onActive");
1656             break;
1657         case Frontend::State::ON_INACTIVE:
1658             CallAppFunc("onInactive");
1659             break;
1660         case Frontend::State::ON_DESTROY:
1661             CallAppFunc("onDestroy");
1662             break;
1663         default:
1664             LOGW("unsupported state: %{public}d", state);
1665             return;
1666     }
1667 }
1668 
OnWindowDisplayModeChanged(bool isShownInMultiWindow,const std::string & data)1669 void JsiDeclarativeEngine::OnWindowDisplayModeChanged(bool isShownInMultiWindow, const std::string& data)
1670 {
1671     LOGI("JsiDeclarativeEngine OnWindowDisplayModeChanged");
1672     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1673     std::vector<shared_ptr<JsValue>> argv = { runtime->NewBoolean(isShownInMultiWindow), runtime->NewString(data) };
1674     CallAppFunc("onWindowDisplayModeChanged", argv);
1675 }
1676 
CallAppFunc(const std::string & appFuncName)1677 bool JsiDeclarativeEngine::CallAppFunc(const std::string& appFuncName)
1678 {
1679     std::vector<shared_ptr<JsValue>> argv = {};
1680     return CallAppFunc(appFuncName, argv);
1681 }
1682 
CallAppFunc(const std::string & appFuncName,std::vector<shared_ptr<JsValue>> & argv)1683 bool JsiDeclarativeEngine::CallAppFunc(const std::string& appFuncName, std::vector<shared_ptr<JsValue>>& argv)
1684 {
1685     LOGD("JsiDeclarativeEngine CallAppFunc");
1686     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1687     ACE_DCHECK(runtime);
1688     shared_ptr<JsValue> global = runtime->GetGlobal();
1689     shared_ptr<JsValue> exportsObject = global->GetProperty(runtime, "exports");
1690     if (!exportsObject->IsObject(runtime)) {
1691         LOGE("property \"exports\" is not a object");
1692         return false;
1693     }
1694     shared_ptr<JsValue> defaultObject = exportsObject->GetProperty(runtime, "default");
1695     if (!defaultObject->IsObject(runtime)) {
1696         LOGE("property \"default\" is not a object");
1697         return false;
1698     }
1699     shared_ptr<JsValue> func = defaultObject->GetProperty(runtime, appFuncName);
1700     if (!func || !func->IsFunction(runtime)) {
1701         return false;
1702     }
1703     shared_ptr<JsValue> result;
1704     result = func->Call(runtime, defaultObject, argv, argv.size());
1705     return (result->ToString(runtime) == "true");
1706 }
1707 
MediaQueryCallback(const std::string & callbackId,const std::string & args)1708 void JsiDeclarativeEngine::MediaQueryCallback(const std::string& callbackId, const std::string& args)
1709 {
1710     JsEngine::MediaQueryCallback(callbackId, args);
1711 }
1712 
RequestAnimationCallback(const std::string & callbackId,uint64_t timeStamp)1713 void JsiDeclarativeEngine::RequestAnimationCallback(const std::string& callbackId, uint64_t timeStamp) {}
1714 
JsCallback(const std::string & callbackId,const std::string & args)1715 void JsiDeclarativeEngine::JsCallback(const std::string& callbackId, const std::string& args) {}
1716 
RunGarbageCollection()1717 void JsiDeclarativeEngine::RunGarbageCollection()
1718 {
1719     if (engineInstance_ && engineInstance_->GetJsRuntime()) {
1720         engineInstance_->GetJsRuntime()->RunGC();
1721     }
1722 }
1723 
RunFullGarbageCollection()1724 void JsiDeclarativeEngine::RunFullGarbageCollection()
1725 {
1726     if (engineInstance_ && engineInstance_->GetJsRuntime()) {
1727         engineInstance_->GetJsRuntime()->RunFullGC();
1728     }
1729 }
1730 
DumpHeapSnapshot(bool isPrivate)1731 void JsiDeclarativeEngine::DumpHeapSnapshot(bool isPrivate)
1732 {
1733     if (engineInstance_ && engineInstance_->GetJsRuntime()) {
1734         engineInstance_->GetJsRuntime()->DumpHeapSnapshot(isPrivate);
1735     }
1736 }
1737 
GetStacktraceMessage()1738 std::string JsiDeclarativeEngine::GetStacktraceMessage()
1739 {
1740     auto arkNativeEngine = static_cast<ArkNativeEngine*>(nativeEngine_);
1741     if (!arkNativeEngine) {
1742         LOGE("GetStacktraceMessage arkNativeEngine is nullptr");
1743         return "";
1744     }
1745     std::string stack;
1746     arkNativeEngine->SuspendVM();
1747     bool getStackSuccess = arkNativeEngine->BuildJsStackTrace(stack);
1748     arkNativeEngine->ResumeVM();
1749     if (!getStackSuccess) {
1750         LOGE("GetStacktraceMessage arkNativeEngine get stack failed");
1751         return "JS stacktrace is empty";
1752     }
1753 
1754     auto runningPage = engineInstance_ ? engineInstance_->GetRunningPage() : nullptr;
1755     return JsiBaseUtils::TransSourceStack(runningPage, stack);
1756 }
1757 
SetLocalStorage(int32_t instanceId,NativeReference * nativeValue)1758 void JsiDeclarativeEngine::SetLocalStorage(int32_t instanceId, NativeReference* nativeValue)
1759 {
1760     LOGI("SetLocalStorage instanceId:%{public}d", instanceId);
1761 #ifdef USE_ARK_ENGINE
1762     auto jsValue = JsConverter::ConvertNativeValueToJsVal(*nativeValue);
1763     if (jsValue->IsObject()) {
1764         auto storage = JSRef<JSObject>::Cast(jsValue);
1765         JSLocalStorage::AddStorage(instanceId, storage);
1766     } else {
1767         LOGI("SetLocalStorage instanceId:%{public}d invalid storage", instanceId);
1768         delete nativeValue;
1769         nativeValue = nullptr;
1770     }
1771 #endif
1772 }
1773 
SetContext(int32_t instanceId,NativeReference * nativeValue)1774 void JsiDeclarativeEngine::SetContext(int32_t instanceId, NativeReference* nativeValue)
1775 {
1776     LOGI("SetContext instanceId:%{public}d", instanceId);
1777 #ifdef USE_ARK_ENGINE
1778     NativeScopeManager* scopeManager = nativeEngine_->GetScopeManager();
1779     auto nativeScope = scopeManager->Open();
1780     NativeValue* value = *nativeValue;
1781     Global<JSValueRef> globalRef = *value;
1782     auto arkRuntime = std::static_pointer_cast<ArkJSRuntime>(JsiDeclarativeEngineInstance::GetCurrentRuntime());
1783     if (!arkRuntime || !arkRuntime->GetEcmaVm()) {
1784         LOGE("SetContext null ark runtime");
1785         return;
1786     }
1787     JAVASCRIPT_EXECUTION_SCOPE_STATIC;
1788     auto localRef = globalRef.ToLocal(arkRuntime->GetEcmaVm());
1789     std::shared_ptr<JsValue> jsValue = std::make_shared<ArkJSValue>(arkRuntime, localRef);
1790     if (jsValue->IsObject(arkRuntime)) {
1791         JsiContextModule::AddContext(instanceId_, jsValue);
1792     } else {
1793         LOGI("SetContext instanceId:%{public}d invalid context", instanceId);
1794     }
1795     scopeManager->Close(nativeScope);
1796 #endif
1797 }
1798 
GetGroupJsBridge()1799 RefPtr<GroupJsBridge> JsiDeclarativeEngine::GetGroupJsBridge()
1800 {
1801     return AceType::MakeRefPtr<JsiDeclarativeGroupJsBridge>();
1802 }
1803 
OnActive()1804 void JsiDeclarativeEngine::OnActive()
1805 {
1806     LOGI("JsiDeclarativeEngine onActive called.");
1807     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1808     if (!runtime) {
1809         LOGE("onActive failed, runtime is null.");
1810         return;
1811     }
1812     CallAppFunc("onActive");
1813 }
1814 
OnInactive()1815 void JsiDeclarativeEngine::OnInactive()
1816 {
1817     LOGI("JsiDeclarativeEngine OnInactive called.");
1818     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1819     if (!runtime) {
1820         LOGE("OnInactive failed, runtime is null.");
1821         return;
1822     }
1823     CallAppFunc("onInactive");
1824 }
1825 
OnNewWant(const std::string & data)1826 void JsiDeclarativeEngine::OnNewWant(const std::string& data)
1827 {
1828     LOGI("JsiDeclarativeEngine OnNewWant called.");
1829     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1830     if (!runtime) {
1831         LOGE("OnNewWant failed, runtime is null.");
1832         return;
1833     }
1834 
1835     shared_ptr<JsValue> object = runtime->ParseJson(data);
1836     std::vector<shared_ptr<JsValue>> argv = { object };
1837     CallAppFunc("onNewWant", argv);
1838 }
1839 
OnStartContinuation()1840 bool JsiDeclarativeEngine::OnStartContinuation()
1841 {
1842     LOGI("JsiDeclarativeEngine OnStartContinuation");
1843     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1844     if (!runtime) {
1845         LOGE("OnStartContinuation failed, runtime is null.");
1846         return false;
1847     }
1848 
1849     return CallAppFunc("onStartContinuation");
1850 }
1851 
OnCompleteContinuation(int32_t code)1852 void JsiDeclarativeEngine::OnCompleteContinuation(int32_t code)
1853 {
1854     LOGI("JsiDeclarativeEngine OnCompleteContinuation");
1855     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1856     if (!runtime) {
1857         LOGE("OnCompleteContinuation failed, runtime is null.");
1858         return;
1859     }
1860 
1861     std::vector<shared_ptr<JsValue>> argv = { runtime->NewNumber(code) };
1862     CallAppFunc("onCompleteContinuation", argv);
1863 }
1864 
ClearCache()1865 void JsiDeclarativeEngine::ClearCache()
1866 {
1867     JSNApi::CleanJSVMCache();
1868 }
1869 
OnRemoteTerminated()1870 void JsiDeclarativeEngine::OnRemoteTerminated()
1871 {
1872     LOGI("JsiDeclarativeEngine OnRemoteTerminated");
1873     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1874     if (!runtime) {
1875         LOGE("OnRemoteTerminated failed, runtime is null.");
1876         return;
1877     }
1878 
1879     CallAppFunc("onRemoteTerminated");
1880 }
1881 
OnSaveData(std::string & data)1882 void JsiDeclarativeEngine::OnSaveData(std::string& data)
1883 {
1884     LOGI("JsiDeclarativeEngine OnSaveData");
1885     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1886     if (!runtime) {
1887         LOGE("OnSaveData failed, runtime is null.");
1888         return;
1889     }
1890 
1891     shared_ptr<JsValue> object = runtime->NewObject();
1892     std::vector<shared_ptr<JsValue>> argv = { object };
1893     if (CallAppFunc("onSaveData", argv)) {
1894         data = object->GetJsonString(runtime);
1895     }
1896 }
1897 
SetErrorEventHandler(std::function<void (const std::string &,const std::string &)> && errorCallback)1898 void JsiDeclarativeEngine::SetErrorEventHandler(
1899     std::function<void(const std::string&, const std::string&)>&& errorCallback)
1900 {
1901     LOGI("JsiDeclarativeEngine SetErrorEventHandler");
1902     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1903     if (!runtime) {
1904         LOGE("SetErrorEventHandler failed, runtime is null.");
1905         return;
1906     }
1907 
1908     runtime->SetErrorEventHandler(std::move(errorCallback));
1909 }
1910 
OnRestoreData(const std::string & data)1911 bool JsiDeclarativeEngine::OnRestoreData(const std::string& data)
1912 {
1913     LOGI("JsiDeclarativeEngine OnRestoreData");
1914     shared_ptr<JsRuntime> runtime = engineInstance_->GetJsRuntime();
1915     if (!runtime) {
1916         LOGE("OnRestoreData failed, runtime is null.");
1917         return false;
1918     }
1919     shared_ptr<JsValue> result;
1920     shared_ptr<JsValue> jsonObj = runtime->ParseJson(data);
1921     if (jsonObj->IsUndefined(runtime) || jsonObj->IsException(runtime)) {
1922         LOGE("JsiDeclarativeEngine: Parse json for restore data failed.");
1923         return false;
1924     }
1925     std::vector<shared_ptr<JsValue>> argv = { jsonObj };
1926     return CallAppFunc("onRestoreData", argv);
1927 }
1928 
1929 // ArkTsCard start
OHOS_ACE_PreloadAceModuleCard(void * runtime)1930 extern "C" ACE_FORCE_EXPORT void OHOS_ACE_PreloadAceModuleCard(void* runtime)
1931 {
1932     JsiDeclarativeEngineInstance::PreloadAceModuleCard(runtime);
1933 }
1934 
PreloadAceModuleCard(void * runtime)1935 void JsiDeclarativeEngineInstance::PreloadAceModuleCard(void* runtime)
1936 {
1937     isUnique_ = true;
1938     if (isModulePreloaded_ && !IsPlugin() && !isUnique_) {
1939         LOGE("PreloadAceModule already preloaded");
1940         return;
1941     }
1942     auto sharedRuntime = reinterpret_cast<NativeEngine*>(runtime);
1943 
1944     if (!sharedRuntime) {
1945         LOGE("PreloadAceModule null runtime");
1946         return;
1947     }
1948     std::shared_ptr<ArkJSRuntime> arkRuntime = std::make_shared<ArkJSRuntime>();
1949     localRuntime_ = arkRuntime;
1950     auto nativeArkEngine = static_cast<ArkNativeEngine*>(sharedRuntime);
1951     EcmaVM* vm = const_cast<EcmaVM*>(nativeArkEngine->GetEcmaVm());
1952     if (vm == nullptr) {
1953         LOGE("PreloadAceModule NativeDeclarativeEngine Initialize, vm is null");
1954         return;
1955     }
1956     if (!arkRuntime->InitializeFromExistVM(vm)) {
1957         LOGE("PreloadAceModule Ark Engine initialize runtime failed");
1958         return;
1959     }
1960     LocalScope scope(vm);
1961     globalRuntime_ = arkRuntime;
1962 
1963     // preload js views
1964     JsRegisterFormViews(JSNApi::GetGlobalObject(vm));
1965 
1966     // preload aceConsole
1967     shared_ptr<JsValue> global = arkRuntime->GetGlobal();
1968     shared_ptr<JsValue> aceConsoleObj = arkRuntime->NewObject();
1969     aceConsoleObj->SetProperty(arkRuntime, "log", arkRuntime->NewFunction(JsiBaseUtils::JsInfoLogPrint));
1970     aceConsoleObj->SetProperty(arkRuntime, "debug", arkRuntime->NewFunction(JsiBaseUtils::JsDebugLogPrint));
1971     aceConsoleObj->SetProperty(arkRuntime, "info", arkRuntime->NewFunction(JsiBaseUtils::JsInfoLogPrint));
1972     aceConsoleObj->SetProperty(arkRuntime, "warn", arkRuntime->NewFunction(JsiBaseUtils::JsWarnLogPrint));
1973     aceConsoleObj->SetProperty(arkRuntime, "error", arkRuntime->NewFunction(JsiBaseUtils::JsErrorLogPrint));
1974     global->SetProperty(arkRuntime, "aceConsole", aceConsoleObj);
1975 
1976     // preload aceTrace
1977     shared_ptr<JsValue> aceTraceObj = arkRuntime->NewObject();
1978     aceTraceObj->SetProperty(arkRuntime, "begin", arkRuntime->NewFunction(JsiBaseUtils::JsTraceBegin));
1979     aceTraceObj->SetProperty(arkRuntime, "end", arkRuntime->NewFunction(JsiBaseUtils::JsTraceEnd));
1980     global->SetProperty(arkRuntime, "aceTrace", aceTraceObj);
1981 
1982     // preload getContext
1983     JsiContextModule::GetInstance()->InitContextModule(arkRuntime, global);
1984 
1985     // preload exports and requireNative
1986     shared_ptr<JsValue> exportsUtilObj = arkRuntime->NewObject();
1987     global->SetProperty(arkRuntime, "exports", exportsUtilObj);
1988     global->SetProperty(arkRuntime, "requireNativeModule", arkRuntime->NewFunction(RequireNativeModule));
1989 
1990     // preload js enums
1991     bool jsEnumStyleResult = arkRuntime->EvaluateJsCode(
1992         (uint8_t*)_binary_jsEnumStyle_abc_start, _binary_jsEnumStyle_abc_end - _binary_jsEnumStyle_abc_start);
1993     if (!jsEnumStyleResult) {
1994         LOGE("EvaluateJsCode jsEnumStyle failed");
1995         globalRuntime_ = nullptr;
1996         return;
1997     }
1998 
1999     // preload state management
2000     uint8_t* codeStart;
2001     int32_t codeLength;
2002     codeStart = (uint8_t*)_binary_stateMgmt_abc_start;
2003     codeLength = _binary_stateMgmt_abc_end - _binary_stateMgmt_abc_start;
2004     bool evalResult = arkRuntime->EvaluateJsCode(codeStart, codeLength);
2005     if (!evalResult) {
2006         LOGE("PreloadAceModuleCard EvaluateJsCode stateMgmt failed");
2007     }
2008     isModulePreloaded_ = evalResult;
2009     globalRuntime_ = nullptr;
2010     cardRuntime_ = runtime;
2011     JSNApi::TriggerGC(vm, JSNApi::TRIGGER_GC_TYPE::FULL_GC);
2012 }
2013 // ArkTsCard end
2014 } // namespace OHOS::Ace::Framework
2015