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