• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 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 "adapter/ohos/entrance/pa_engine/engine/jsi/jsi_pa_engine.h"
17 
18 #include "js_backend_timer_module.h"
19 #include "js_environment.h"
20 #include "napi_common_ability.h"
21 
22 #include "frameworks/bridge/js_frontend/engine/jsi/ark_js_value.h"
23 #include "frameworks/bridge/js_frontend/engine/jsi/jsi_base_utils.h"
24 
25 extern const char _binary_paMgmt_abc_start[];
26 extern const char _binary_paMgmt_abc_end[];
27 
28 namespace OHOS::Ace {
29 namespace {
30 #ifdef APP_USE_ARM
31 const std::string ARK_DEBUGGER_LIB_PATH = "libark_inspector.z.so";
32 #else
33 const std::string ARK_DEBUGGER_LIB_PATH = "libark_inspector.z.so";
34 #endif
35 const char TASK_RUNNER[] = "PaEngineRunner";
36 
UnwrapRawImageDataMap(napi_env env,napi_value argv,std::map<std::string,int> & rawImageDataMap)37 bool UnwrapRawImageDataMap(napi_env env, napi_value argv, std::map<std::string, int>& rawImageDataMap)
38 {
39     if (!AppExecFwk::IsTypeForNapiValue(env, argv, napi_object)) {
40         LOGW("%{public}s failed, param is not napi_object.", __func__);
41         return false;
42     }
43 
44     napi_valuetype jsValueType = napi_undefined;
45     napi_value jsProNameList = nullptr;
46     uint32_t jsProCount = 0;
47 
48     NAPI_CALL_BASE(env, napi_get_property_names(env, argv, &jsProNameList), false);
49     NAPI_CALL_BASE(env, napi_get_array_length(env, jsProNameList, &jsProCount), false);
50     LOGI("%{public}s called. Property size=%{public}d.", __func__, jsProCount);
51 
52     napi_value jsProName = nullptr;
53     napi_value jsProValue = nullptr;
54     for (uint32_t index = 0; index < jsProCount; index++) {
55         NAPI_CALL_BASE(env, napi_get_element(env, jsProNameList, index, &jsProName), false);
56         std::string strProName = AppExecFwk::UnwrapStringFromJS(env, jsProName);
57         NAPI_CALL_BASE(env, napi_get_named_property(env, argv, strProName.c_str(), &jsProValue), false);
58         NAPI_CALL_BASE(env, napi_typeof(env, jsProValue, &jsValueType), false);
59         int natValue = AppExecFwk::UnwrapInt32FromJS(env, jsProValue);
60         rawImageDataMap.emplace(strProName, natValue);
61     }
62     return true;
63 }
64 
65 // native implementation for js function: Particle.onCreateFinish()
JsOnCreateFinish(const shared_ptr<JsRuntime> & runtime,const shared_ptr<JsValue> & thisObj,const std::vector<shared_ptr<JsValue>> & argv,int32_t argc)66 shared_ptr<JsValue> JsOnCreateFinish(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj,
67     const std::vector<shared_ptr<JsValue>>& argv, int32_t argc)
68 {
69     return runtime->NewUndefined();
70 }
71 
72 // native implementation for js function: Particle.JsHandleCallback()
JsHandleCallback(const shared_ptr<JsRuntime> & runtime,const shared_ptr<JsValue> & thisObj,const std::vector<shared_ptr<JsValue>> & argv,int32_t argc)73 shared_ptr<JsValue> JsHandleCallback(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj,
74     const std::vector<shared_ptr<JsValue>>& argv, int32_t argc)
75 {
76     LOGI("JsHandleCallback");
77     return runtime->NewUndefined();
78 }
79 
80 // native implementation for js function: Particle.JsRunLoopOnce()
JsRunLoopOnce(const shared_ptr<JsRuntime> & runtime,const shared_ptr<JsValue> & thisObj,const std::vector<shared_ptr<JsValue>> & argv,int32_t argc)81 shared_ptr<JsValue> JsRunLoopOnce(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj,
82     const std::vector<shared_ptr<JsValue>>& argv, int32_t argc)
83 {
84     auto engineInstance = static_cast<JsiPaEngine*>(runtime->GetEmbedderData());
85     if (engineInstance == nullptr) {
86         LOGE("engineInstance is nullptr");
87         return runtime->NewUndefined();
88     }
89     auto nativeEngine = engineInstance->GetNativeEngine();
90     if (nativeEngine == nullptr) {
91         LOGE("nativeEngine is nullptr");
92         return runtime->NewUndefined();
93     }
94 
95     nativeEngine->Loop(LOOP_ONCE);
96     runtime->ExecutePendingJob();
97     return runtime->NewUndefined();
98 }
99 
100 // native implementation for js function: Particle.JsRunMicrotasks()
JsRunMicrotasks(const shared_ptr<JsRuntime> & runtime,const shared_ptr<JsValue> & thisObj,const std::vector<shared_ptr<JsValue>> & argv,int32_t argc)101 shared_ptr<JsValue> JsRunMicrotasks(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj,
102     const std::vector<shared_ptr<JsValue>>& argv, int32_t argc)
103 {
104     runtime->ExecutePendingJob();
105     return runtime->NewUndefined();
106 }
107 
AsyncFuncCallBack(const shared_ptr<JsRuntime> & runtime,const shared_ptr<JsValue> & thisObj,const std::vector<shared_ptr<JsValue>> & argv,int32_t argc)108 shared_ptr<JsValue> AsyncFuncCallBack(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj,
109     const std::vector<shared_ptr<JsValue>>& argv, int32_t argc)
110 {
111     LOGI("AsyncFuncCallBack");
112     auto engineInstance = static_cast<JsiPaEngine*>(runtime->GetEmbedderData());
113     if (engineInstance == nullptr) {
114         LOGE("engineInstance is nullptr");
115         return runtime->NewUndefined();
116     }
117     if (argc != 2) {
118         LOGE("args length is error");
119         engineInstance->SetBlockWaiting(true);
120         engineInstance->SetAsyncResult(runtime->NewUndefined());
121         return runtime->NewUndefined();
122     }
123     int32_t code = argv[0]->ToInt32(runtime);
124     if (code != 0) {
125         LOGE("AsyncFuncCallBack error code: %{public}d", code);
126     }
127     engineInstance->SetBlockWaiting(true);
128     engineInstance->SetAsyncResult(argv[1]);
129     return runtime->NewUndefined();
130 }
131 
ToJSONStringInt(std::string sKey,std::string sValue)132 inline std::string ToJSONStringInt(std::string sKey, std::string sValue)
133 {
134     char szDoubleQuotes[] = "\"";
135     char szColon[] = ":";
136     std::string strResult;
137     strResult.append(szDoubleQuotes);
138     strResult.append(sKey);
139     strResult.append(szDoubleQuotes);
140 
141     strResult.append(szColon);
142     strResult.append(sValue);
143     return strResult;
144 }
145 } // namespace
146 
RegisterUncaughtExceptionHandler()147 void JsiPaEngine::RegisterUncaughtExceptionHandler()
148 {
149     ACE_SCOPED_TRACE("JsiPaEngine::RegisterUncaughtExceptionHandler");
150     JsEnv::UncaughtExceptionInfo uncaughtExceptionInfo;
151     uncaughtExceptionInfo.uncaughtTask = [](std::string summary, const JsEnv::ErrorObject errorObj) {
152         std::string packageName = AceApplicationInfo::GetInstance().GetPackageName();
153         JsErrorObject errorInfo = {
154             .name = errorObj.name,
155             .message = errorObj.message,
156             .stack = errorObj.stack,
157         };
158         EventReport::JsErrReport(packageName, "", summary);
159         ExceptionHandler::HandleJsException(summary, errorInfo);
160     };
161 
162     jsAbilityRuntime_->RegisterUncaughtExceptionHandler(uncaughtExceptionInfo);
163 }
164 
RegisterConsoleModule(ArkNativeEngine * engine)165 void JsiPaEngine::RegisterConsoleModule(ArkNativeEngine* engine)
166 {
167     ACE_SCOPED_TRACE("JsiPaEngine::RegisterConsoleModule");
168     CHECK_NULL_VOID(engine);
169 
170     napi_env env = reinterpret_cast<napi_env>(engine);
171     napi_value globalObj;
172     napi_get_global(env, &globalObj);
173     napi_valuetype valueType = napi_undefined;
174     napi_typeof(env, globalObj, &valueType);
175     if (valueType != napi_object) {
176         LOGE("global is not NativeObject");
177         return;
178     }
179 
180     napi_value logValue;
181     napi_create_function(env, "log", strlen("log"), AppInfoLogPrint, nullptr, &logValue);
182     napi_value debugValue;
183     napi_create_function(env, "debug", strlen("debug"), AppDebugLogPrint, nullptr, &debugValue);
184     napi_value infoValue;
185     napi_create_function(env, "info", strlen("info"), AppInfoLogPrint, nullptr, &infoValue);
186     napi_value warnValue;
187     napi_create_function(env, "warn", strlen("warn"), AppWarnLogPrint, nullptr, &warnValue);
188     napi_value errorValue;
189     napi_create_function(env, "error", strlen("error"), AppErrorLogPrint, nullptr, &errorValue);
190     napi_value consoleObj = nullptr;
191     napi_create_object(env, &consoleObj);
192     napi_set_named_property(env, consoleObj, "log", logValue);
193     napi_set_named_property(env, consoleObj, "debug", debugValue);
194     napi_set_named_property(env, consoleObj, "info", infoValue);
195     napi_set_named_property(env, consoleObj, "warn", warnValue);
196     napi_set_named_property(env, consoleObj, "error", errorValue);
197     napi_set_named_property(env, globalObj, "console", consoleObj);
198 }
199 
RegisterPaModule()200 void JsiPaEngine::RegisterPaModule()
201 {
202     ACE_SCOPED_TRACE("JsiPaEngine::RegisterAceModule");
203 
204     shared_ptr<JsValue> aceObj = runtime_->NewObject();
205     if (!aceObj) {
206         LOGE("RegisterPaModule failed. aceObj is null");
207         return;
208     }
209     if (!aceObj->SetProperty(runtime_, "onCreateFinish", runtime_->NewFunction(JsOnCreateFinish))) {
210         LOGE("RegisterPaModule onCreateFinish failed.");
211     }
212     if (!aceObj->SetProperty(runtime_, "handleCallback", runtime_->NewFunction(JsHandleCallback))) {
213         LOGE("RegisterPaModule handleCallback failed.");
214     }
215     if (!aceObj->SetProperty(runtime_, "runLoopOnce", runtime_->NewFunction(JsRunLoopOnce))) {
216         LOGE("RegisterPaModule runLoopOnce failed.");
217     }
218     if (!aceObj->SetProperty(runtime_, "runMicrotasks", runtime_->NewFunction(JsRunMicrotasks))) {
219         LOGE("RegisterPaModule runMicrotasks failed.");
220     }
221 
222     shared_ptr<JsValue> global = runtime_->GetGlobal();
223     if (!global->SetProperty(runtime_, "Particle", aceObj)) {
224         LOGE("RegisterPaModule ace failed.");
225     }
226 }
227 
EvaluateJsCode()228 void JsiPaEngine::EvaluateJsCode()
229 {
230     ACE_SCOPED_TRACE("JsiPaEngine::EvaluateJsCode");
231     CHECK_NULL_VOID(jsAbilityRuntime_);
232     // load jsfwk
233     if (language_ == SrcLanguage::JS && !jsAbilityRuntime_->LoadScript("/system/etc/strip.native.min.abc")) {
234         LOGE("Failed to load js framework!");
235     }
236     // load paMgmt.js
237     std::vector<uint8_t> paMgmt(_binary_paMgmt_abc_start, _binary_paMgmt_abc_end);
238     if (!jsAbilityRuntime_->LoadScript("", &paMgmt, true)) {
239         LOGE("EvaluateJsCode paMgmt abc failed");
240     }
241 }
242 
InitJsRuntimeOptions(AbilityRuntime::Runtime::Options & options)243 void JsiPaEngine::InitJsRuntimeOptions(AbilityRuntime::Runtime::Options& options)
244 {
245     options.lang = AbilityRuntime::Runtime::Language::JS;
246     options.eventRunner = eventRunner_;
247     options.loadAce = false;
248     options.preload = false;
249     options.isStageModel = false;
250     options.hapPath = GetHapPath();
251     options.isDebugVersion = GetDebugMode();
252     options.packagePathStr = GetWorkerPath()->packagePathStr;
253     options.assetBasePathStr = GetWorkerPath()->assetBasePathStr;
254     options.isJsFramework = language_ == SrcLanguage::JS;
255 }
256 
CreateJsRuntime()257 bool JsiPaEngine::CreateJsRuntime()
258 {
259     AbilityRuntime::Runtime::Options options;
260     InitJsRuntimeOptions(options);
261     jsAbilityRuntime_ = AbilityRuntime::JsRuntime::Create(options);
262     if (jsAbilityRuntime_ == nullptr) {
263         LOGE("Create js runtime failed.");
264         return false;
265     }
266 
267     return true;
268 }
269 
InitJsEnv(bool debuggerMode,const std::unordered_map<std::string,void * > & extraNativeObject)270 bool JsiPaEngine::InitJsEnv(bool debuggerMode, const std::unordered_map<std::string, void*>& extraNativeObject)
271 {
272     ACE_SCOPED_TRACE("JsiPaEngine::InitJsEnv");
273     runtime_.reset(new ArkJSRuntime());
274     if (runtime_ == nullptr) {
275         LOGE("Can't allocate JSI JSRuntime");
276         EventReport::SendJsException(JsExcepType::JS_ENGINE_INIT_ERR);
277         return false;
278     }
279 
280     runtime_->SetLogPrint(PrintLog);
281     StartDebugMode(debuggerMode);
282 
283     auto ecmaVm = GetEcmaVm();
284     CHECK_NULL_RETURN(ecmaVm, false);
285     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime_);
286     if (!arkJSRuntime->InitializeFromExistVM(ecmaVm)) {
287         LOGE("Initialize runtime from exist vm failed.");
288         return false;
289     }
290     arkJSRuntime->SetDebugMode(isDebugMode_);
291     arkJSRuntime->SetInstanceId(instanceId_);
292 
293 #if !defined(PREVIEW)
294     for (const auto& [key, value] : extraNativeObject) {
295         shared_ptr<JsValue> nativeValue = runtime_->NewNativePointer(value);
296         runtime_->GetGlobal()->SetProperty(runtime_, key, nativeValue);
297     }
298 #endif
299 
300     // Register pa native functions
301     RegisterPaModule();
302 
303     // load abc file
304     EvaluateJsCode();
305 
306     runtime_->SetEmbedderData(this);
307 
308     RegisterUncaughtExceptionHandler();
309     LOGI("InitJsEnv success");
310     return true;
311 }
312 
GetJsRuntime() const313 std::shared_ptr<JsRuntime> JsiPaEngine::GetJsRuntime() const
314 {
315     return runtime_;
316 }
317 
GetNativeEngine() const318 inline NativeEngine* JsiPaEngine::GetNativeEngine() const
319 {
320     CHECK_NULL_RETURN(jsAbilityRuntime_, nullptr);
321     return jsAbilityRuntime_->GetNativeEnginePointer();
322 }
323 
GetEcmaVm() const324 inline panda::ecmascript::EcmaVM* JsiPaEngine::GetEcmaVm() const
325 {
326     CHECK_NULL_RETURN(jsAbilityRuntime_, nullptr);
327     return jsAbilityRuntime_->GetEcmaVm();
328 }
329 
StartDebugMode(bool debuggerMode)330 void JsiPaEngine::StartDebugMode(bool debuggerMode)
331 {
332     if (debuggerMode && jsAbilityRuntime_ != nullptr) {
333 #ifdef OHOS_PLATFORM
334         jsAbilityRuntime_->StartDebugger(debuggerMode, instanceId_);
335 #endif
336     }
337 }
338 
339 // -----------------------
340 // Start JsiPaEngine
341 // -----------------------
~JsiPaEngine()342 JsiPaEngine::~JsiPaEngine()
343 {
344     LOGI("JsiPaEngine destructor");
345     UnloadLibrary();
346 
347     if (runtime_) {
348         runtime_->Reset();
349     }
350     runtime_.reset();
351     runtime_ = nullptr;
352 
353     // To guarantee the jsruntime released in js thread
354     auto jsRuntime = std::move(jsAbilityRuntime_);
355     if (!eventHandler_->PostSyncTask([&jsRuntime] { auto runtime = std::move(jsRuntime); })) {
356         LOGE("Post sync task failed.");
357     }
358 }
359 
Initialize(BackendType type,SrcLanguage language)360 bool JsiPaEngine::Initialize(BackendType type, SrcLanguage language)
361 {
362     ACE_SCOPED_TRACE("JsiPaEngine::Initialize");
363     LOGI("JsiPaEngine initialize");
364     SetDebugMode(NeedDebugBreakPoint());
365     type_ = type;
366     language_ = language;
367 
368     eventRunner_ = EventRunner::Create(TASK_RUNNER + std::to_string(instanceId_));
369     if (eventRunner_ == nullptr) {
370         LOGE("Create runner failed.");
371         return false;
372     }
373 
374     eventHandler_ = std::make_shared<EventHandler>(eventRunner_);
375     if (eventHandler_ == nullptr) {
376         LOGE("Create handler failed.");
377         return false;
378     }
379 
380     bool ret = false;
381     eventHandler_->PostSyncTask([weakEngine = AceType::WeakClaim(this), &ret] {
382         auto paEngine = weakEngine.Upgrade();
383         if (paEngine != nullptr) {
384             ret = paEngine->CreateJsRuntime();
385         }
386     });
387     if (!ret) {
388         return false;
389     }
390 
391     PostTask([weakEngine = AceType::WeakClaim(this), type, language] {
392         auto paEngine = weakEngine.Upgrade();
393         if (paEngine == nullptr) {
394             LOGE("Pa engine is invalid.");
395             return;
396         }
397         paEngine->InitializeInner(type, language);
398     }, "ArkUIPaEngineInit");
399     return true;
400 }
401 
InitializeInner(BackendType type,SrcLanguage language)402 bool JsiPaEngine::InitializeInner(BackendType type, SrcLanguage language)
403 {
404     bool result = InitJsEnv(GetDebugMode(), GetExtraNativeObject());
405     if (!result) {
406         LOGE("Init js env failed");
407         return false;
408     }
409 
410     LoadLibrary();
411 
412     auto nativeEngine = GetNativeEngine();
413     CHECK_NULL_RETURN(nativeEngine, false);
414     if (language_ == SrcLanguage::JS) {
415         InitTimerModule(reinterpret_cast<napi_env>(nativeEngine));
416     }
417 
418     if (jsBackendAssetManager_) {
419         std::vector<std::string> packagePath = jsBackendAssetManager_->GetLibPath();
420         auto appLibPathKey = jsBackendAssetManager_->GetAppLibPathKey();
421         if (!packagePath.empty()) {
422             auto arkNativeEngine = static_cast<ArkNativeEngine*>(nativeEngine);
423             arkNativeEngine->SetPackagePath(appLibPathKey, packagePath);
424         }
425     }
426     return true;
427 }
428 
SetAssetManager(const RefPtr<AssetManager> & assetManager)429 void JsiPaEngine::SetAssetManager(const RefPtr<AssetManager>& assetManager)
430 {
431     jsBackendAssetManager_ = Referenced::MakeRefPtr<JsBackendAssetManager>(assetManager);
432 }
433 
LoadJs(const std::string & url,const OHOS::AAFwk::Want & want)434 void JsiPaEngine::LoadJs(const std::string& url, const OHOS::AAFwk::Want& want)
435 {
436     ACE_SCOPED_TRACE("JsiPaEngine::LoadJs");
437     LOGI("JsiPaEngine LoadJs: %{private}s", url.c_str());
438 
439     auto runtime = GetJsRuntime();
440 
441     // js file to abc file and execute abc file
442     const char js_ext[] = ".js";
443     const char bin_ext[] = ".abc";
444     auto pos = url.rfind(js_ext);
445     if (pos != std::string::npos && pos == url.length() - (sizeof(js_ext) - 1)) {
446         std::string urlName = url.substr(0, pos) + bin_ext;
447         LOGI("GetAssetContent: %{public}s", urlName.c_str());
448         std::vector<uint8_t> content;
449         if (jsBackendAssetManager_ == nullptr || !jsBackendAssetManager_->GetAssetContent(urlName, content)) {
450             LOGE("GetAssetContent \"%{public}s\" failed.", urlName.c_str());
451             return;
452         }
453         std::string abcPath = jsBackendAssetManager_->GetAssetPath(urlName).append(urlName);
454         CHECK_NULL_VOID(jsAbilityRuntime_);
455         if (!jsAbilityRuntime_->LoadScript(abcPath, &content, true)) {
456             LOGE("LoadScript \"%{public}s\" failed.", urlName.c_str());
457             return;
458         }
459 
460         // only ace1.0 need
461         shared_ptr<JsValue> mainEntryFunc = runtime->GetGlobal()->GetProperty(runtime, "___mainEntry___");
462         if (mainEntryFunc->IsFunction(runtime)) {
463             LOGI("JsiPaEngine call mainEntryFunc");
464             runtime->GetGlobal()->SetProperty(runtime, "___mainEntry___", runtime->NewUndefined());
465             const std::vector<shared_ptr<JsValue>>& argv = { runtime->GetGlobal() };
466             shared_ptr<JsValue> retVal = CallFunc(mainEntryFunc, argv);
467             auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
468             if (arkJSRuntime->HasPendingException()) {
469                 LOGE("JsiPaEngine call mainEntryFunc FAILED!");
470             }
471         }
472     }
473 
474     // call start pa func
475     if (type_ == BackendType::SERVICE) {
476         StartService();
477     } else if (type_ == BackendType::DATA) {
478         StartData();
479     } else if (type_ == BackendType::FORM) {
480         LOGI("Form Ability LoadJS finish.");
481     } else {
482         LOGE("backend type not support");
483     }
484 }
485 
LoadLibrary()486 void JsiPaEngine::LoadLibrary()
487 {
488 #ifdef APP_USE_ARM
489     const char* rdbPath = "/system/lib/module/data/librdb.z.so";
490 #else
491     const char* rdbPath = "/system/lib64/module/data/librdb.z.so";
492 #endif
493     if (strlen(rdbPath) == 0) {
494         LOGE("module path is empty");
495         return;
496     }
497 
498     libRdb_ = dlopen(rdbPath, RTLD_LAZY);
499     if (libRdb_ == nullptr) {
500         LOGE("dlopen failed: %{public}s", dlerror());
501     }
502 
503     rdbValueBucketNewInstance_ = reinterpret_cast<RdbValueBucketNewInstance>(
504         dlsym(libRdb_, "NAPI_OHOS_Data_RdbJsKit_ValuesBucketProxy_NewInstance"));
505     if (rdbValueBucketNewInstance_ == nullptr) {
506         LOGE("symbol not found: %{public}s", dlerror());
507     }
508 
509     rdbValueBucketGetNativeObject_ = reinterpret_cast<RdbValueBucketGetNativeObject>(
510         dlsym(libRdb_, "NAPI_OHOS_Data_RdbJsKit_ValuesBucketProxy_GetNativeObject"));
511     if (rdbValueBucketGetNativeObject_ == nullptr) {
512         LOGE("symbol not found: %{public}s", dlerror());
513     }
514 
515     rdbResultSetProxyNewInstance_ = reinterpret_cast<RdbResultSetProxyNewInstance>(
516         dlsym(libRdb_, "NAPI_OHOS_Data_RdbJsKit_ResultSetProxy_NewInstance"));
517     if (rdbResultSetProxyNewInstance_ == nullptr) {
518         LOGE("symbol not found: %{public}s", dlerror());
519     }
520 
521     rdbResultSetProxyGetNativeObject_ = reinterpret_cast<RdbResultSetProxyGetNativeObject>(
522         dlsym(libRdb_, "NAPI_OHOS_Data_RdbJsKit_ResultSetProxy_GetNativeObject"));
523     if (rdbResultSetProxyGetNativeObject_ == nullptr) {
524         LOGE("symbol not found: %{public}s", dlerror());
525     }
526 
527 #ifdef APP_USE_ARM
528     const char* dataAbilityPath = "/system/lib/module/data/libdataability.z.so";
529 #else
530     const char* dataAbilityPath = "/system/lib64/module/data/libdataability.z.so";
531 #endif
532     if (strlen(dataAbilityPath) == 0) {
533         LOGE("module path is empty");
534         return;
535     }
536 
537     libDataAbility_ = dlopen(dataAbilityPath, RTLD_LAZY);
538     if (libDataAbility_ == nullptr) {
539         LOGE("dlopen failed: %{public}s", dlerror());
540     }
541 
542     dataAbilityPredicatesNewInstance_ = reinterpret_cast<DataAbilityPredicatesNewInstance>(
543         dlsym(libDataAbility_, "NAPI_OHOS_Data_DataAbilityJsKit_DataAbilityPredicatesProxy_NewInstance"));
544     if (dataAbilityPredicatesNewInstance_ == nullptr) {
545         LOGE("symbol not found: %{public}s", dlerror());
546     }
547 
548     dataAbilityPredicatesGetNativeObject_ = reinterpret_cast<DataAbilityPredicatesGetNativeObject>(
549         dlsym(libDataAbility_, "NAPI_OHOS_Data_DataAbilityJsKit_DataAbilityPredicatesProxy_GetNativeObject"));
550     if (dataAbilityPredicatesGetNativeObject_ == nullptr) {
551         LOGE("symbol not found: %{public}s", dlerror());
552     }
553 }
554 
UnloadLibrary()555 void JsiPaEngine::UnloadLibrary()
556 {
557     dlclose(libRdb_);
558     dlclose(libDataAbility_);
559 }
560 
GetPaFunc(const std::string & funcName)561 shared_ptr<JsValue> JsiPaEngine::GetPaFunc(const std::string& funcName)
562 {
563     LOGI("JsiPaEngine GetPaFunc funcName: %{public}s", funcName.c_str());
564     shared_ptr<JsRuntime> runtime = GetJsRuntime();
565     ACE_DCHECK(runtime);
566     shared_ptr<JsValue> global = runtime->GetGlobal();
567     shared_ptr<JsValue> exportsObject = global->GetProperty(runtime, "exports");
568     if (!exportsObject->IsObject(runtime)) {
569         LOGE("property \"exports\" is not a object");
570         return nullptr;
571     }
572     shared_ptr<JsValue> defaultObject = exportsObject->GetProperty(runtime, "default");
573     if (!defaultObject->IsObject(runtime)) {
574         LOGE("property \"default\" is not a object");
575         return nullptr;
576     }
577 
578     shared_ptr<JsValue> func = defaultObject->GetProperty(runtime, funcName);
579     if (!func->IsFunction(runtime)) {
580         LOGE("%{public}s not found or is not a function!", funcName.c_str());
581         return nullptr;
582     }
583     return func;
584 }
585 
CallFunc(const shared_ptr<JsValue> & func)586 shared_ptr<JsValue> JsiPaEngine::CallFunc(const shared_ptr<JsValue>& func)
587 {
588     const std::vector<shared_ptr<JsValue>>& argv = {};
589     return CallFunc(func, argv);
590 }
591 
CallFunc(const shared_ptr<JsValue> & func,const std::vector<shared_ptr<JsValue>> & argv)592 shared_ptr<JsValue> JsiPaEngine::CallFunc(const shared_ptr<JsValue>& func, const std::vector<shared_ptr<JsValue>>& argv)
593 {
594     shared_ptr<JsRuntime> runtime = GetJsRuntime();
595     ACE_DCHECK(runtime);
596     if (func == nullptr) {
597         LOGE("func is nullptr!");
598         return runtime->NewUndefined();
599     }
600     if (!func->IsFunction(runtime)) {
601         LOGE("func is not a function!");
602         return runtime->NewUndefined();
603     }
604 
605     auto nativeEngine = GetNativeEngine();
606     CHECK_NULL_RETURN(nativeEngine, runtime->NewUndefined());
607     napi_env env = reinterpret_cast<napi_env>(nativeEngine);
608     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
609     if (arkJSRuntime->HasPendingException()) {
610         LOGE("JsiPaEngine CallFunc FAILED!");
611         return runtime->NewUndefined();
612     }
613 
614     auto arkJSFunc = std::static_pointer_cast<ArkJSValue>(func);
615     if (arkJSFunc->IsUndefined(runtime)) {
616         LOGE("JsiPaEngine CallFunc return value is und efined!");
617         return runtime->NewUndefined();
618     }
619 
620     std::vector<napi_value> nativeArgv;
621     int32_t length = 0;
622     for (auto item : argv) {
623         auto value = std::static_pointer_cast<ArkJSValue>(item);
624         auto napiValue = ArkNativeEngine::ArkValueToNapiValue(env, value->GetValue(arkJSRuntime));
625         nativeArgv.emplace_back(napiValue);
626         length++;
627     }
628 
629     napi_value nativeFunc = ArkNativeEngine::ArkValueToNapiValue(env, arkJSFunc->GetValue(arkJSRuntime));
630     CHECK_NULL_RETURN(nativeFunc, nullptr);
631     napi_value globalObj;
632     napi_get_global(env, &globalObj);
633     napi_valuetype valueType = napi_undefined;
634     napi_typeof(env, globalObj, &valueType);
635     if (valueType != napi_object) {
636         LOGE("global is not NativeObject");
637         return runtime->NewUndefined();
638     }
639     napi_value ret;
640     napi_call_function(env, globalObj, nativeFunc, length, nativeArgv.data(), &ret);
641     return NapiValueToJsValue(ret);
642 }
643 
CallFuncWithDefaultThis(const shared_ptr<JsValue> & func,const std::vector<shared_ptr<JsValue>> & argv)644 shared_ptr<JsValue> JsiPaEngine::CallFuncWithDefaultThis(
645     const shared_ptr<JsValue>& func, const std::vector<shared_ptr<JsValue>>& argv)
646 {
647     shared_ptr<JsRuntime> runtime = GetJsRuntime();
648     ACE_DCHECK(runtime);
649     if (func == nullptr) {
650         LOGE("func is nullptr!");
651         return runtime->NewUndefined();
652     }
653     if (!func->IsFunction(runtime)) {
654         LOGE("func is not a function!");
655         return runtime->NewUndefined();
656     }
657 
658     shared_ptr<JsValue> global = runtime->GetGlobal();
659     shared_ptr<JsValue> thisObject = global;
660     do {
661         shared_ptr<JsValue> exportsObject = global->GetProperty(runtime, "exports");
662         if (!exportsObject->IsObject(runtime)) {
663             LOGW("property \"exports\" is not a object");
664             break;
665         }
666         shared_ptr<JsValue> defaultObject = exportsObject->GetProperty(runtime, "default");
667         if (!defaultObject->IsObject(runtime)) {
668             LOGE("property \"default\" is not a object");
669             break;
670         }
671         thisObject = defaultObject;
672     } while (false);
673 
674     auto nativeEngine = GetNativeEngine();
675     CHECK_NULL_RETURN(nativeEngine, runtime->NewUndefined());
676     napi_env env = reinterpret_cast<napi_env>(nativeEngine);
677     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
678     if (arkJSRuntime->HasPendingException()) {
679         LOGE("JsiPaEngine CallFunc FAILED!");
680         return runtime->NewUndefined();
681     }
682 
683     auto arkJSThis = std::static_pointer_cast<ArkJSValue>(thisObject);
684     if (arkJSThis->IsUndefined(runtime)) {
685         LOGE("JsiPaEngine CallFunc return value is undefined!");
686         return runtime->NewUndefined();
687     }
688 
689     auto arkJSFunc = std::static_pointer_cast<ArkJSValue>(func);
690     if (arkJSFunc->IsUndefined(runtime)) {
691         LOGE("JsiPaEngine CallFunc return value is und efined!");
692         return runtime->NewUndefined();
693     }
694 
695     std::vector<napi_value> nativeArgv;
696     int32_t length = 0;
697     for (auto item : argv) {
698         auto value = std::static_pointer_cast<ArkJSValue>(item);
699         auto nativeVal = ArkNativeEngine::ArkValueToNapiValue(env, value->GetValue(arkJSRuntime));
700         nativeArgv.emplace_back(nativeVal);
701         length++;
702     }
703 
704     napi_value nativeFunc = ArkNativeEngine::ArkValueToNapiValue(env, arkJSFunc->GetValue(arkJSRuntime));
705     CHECK_NULL_RETURN(nativeFunc, nullptr);
706 
707     napi_value nativeThis = ArkNativeEngine::ArkValueToNapiValue(env, arkJSThis->GetValue(arkJSRuntime));
708     CHECK_NULL_RETURN(nativeThis, nullptr);
709 
710     napi_value ret;
711     napi_call_function(env, nativeThis, nativeFunc, length, nativeArgv.data(), &ret);
712 
713     return NapiValueToJsValue(ret);
714 }
715 
CallFunc(const shared_ptr<JsValue> & func,const std::vector<shared_ptr<JsValue>> & argv,const CallingInfo & callingInfo)716 shared_ptr<JsValue> JsiPaEngine::CallFunc(
717     const shared_ptr<JsValue>& func, const std::vector<shared_ptr<JsValue>>& argv, const CallingInfo& callingInfo)
718 {
719     shared_ptr<JsRuntime> runtime = GetJsRuntime();
720     ACE_DCHECK(runtime);
721     if (func == nullptr) {
722         LOGE("func is nullptr!");
723         return runtime->NewUndefined();
724     }
725     if (!func->IsFunction(runtime)) {
726         LOGE("func is not a function!");
727         return runtime->NewUndefined();
728     }
729     shared_ptr<JsValue> global = runtime->GetGlobal();
730 
731     auto nativeEngine = GetNativeEngine();
732     CHECK_NULL_RETURN(nativeEngine, runtime->NewUndefined());
733     napi_env env = reinterpret_cast<napi_env>(nativeEngine);
734     NAPI_CallingInfo oldCallingInfo;
735     NAPI_RemoteObject_saveOldCallingInfo(env, oldCallingInfo);
736     NAPI_RemoteObject_setNewCallingInfo(env, callingInfo);
737     NAPI_RemoteObject_resetOldCallingInfo(env, oldCallingInfo);
738 
739     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
740     if (arkJSRuntime->HasPendingException()) {
741         LOGE("JsiPaEngine CallFunc FAILED!");
742         return runtime->NewUndefined();
743     }
744 
745     auto arkJSFunc = std::static_pointer_cast<ArkJSValue>(func);
746     if (arkJSFunc->IsUndefined(runtime)) {
747         LOGE("JsiPaEngine CallFunc return value is und efined!");
748         return runtime->NewUndefined();
749     }
750 
751     std::vector<napi_value> nativeArgv;
752     int32_t length = 0;
753 
754     for (auto item : argv) {
755         auto value = std::static_pointer_cast<ArkJSValue>(item);
756         auto napiValue = ArkNativeEngine::ArkValueToNapiValue(env, value->GetValue(arkJSRuntime));
757         nativeArgv.emplace_back(napiValue);
758         length++;
759     }
760 
761     napi_value nativeFunc = ArkNativeEngine::ArkValueToNapiValue(env, arkJSFunc->GetValue(arkJSRuntime));
762     CHECK_NULL_RETURN(nativeFunc, nullptr);
763 
764     napi_value globalObj;
765     napi_get_global(env, &globalObj);
766     napi_valuetype valueType = napi_undefined;
767     napi_typeof(env, globalObj, &valueType);
768     if (valueType != napi_object) {
769         LOGE("global is not NativeObject");
770         return runtime->NewUndefined();
771     }
772     napi_value ret;
773     napi_call_function(env, globalObj, nativeFunc, length, nativeArgv.data(), &ret);
774     return NapiValueToJsValue(ret);
775 }
776 
CallAsyncFunc(const shared_ptr<JsValue> & func,std::vector<shared_ptr<JsValue>> & argv,const CallingInfo & callingInfo)777 shared_ptr<JsValue> JsiPaEngine::CallAsyncFunc(
778     const shared_ptr<JsValue>& func, std::vector<shared_ptr<JsValue>>& argv, const CallingInfo& callingInfo)
779 {
780     shared_ptr<JsRuntime> runtime = GetJsRuntime();
781     ACE_DCHECK(runtime);
782     if (func == nullptr) {
783         LOGE("func is nullptr!");
784         return runtime->NewUndefined();
785     }
786     if (!func->IsFunction(runtime)) {
787         LOGE("func is not a function!");
788         return runtime->NewUndefined();
789     }
790     shared_ptr<JsValue> global = runtime->GetGlobal();
791 
792     auto nativeEngine = GetNativeEngine();
793     CHECK_NULL_RETURN(nativeEngine, runtime->NewUndefined());
794     napi_env env = reinterpret_cast<napi_env>(nativeEngine);
795     NAPI_CallingInfo oldCallingInfo;
796     NAPI_RemoteObject_saveOldCallingInfo(env, oldCallingInfo);
797     NAPI_RemoteObject_setNewCallingInfo(env, callingInfo);
798 
799     argv.push_back(runtime->NewFunction(AsyncFuncCallBack));
800 
801     SetBlockWaiting(false);
802 
803     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
804     if (arkJSRuntime->HasPendingException()) {
805         LOGE("JsiPaEngine CallFunc FAILED!");
806         return runtime->NewUndefined();
807     }
808 
809     auto arkJSFunc = std::static_pointer_cast<ArkJSValue>(func);
810     if (arkJSFunc->IsUndefined(runtime)) {
811         LOGE("JsiPaEngine CallFunc return value is und efined!");
812         return runtime->NewUndefined();
813     }
814 
815     std::vector<napi_value> nativeArgv;
816     int32_t length = 0;
817     for (auto item : argv) {
818         auto value = std::static_pointer_cast<ArkJSValue>(item);
819         auto napiValue = ArkNativeEngine::ArkValueToNapiValue(env, value->GetValue(arkJSRuntime));
820         nativeArgv.emplace_back(napiValue);
821         length++;
822     }
823 
824     napi_value nativeFunc = ArkNativeEngine::ArkValueToNapiValue(env, arkJSFunc->GetValue(arkJSRuntime));
825     CHECK_NULL_RETURN(nativeFunc, nullptr);
826     napi_value globalObj;
827     napi_get_global(env, &globalObj);
828     napi_valuetype valueType = napi_undefined;
829     napi_typeof(env, globalObj, &valueType);
830     if (valueType != napi_object) {
831         LOGE("global is not NativeObject");
832         return runtime->NewUndefined();
833     }
834     napi_value ret;
835     napi_call_function(env, globalObj, nativeFunc, length, nativeArgv.data(), &ret);
836 
837     runtime->ExecutePendingJob();
838     while (!GetBlockWaiting()) {
839         nativeEngine->Loop(LOOP_ONCE);
840         runtime->ExecutePendingJob();
841     }
842     NAPI_RemoteObject_resetOldCallingInfo(env, oldCallingInfo);
843     return GetAsyncResult();
844 }
845 
NapiValueToJsValue(napi_value napiValue)846 shared_ptr<JsValue> JsiPaEngine::NapiValueToJsValue(napi_value napiValue)
847 {
848     if (napiValue == nullptr) {
849         LOGE("napiValue is nullptr!");
850         return GetJsRuntime()->NewUndefined();
851     }
852     auto arkRuntime = std::static_pointer_cast<ArkJSRuntime>(GetJsRuntime());
853     return std::make_shared<ArkJSValue>(arkRuntime, NapiValueToLocalValue(napiValue));
854 }
855 
WantToJsValue(const OHOS::AAFwk::Want & want)856 shared_ptr<JsValue> JsiPaEngine::WantToJsValue(const OHOS::AAFwk::Want& want)
857 {
858     napi_value napiWant = OHOS::AppExecFwk::WrapWant(reinterpret_cast<napi_env>(GetNativeEngine()), want);
859     return NapiValueToJsValue(napiWant);
860 }
861 
StartService()862 void JsiPaEngine::StartService()
863 {
864     LOGI("JsiPaEngine StartService");
865     auto func = GetPaFunc("onStart");
866     CallFunc(func);
867 }
868 
StartData()869 void JsiPaEngine::StartData()
870 {
871     LOGI("JsiPaEngine StartData");
872 
873     const auto& nativeObjects = GetExtraNativeObject();
874     auto it = nativeObjects.find("ability");
875     if (it == nativeObjects.end() || it->second == nullptr) {
876         LOGE("Can't find ability object");
877         return;
878     }
879 
880     shared_ptr<JsRuntime> runtime = GetJsRuntime();
881     auto nativeEngine = GetNativeEngine();
882     CHECK_NULL_VOID(nativeEngine);
883     const std::shared_ptr<AppExecFwk::AbilityInfo> abilityInfo =
884         reinterpret_cast<Ability*>(it->second)->GetAbilityInfo();
885     const AppExecFwk::AbilityInfo abilityInfoInstance = *(abilityInfo.get());
886     napi_value abilityInfoNapi =
887         AppExecFwk::ConvertAbilityInfo(reinterpret_cast<napi_env>(nativeEngine), abilityInfoInstance);
888     const std::vector<shared_ptr<JsValue>>& argv = { NapiValueToJsValue(abilityInfoNapi) };
889 
890     auto func = GetPaFunc("onInitialized");
891     CallFunc(func, argv);
892 }
893 
DestroyApplication(const std::string & packageName)894 void JsiPaEngine::DestroyApplication(const std::string& packageName)
895 {
896     LOGI("JsiPaEngine DestroyApplication");
897     shared_ptr<JsRuntime> runtime = GetJsRuntime();
898     const std::vector<shared_ptr<JsValue>>& argv = { runtime->NewString(packageName) };
899     auto func = GetPaFunc("onStop");
900     CallFunc(func, argv);
901 }
902 
Insert(const Uri & uri,const OHOS::NativeRdb::ValuesBucket & value,const CallingInfo & callingInfo)903 int32_t JsiPaEngine::Insert(const Uri& uri, const OHOS::NativeRdb::ValuesBucket& value, const CallingInfo& callingInfo)
904 {
905     LOGI("JsiPaEngine Insert");
906     shared_ptr<JsRuntime> runtime = GetJsRuntime();
907     auto nativeEngine = GetNativeEngine();
908     CHECK_NULL_RETURN(nativeEngine, 0);
909     napi_env env = reinterpret_cast<napi_env>(nativeEngine);
910     napi_value argNapiValue = rdbValueBucketNewInstance_(env, const_cast<OHOS::NativeRdb::ValuesBucket&>(value));
911     std::vector<shared_ptr<JsValue>> argv;
912     argv.push_back(runtime->NewString(uri.ToString()));
913     argv.push_back(NapiValueToJsValue(argNapiValue));
914     auto func = GetPaFunc("insert");
915     shared_ptr<JsValue> retVal = CallAsyncFunc(func, argv, callingInfo);
916 
917     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
918     if (arkJSRuntime->HasPendingException()) {
919         LOGE("JsiPaEngine Insert FAILED!");
920         return 0;
921     }
922     auto arkJSValue = std::static_pointer_cast<ArkJSValue>(retVal);
923     return arkJSValue->ToInt32(runtime);
924 }
925 
ExcludeTag(const std::string & jsonString,const std::string & tagString)926 std::string JsiPaEngine::ExcludeTag(const std::string& jsonString, const std::string& tagString)
927 {
928     size_t pos = jsonString.find(tagString);
929     if (pos == std::string::npos) {
930         return jsonString;
931     }
932     std::string valueString = jsonString.substr(pos);
933     pos = valueString.find(":");
934     if (pos == std::string::npos) {
935         return "";
936     }
937     size_t valuePos = pos + 1;
938     while (valuePos < valueString.size()) {
939         if (valueString.at(valuePos) != ' ' && valueString.at(valuePos) != '\t') {
940             break;
941         }
942         valuePos++;
943     }
944     if (valuePos >= valueString.size()) {
945         return "";
946     }
947     valueString = valueString.substr(valuePos);
948     return valueString.substr(0, valueString.size() - 1);
949 }
950 
IncludeTag(const std::string & jsonString,const std::string & tagString)951 std::string JsiPaEngine::IncludeTag(const std::string& jsonString, const std::string& tagString)
952 {
953     std::string result = "{\"" + tagString + "\":";
954     result += jsonString;
955     result += "}";
956     return result;
957 }
958 
Call(const std::string & method,const std::string & arg,const AppExecFwk::PacMap & pacMap,const CallingInfo & callingInfo)959 std::shared_ptr<AppExecFwk::PacMap> JsiPaEngine::Call(
960     const std::string& method, const std::string& arg, const AppExecFwk::PacMap& pacMap, const CallingInfo& callingInfo)
961 {
962     std::string pacString = const_cast<AppExecFwk::PacMap&>(pacMap).ToString();
963     std::string params = ExcludeTag(pacString, "pacmap");
964     shared_ptr<JsRuntime> runtime = GetJsRuntime();
965     std::vector<shared_ptr<JsValue>> argv;
966     argv.push_back(runtime->NewString(method));
967     argv.push_back(runtime->NewString(arg));
968     argv.push_back(runtime->NewString(params));
969     auto func = GetPaFunc("call");
970     if (func == nullptr) {
971         return nullptr;
972     }
973     shared_ptr<JsValue> retVal = CallFunc(func, argv, callingInfo);
974     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
975     if (arkJSRuntime->HasPendingException()) {
976         LOGE("JsiPaEngine Query FAILED!");
977         return nullptr;
978     }
979     auto arkJSValue = std::static_pointer_cast<ArkJSValue>(retVal);
980     if (arkJSValue->IsUndefined(runtime)) {
981         LOGE("JsiPaEngine Query return value is undefined!");
982         return nullptr;
983     }
984     std::string retStr = IncludeTag(arkJSValue->ToString(runtime), "pacmap");
985     auto result = std::make_shared<AppExecFwk::PacMap>();
986     if (result == nullptr) {
987         LOGE("fail to create PacMap");
988         return nullptr;
989     }
990     result->FromString(retStr);
991     return result;
992 }
993 
BatchInsert(const Uri & uri,const std::vector<OHOS::NativeRdb::ValuesBucket> & values,const CallingInfo & callingInfo)994 int32_t JsiPaEngine::BatchInsert(
995     const Uri& uri, const std::vector<OHOS::NativeRdb::ValuesBucket>& values, const CallingInfo& callingInfo)
996 {
997     LOGI("JsiPaEngine BatchInsert");
998     shared_ptr<JsRuntime> runtime = GetJsRuntime();
999     auto nativeEngine = GetNativeEngine();
1000     CHECK_NULL_RETURN(nativeEngine, 0);
1001     napi_env env = reinterpret_cast<napi_env>(nativeEngine);
1002     napi_value argColumnsNapiValue = nullptr;
1003     napi_create_array(env, &argColumnsNapiValue);
1004     bool isArray = false;
1005     if (napi_is_array(env, argColumnsNapiValue, &isArray) != napi_ok || !isArray) {
1006         LOGE("JsiPaEngine create array failed");
1007         return 0;
1008     }
1009     int32_t index = 0;
1010     for (auto value : values) {
1011         napi_value result = rdbValueBucketNewInstance_(env, const_cast<OHOS::NativeRdb::ValuesBucket&>(value));
1012         napi_set_element(env, argColumnsNapiValue, index++, result);
1013     }
1014 
1015     std::vector<shared_ptr<JsValue>> argv;
1016     argv.push_back(runtime->NewString(uri.ToString()));
1017     argv.push_back(NapiValueToJsValue(argColumnsNapiValue));
1018     auto func = GetPaFunc("batchInsert");
1019     shared_ptr<JsValue> retVal = CallAsyncFunc(func, argv, callingInfo);
1020     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1021     if (arkJSRuntime->HasPendingException()) {
1022         LOGE("JsiPaEngine BatchInsert FAILED!");
1023         return 0;
1024     }
1025     auto arkJSValue = std::static_pointer_cast<ArkJSValue>(retVal);
1026     return arkJSValue->ToInt32(runtime);
1027 }
1028 
Query(const Uri & uri,const std::vector<std::string> & columns,const OHOS::NativeRdb::DataAbilityPredicates & predicates,const CallingInfo & callingInfo)1029 std::shared_ptr<OHOS::NativeRdb::AbsSharedResultSet> JsiPaEngine::Query(const Uri& uri,
1030     const std::vector<std::string>& columns, const OHOS::NativeRdb::DataAbilityPredicates& predicates,
1031     const CallingInfo& callingInfo)
1032 {
1033     LOGI("JsiPaEngine Query");
1034     std::shared_ptr<OHOS::NativeRdb::AbsSharedResultSet> resultSet = nullptr;
1035     shared_ptr<JsRuntime> runtime = GetJsRuntime();
1036     auto nativeEngine = GetNativeEngine();
1037     CHECK_NULL_RETURN(nativeEngine, resultSet);
1038     napi_env env = reinterpret_cast<napi_env>(nativeEngine);
1039     napi_value argColumnsNapiValue = nullptr;
1040     napi_create_array(env, &argColumnsNapiValue);
1041     bool isArray = false;
1042     if (napi_is_array(env, argColumnsNapiValue, &isArray) != napi_ok || !isArray) {
1043         LOGE("JsiPaEngine create array failed");
1044         return resultSet;
1045     }
1046     int32_t index = 0;
1047     for (auto column : columns) {
1048         napi_value result = nullptr;
1049         napi_create_string_utf8(env, column.c_str(), column.length(), &result);
1050         napi_set_element(env, argColumnsNapiValue, index++, result);
1051     }
1052 
1053     OHOS::NativeRdb::DataAbilityPredicates* predicatesPtr = new OHOS::NativeRdb::DataAbilityPredicates();
1054     *predicatesPtr = predicates;
1055     napi_value argPredicatesNapiValue = dataAbilityPredicatesNewInstance_(env, predicatesPtr);
1056     if (argPredicatesNapiValue == nullptr) {
1057         LOGE("JsiPaEngine Query argPredicatesNapiValue is nullptr");
1058         return resultSet;
1059     }
1060 
1061     std::vector<shared_ptr<JsValue>> argv;
1062     argv.push_back(runtime->NewString(uri.ToString()));
1063     argv.push_back(NapiValueToJsValue(argColumnsNapiValue));
1064     argv.push_back(NapiValueToJsValue(argPredicatesNapiValue));
1065     auto func = GetPaFunc("query");
1066     shared_ptr<JsValue> retVal = CallAsyncFunc(func, argv, callingInfo);
1067 
1068     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1069     if (arkJSRuntime->HasPendingException()) {
1070         LOGE("JsiPaEngine Query FAILED!");
1071         return resultSet;
1072     }
1073     auto arkJSValue = std::static_pointer_cast<ArkJSValue>(retVal);
1074     if (arkJSValue->IsUndefined(runtime)) {
1075         LOGE("JsiPaEngine Query return value is undefined!");
1076         return resultSet;
1077     }
1078 
1079     napi_value napiValue = ArkNativeEngine::ArkValueToNapiValue(env, arkJSValue->GetValue(arkJSRuntime));
1080     if (napiValue == nullptr) {
1081         LOGE("JsiPaEngine nativeValue is nullptr");
1082         return resultSet;
1083     }
1084     resultSet = rdbResultSetProxyGetNativeObject_(env, napiValue);
1085     if (resultSet == nullptr) {
1086         LOGE("JsiPaEngine AbsSharedResultSet from JS to Native failed");
1087     }
1088     return resultSet;
1089 }
1090 
Update(const Uri & uri,const OHOS::NativeRdb::ValuesBucket & value,const OHOS::NativeRdb::DataAbilityPredicates & predicates,const CallingInfo & callingInfo)1091 int32_t JsiPaEngine::Update(const Uri& uri, const OHOS::NativeRdb::ValuesBucket& value,
1092     const OHOS::NativeRdb::DataAbilityPredicates& predicates, const CallingInfo& callingInfo)
1093 {
1094     LOGI("JsiPaEngine Update");
1095     shared_ptr<JsRuntime> runtime = GetJsRuntime();
1096     auto nativeEngine = GetNativeEngine();
1097     CHECK_NULL_RETURN(nativeEngine, 0);
1098     napi_env env = reinterpret_cast<napi_env>(nativeEngine);
1099     napi_value argNapiValue = rdbValueBucketNewInstance_(env, const_cast<OHOS::NativeRdb::ValuesBucket&>(value));
1100 
1101     OHOS::NativeRdb::DataAbilityPredicates* predicatesPtr = new OHOS::NativeRdb::DataAbilityPredicates();
1102     *predicatesPtr = predicates;
1103     napi_value argPredicatesNapiValue = dataAbilityPredicatesNewInstance_(env, predicatesPtr);
1104     if (argPredicatesNapiValue == nullptr) {
1105         LOGE("JsiPaEngine Update argPredicatesNativeValue is nullptr");
1106         return 0;
1107     }
1108 
1109     std::vector<shared_ptr<JsValue>> argv;
1110     argv.push_back(runtime->NewString(uri.ToString()));
1111     argv.push_back(NapiValueToJsValue(argNapiValue));
1112     argv.push_back(NapiValueToJsValue(argPredicatesNapiValue));
1113     auto func = GetPaFunc("update");
1114     shared_ptr<JsValue> retVal = CallAsyncFunc(func, argv, callingInfo);
1115 
1116     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1117     if (arkJSRuntime->HasPendingException()) {
1118         LOGE("JsiPaEngine Update FAILED!");
1119         return 0;
1120     }
1121     auto arkJSValue = std::static_pointer_cast<ArkJSValue>(retVal);
1122     return arkJSValue->ToInt32(runtime);
1123 }
1124 
Delete(const Uri & uri,const OHOS::NativeRdb::DataAbilityPredicates & predicates,const CallingInfo & callingInfo)1125 int32_t JsiPaEngine::Delete(
1126     const Uri& uri, const OHOS::NativeRdb::DataAbilityPredicates& predicates, const CallingInfo& callingInfo)
1127 {
1128     LOGI("JsiPaEngine Delete");
1129     shared_ptr<JsRuntime> runtime = GetJsRuntime();
1130     auto nativeEngine = GetNativeEngine();
1131     CHECK_NULL_RETURN(nativeEngine, 0);
1132     napi_env env = reinterpret_cast<napi_env>(nativeEngine);
1133     OHOS::NativeRdb::DataAbilityPredicates* predicatesPtr = new OHOS::NativeRdb::DataAbilityPredicates();
1134     *predicatesPtr = predicates;
1135     napi_value argPredicatesNapiValue = dataAbilityPredicatesNewInstance_(env, predicatesPtr);
1136     if (argPredicatesNapiValue == nullptr) {
1137         LOGE("JsiPaEngine Delete argPredicatesNativeValue is nullptr");
1138         return 0;
1139     }
1140 
1141     std::vector<shared_ptr<JsValue>> argv;
1142     argv.push_back(runtime->NewString(uri.ToString()));
1143     argv.push_back(NapiValueToJsValue(argPredicatesNapiValue));
1144     auto func = GetPaFunc("delete");
1145     shared_ptr<JsValue> retVal = CallAsyncFunc(func, argv, callingInfo);
1146 
1147     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1148     if (arkJSRuntime->HasPendingException()) {
1149         LOGE("JsiPaEngine Delete FAILED!");
1150         return 0;
1151     }
1152     auto arkJSValue = std::static_pointer_cast<ArkJSValue>(retVal);
1153     return arkJSValue->ToInt32(runtime);
1154 }
1155 
GetType(const Uri & uri,const CallingInfo & callingInfo)1156 std::string JsiPaEngine::GetType(const Uri& uri, const CallingInfo& callingInfo)
1157 {
1158     shared_ptr<JsRuntime> runtime = GetJsRuntime();
1159     std::vector<shared_ptr<JsValue>> argv;
1160     argv.push_back(runtime->NewString(uri.ToString()));
1161     auto func = GetPaFunc("getType");
1162     shared_ptr<JsValue> retVal = CallAsyncFunc(func, argv, callingInfo);
1163 
1164     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1165     if (arkJSRuntime->HasPendingException()) {
1166         LOGE("JsiPaEngine GetType FAILED!");
1167         return std::string();
1168     }
1169     auto arkJSValue = std::static_pointer_cast<ArkJSValue>(retVal);
1170     return arkJSValue->ToString(runtime);
1171 }
1172 
GetFileTypes(const Uri & uri,const std::string & mimeTypeFilter,const CallingInfo & callingInfo)1173 std::vector<std::string> JsiPaEngine::GetFileTypes(
1174     const Uri& uri, const std::string& mimeTypeFilter, const CallingInfo& callingInfo)
1175 {
1176     shared_ptr<JsRuntime> runtime = GetJsRuntime();
1177     std::vector<shared_ptr<JsValue>> argv;
1178     argv.push_back(runtime->NewString(uri.ToString()));
1179     argv.push_back(runtime->NewString(mimeTypeFilter));
1180     auto func = GetPaFunc("getFileTypes");
1181     shared_ptr<JsValue> retVal = CallAsyncFunc(func, argv, callingInfo);
1182 
1183     std::vector<std::string> ret;
1184     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1185     if (arkJSRuntime->HasPendingException()) {
1186         LOGE("JsiPaEngine GetFileTypes FAILED!");
1187         return ret;
1188     }
1189     auto arkJSValue = std::static_pointer_cast<ArkJSValue>(retVal);
1190     if (!arkJSValue->IsArray(runtime)) {
1191         LOGE("JsiPaEngine GetFileTypes return not array!");
1192         return ret;
1193     }
1194     int32_t length = arkJSValue->GetArrayLength(runtime);
1195     LOGI("JsiPaEngine GetFileTypes array length %{public}d", length);
1196     for (int i = 0; i < length; i++) {
1197         auto itemVal = arkJSValue->GetProperty(runtime, i);
1198         ret.push_back(itemVal->ToString(runtime));
1199     }
1200     return ret;
1201 }
1202 
OpenFile(const Uri & uri,const std::string & mode,const CallingInfo & callingInfo)1203 int32_t JsiPaEngine::OpenFile(const Uri& uri, const std::string& mode, const CallingInfo& callingInfo)
1204 {
1205     LOGI("JsiPaEngine OpenFile");
1206     shared_ptr<JsRuntime> runtime = GetJsRuntime();
1207     std::vector<shared_ptr<JsValue>> argv;
1208     argv.push_back(runtime->NewString(uri.ToString()));
1209     argv.push_back(runtime->NewString(mode));
1210     auto func = GetPaFunc("openFile");
1211     shared_ptr<JsValue> retVal = CallAsyncFunc(func, argv, callingInfo);
1212 
1213     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1214     if (arkJSRuntime->HasPendingException()) {
1215         LOGE("JsiPaEngine OpenFile FAILED!");
1216         return 0;
1217     }
1218     auto arkJSValue = std::static_pointer_cast<ArkJSValue>(retVal);
1219     return arkJSValue->ToInt32(runtime);
1220 }
1221 
OpenRawFile(const Uri & uri,const std::string & mode,const CallingInfo & callingInfo)1222 int32_t JsiPaEngine::OpenRawFile(const Uri& uri, const std::string& mode, const CallingInfo& callingInfo)
1223 {
1224     LOGI("JsiPaEngine OpenRawFile");
1225     shared_ptr<JsRuntime> runtime = GetJsRuntime();
1226     std::vector<shared_ptr<JsValue>> argv;
1227     argv.push_back(runtime->NewString(uri.ToString()));
1228     argv.push_back(runtime->NewString(mode));
1229     auto func = GetPaFunc("openRawFile");
1230     shared_ptr<JsValue> retVal = CallAsyncFunc(func, argv, callingInfo);
1231 
1232     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1233     if (arkJSRuntime->HasPendingException()) {
1234         LOGE("JsiPaEngine OpenRawFile FAILED!");
1235         return 0;
1236     }
1237     auto arkJSValue = std::static_pointer_cast<ArkJSValue>(retVal);
1238     return arkJSValue->ToInt32(runtime);
1239 }
1240 
NormalizeUri(const Uri & uri,const CallingInfo & callingInfo)1241 Uri JsiPaEngine::NormalizeUri(const Uri& uri, const CallingInfo& callingInfo)
1242 {
1243     LOGI("JsiPaEngine NormalizeUri");
1244     shared_ptr<JsRuntime> runtime = GetJsRuntime();
1245     std::vector<shared_ptr<JsValue>> argv;
1246     argv.push_back(runtime->NewString(uri.ToString()));
1247     auto func = GetPaFunc("normalizeUri");
1248     shared_ptr<JsValue> retVal = CallAsyncFunc(func, argv, callingInfo);
1249 
1250     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1251     if (arkJSRuntime->HasPendingException()) {
1252         LOGE("JsiPaEngine NormalizeUri FAILED!");
1253         return Uri("");
1254     }
1255     auto arkJSValue = std::static_pointer_cast<ArkJSValue>(retVal);
1256     return Uri(arkJSValue->ToString(runtime));
1257 }
1258 
DenormalizeUri(const Uri & uri,const CallingInfo & callingInfo)1259 Uri JsiPaEngine::DenormalizeUri(const Uri& uri, const CallingInfo& callingInfo)
1260 {
1261     LOGI("JsiPaEngine DenormalizeUri");
1262     shared_ptr<JsRuntime> runtime = GetJsRuntime();
1263     std::vector<shared_ptr<JsValue>> argv;
1264     argv.push_back(runtime->NewString(uri.ToString()));
1265     auto func = GetPaFunc("denormalizeUri");
1266     shared_ptr<JsValue> retVal = CallAsyncFunc(func, argv, callingInfo);
1267 
1268     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1269     if (arkJSRuntime->HasPendingException()) {
1270         LOGE("JsiPaEngine DenormalizeUri FAILED!");
1271         return Uri("");
1272     }
1273     auto arkJSValue = std::static_pointer_cast<ArkJSValue>(retVal);
1274     return Uri(arkJSValue->ToString(runtime));
1275 }
1276 
OnConnectService(const OHOS::AAFwk::Want & want)1277 sptr<IRemoteObject> JsiPaEngine::OnConnectService(const OHOS::AAFwk::Want& want)
1278 {
1279     ContainerScope scope(instanceId_);
1280     LOGI("JsiPaEngine OnConnectService");
1281     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(GetJsRuntime());
1282     const std::vector<shared_ptr<JsValue>>& argv = { WantToJsValue(want) };
1283     auto func = GetPaFunc("onConnect");
1284     shared_ptr<JsValue> retVal = CallFunc(func, argv);
1285 
1286     if (arkJSRuntime->HasPendingException()) {
1287         LOGE("JsiPaEngine onConnectService FAILED!");
1288         return nullptr;
1289     }
1290 
1291     auto nativeEngine = GetNativeEngine();
1292     CHECK_NULL_RETURN(nativeEngine, nullptr);
1293     napi_env env = reinterpret_cast<napi_env>(nativeEngine);
1294     auto arkJSValue = std::static_pointer_cast<ArkJSValue>(retVal);
1295     napi_value nativeValue = ArkNativeEngine::ArkValueToNapiValue(env, arkJSValue->GetValue(arkJSRuntime));
1296     if (nativeValue == nullptr) {
1297         LOGE("JsiPaEngine nativeValue is nullptr");
1298         return nullptr;
1299     }
1300     auto remoteObj = NAPI_ohos_rpc_getNativeRemoteObject(env, nativeValue);
1301     return remoteObj;
1302 }
1303 
OnDisconnectService(const OHOS::AAFwk::Want & want)1304 void JsiPaEngine::OnDisconnectService(const OHOS::AAFwk::Want& want)
1305 {
1306     ContainerScope scope(instanceId_);
1307     LOGI("JsiPaEngine OnDisconnectService");
1308     const std::vector<shared_ptr<JsValue>>& argv = { WantToJsValue(want) };
1309     auto func = GetPaFunc("onDisconnect");
1310     CallFunc(func, argv);
1311 }
1312 
OnCommand(const OHOS::AAFwk::Want & want,int startId)1313 void JsiPaEngine::OnCommand(const OHOS::AAFwk::Want& want, int startId)
1314 {
1315     ContainerScope scope(instanceId_);
1316     LOGI("JsiPaEngine OnCommand");
1317     shared_ptr<JsRuntime> runtime = GetJsRuntime();
1318     const std::vector<shared_ptr<JsValue>>& argv = { WantToJsValue(want), runtime->NewInt32(startId) };
1319     auto func = GetPaFunc("onCommand");
1320     CallFunc(func, argv);
1321 }
1322 
OnCreate(const OHOS::AAFwk::Want & want)1323 void JsiPaEngine::OnCreate(const OHOS::AAFwk::Want& want)
1324 {
1325     ContainerScope scope(instanceId_);
1326     shared_ptr<JsRuntime> runtime = GetJsRuntime();
1327 
1328     const std::vector<shared_ptr<JsValue>>& argv = { WantToJsValue(want) };
1329     auto func = GetPaFunc("onCreate");
1330     auto result = CallFuncWithDefaultThis(func, argv);
1331     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1332     if (arkJSRuntime->HasPendingException() || result->IsUndefined(runtime)) {
1333         LOGE("JsiPaEngine CallFunc FAILED!");
1334         return;
1335     }
1336 
1337     auto arkJSValue = std::static_pointer_cast<ArkJSValue>(result);
1338     shared_ptr<JsValue> propertyNames;
1339     int32_t len = 0;
1340     if (!arkJSValue->GetPropertyNames(runtime, propertyNames, len)) {
1341         LOGE("JsiPaEngine StartForm GetPropertyNames error");
1342         return;
1343     }
1344     LOGI("JsiPaEngine onCreate return property num %{public}d", len);
1345 
1346     std::string jsonStr;
1347     shared_ptr<JsValue> formJsonData = arkJSValue->GetProperty(runtime, "data");
1348     if (formJsonData != nullptr) {
1349         jsonStr = formJsonData->ToString(runtime);
1350         LOGI("Add FormBindingData json:%{public}s", jsonStr.c_str());
1351     }
1352     AppExecFwk::FormProviderData formData = AppExecFwk::FormProviderData(jsonStr);
1353     shared_ptr<JsValue> formImageData = arkJSValue->GetProperty(runtime, "image");
1354     if (formImageData != nullptr) {
1355         std::map<std::string, int> rawImageDataMap;
1356         auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1357         auto nativeEngine = GetNativeEngine();
1358         CHECK_NULL_VOID(nativeEngine);
1359         napi_env env = reinterpret_cast<napi_env>(nativeEngine);
1360         napi_value napiValue = ArkNativeEngine::ArkValueToNapiValue(
1361             env, std::static_pointer_cast<ArkJSValue>(formImageData)->GetValue(arkJSRuntime));
1362         UnwrapRawImageDataMap(env, napiValue, rawImageDataMap);
1363         for (const auto& data : rawImageDataMap) {
1364             formData.AddImageData(data.first, data.second);
1365         }
1366     }
1367     SetFormData(formData);
1368 }
1369 
OnDelete(const int64_t formId)1370 void JsiPaEngine::OnDelete(const int64_t formId)
1371 {
1372     LOGI("JsiPaEngine OnDelete");
1373     shared_ptr<JsRuntime> runtime = GetJsRuntime();
1374     const std::vector<shared_ptr<JsValue>>& argv = { runtime->NewString(std::to_string(formId)) };
1375     auto func = GetPaFunc("onDestroy");
1376     CallFuncWithDefaultThis(func, argv);
1377 }
1378 
OnTriggerEvent(const int64_t formId,const std::string & message)1379 void JsiPaEngine::OnTriggerEvent(const int64_t formId, const std::string& message)
1380 {
1381     LOGI("JsiPaEngine OnTriggerEvent");
1382     shared_ptr<JsRuntime> runtime = GetJsRuntime();
1383     const std::vector<shared_ptr<JsValue>>& argv = { runtime->NewString(std::to_string(formId)),
1384         runtime->NewString(message) };
1385     auto func = GetPaFunc("onEvent");
1386     CallFuncWithDefaultThis(func, argv);
1387 }
1388 
OnUpdate(const int64_t formId)1389 void JsiPaEngine::OnUpdate(const int64_t formId)
1390 {
1391     LOGI("JsiPaEngine OnUpdate");
1392     shared_ptr<JsRuntime> runtime = GetJsRuntime();
1393     const std::vector<shared_ptr<JsValue>>& argv = { runtime->NewString(std::to_string(formId)) };
1394     auto func = GetPaFunc("onUpdate");
1395     CallFuncWithDefaultThis(func, argv);
1396 }
1397 
OnCastTemptoNormal(const int64_t formId)1398 void JsiPaEngine::OnCastTemptoNormal(const int64_t formId)
1399 {
1400     shared_ptr<JsRuntime> runtime = GetJsRuntime();
1401     const std::vector<shared_ptr<JsValue>>& argv = { runtime->NewString(std::to_string(formId)) };
1402     auto func = GetPaFunc("onCastToNormal");
1403     CallFuncWithDefaultThis(func, argv);
1404 }
1405 
OnVisibilityChanged(const std::map<int64_t,int32_t> & formEventsMap)1406 void JsiPaEngine::OnVisibilityChanged(const std::map<int64_t, int32_t>& formEventsMap)
1407 {
1408     std::string strJsonResult("{");
1409     for (auto item = formEventsMap.begin(); item != formEventsMap.end(); item++) {
1410         strJsonResult.append(ToJSONStringInt(std::to_string(item->first), std::to_string(item->second)));
1411         strJsonResult.append(",");
1412     }
1413     strJsonResult = strJsonResult.substr(0, strJsonResult.size() - 1);
1414     strJsonResult.append("}");
1415     LOGI("JsiPaEngine strJsonResult = %{public}s", strJsonResult.c_str());
1416 
1417     shared_ptr<JsRuntime> runtime = GetJsRuntime();
1418     const std::vector<shared_ptr<JsValue>>& argv = { runtime->ParseJson(strJsonResult) };
1419     auto func = GetPaFunc("onVisibilityChange");
1420     CallFuncWithDefaultThis(func, argv);
1421 }
1422 
OnAcquireFormState(const OHOS::AAFwk::Want & want)1423 int32_t JsiPaEngine::OnAcquireFormState(const OHOS::AAFwk::Want& want)
1424 {
1425     shared_ptr<JsRuntime> runtime = GetJsRuntime();
1426     const std::vector<shared_ptr<JsValue>>& argv = { WantToJsValue(want) };
1427     auto func = GetPaFunc("onAcquireFormState");
1428     if (func == nullptr) {
1429         LOGW("no OnAcquireFormState!");
1430         return (int32_t)AppExecFwk::FormState::DEFAULT;
1431     }
1432 
1433     auto result = CallFuncWithDefaultThis(func, argv);
1434     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1435     if (arkJSRuntime->HasPendingException()) {
1436         LOGE("JsiPaEngine CallFunc FAILED!");
1437         return (int32_t)AppExecFwk::FormState::DEFAULT;
1438     }
1439 
1440     auto arkJSValue = std::static_pointer_cast<ArkJSValue>(result);
1441     if (!arkJSValue->IsInt32(runtime)) {
1442         LOGE("invalid return value!");
1443         return (int32_t)AppExecFwk::FormState::DEFAULT;
1444     }
1445 
1446     int32_t formState = arkJSValue->ToInt32(runtime);
1447     LOGI("JsiPaEngine OnAcquireFormState, formState: %{public}d", formState);
1448     return formState;
1449 }
1450 
OnShare(int64_t formId,OHOS::AAFwk::WantParams & wantParams)1451 bool JsiPaEngine::OnShare(int64_t formId, OHOS::AAFwk::WantParams& wantParams)
1452 {
1453     auto runtime = GetJsRuntime();
1454     if (runtime == nullptr) {
1455         LOGE("JsiPaEngine JsRuntime Get nullptr!");
1456         return false;
1457     }
1458 
1459     const std::vector<shared_ptr<JsValue>> argv = { runtime->NewString(std::to_string(formId)) };
1460     auto func = GetPaFunc("onShareForm");
1461     if (func == nullptr) {
1462         func = GetPaFunc("onShare");
1463     }
1464     auto result = CallFuncWithDefaultThis(func, argv);
1465     if (result == nullptr) {
1466         LOGE("JsiPaEngine Call function result is nullptr!");
1467         return false;
1468     }
1469 
1470     auto arkJSValue = std::static_pointer_cast<ArkJSValue>(result);
1471     if (arkJSValue == nullptr) {
1472         LOGE("JsiPaEngine JsValue convert failed!");
1473         return false;
1474     }
1475 
1476     auto arkJSRuntime = std::static_pointer_cast<ArkJSRuntime>(runtime);
1477     if (arkJSRuntime == nullptr) {
1478         LOGE("JsiPaEngine JSRuntime convert failed!");
1479         return false;
1480     }
1481 
1482     if (arkJSRuntime->HasPendingException()) {
1483         LOGE("JsiPaEngine CallFunc FAILED!");
1484         return false;
1485     }
1486 
1487     auto nativeEngine = GetNativeEngine();
1488     CHECK_NULL_RETURN(nativeEngine, false);
1489     napi_env env = reinterpret_cast<napi_env>(nativeEngine);
1490     auto napiValue = ArkNativeEngine::ArkValueToNapiValue(env, arkJSValue->GetValue(arkJSRuntime));
1491     if (napiValue == nullptr) {
1492         LOGE("JsiPaEngine nativeValue convert failed!");
1493         return false;
1494     }
1495     napi_valuetype valueType = napi_undefined;
1496     napi_typeof(env, napiValue, &valueType);
1497     if (valueType != napi_object) {
1498         LOGE("napiValue is not napiObject");
1499         return false;
1500     }
1501 
1502     if (!OHOS::AppExecFwk::UnwrapWantParams(env, napiValue, wantParams)) {
1503         LOGE("%{public}s OnShare UnwrapWantParams failed, return false", __func__);
1504         return false;
1505     }
1506     return true;
1507 }
1508 
PostTask(const std::function<void ()> & task,const std::string & name,int64_t delayTime)1509 void JsiPaEngine::PostTask(const std::function<void()>& task, const std::string& name, int64_t delayTime)
1510 {
1511     if (!jsAbilityRuntime_) {
1512         LOGE("Ability runtime is invalid.");
1513         return;
1514     }
1515 
1516     jsAbilityRuntime_->PostTask(task, name, delayTime);
1517 }
1518 
PostSyncTask(const std::function<void ()> & task,const std::string & name)1519 void JsiPaEngine::PostSyncTask(const std::function<void()>& task, const std::string& name)
1520 {
1521     if (!jsAbilityRuntime_) {
1522         LOGE("Ability runtime is invalid.");
1523         return;
1524     }
1525 
1526     jsAbilityRuntime_->PostSyncTask(task, name);
1527 }
1528 
RemoveTask(const std::string & name)1529 void JsiPaEngine::RemoveTask(const std::string& name)
1530 {
1531     if (!jsAbilityRuntime_) {
1532         LOGE("Ability runtime is invalid.");
1533         return;
1534     }
1535 
1536     jsAbilityRuntime_->RemoveTask(name);
1537 }
1538 } // namespace OHOS::Ace
1539