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