From d1c2b856030726b8969749779537d32c230ab028 Mon Sep 17 00:00:00 2001 From: xieyijun3 Date: Tue, 1 Aug 2023 17:43:15 +0800 Subject: [PATCH 1/2] build js engine Signed-off-by: x30034819 Signed-off-by: xieyijun3 --- .gitignore | 2 +- ace_engine/adapter/fangtian/build/BUILD.gn | 26 - ace_engine/adapter/fangtian/build/config.gni | 167 -- .../adapter/fangtian/build/hisysevent.yaml | 155 -- .../adapter/fangtian/entrance/ace_ability.cpp | 4 +- .../fangtian/entrance/ace_container.cpp | 112 +- .../adapter/fangtian/entrance/ace_container.h | 16 - .../fangtian/entrance/pa_engine/BUILD.gn | 79 - .../entrance/pa_engine/backend_delegate.h | 77 - .../pa_engine/backend_delegate_impl.cpp | 594 ------ .../pa_engine/backend_delegate_impl.h | 267 --- .../engine/common/js_backend_engine.h | 151 -- .../common/js_backend_engine_loader.cpp | 79 - .../engine/common/js_backend_engine_loader.h | 34 - .../engine/common/js_backend_timer_module.cpp | 248 --- .../engine/common/js_backend_timer_module.h | 61 - .../entrance/pa_engine/engine/jsi/BUILD.gn | 137 -- .../pa_engine/engine/jsi/jsi_pa_engine.cpp | 1570 ---------------- .../pa_engine/engine/jsi/jsi_pa_engine.h | 223 --- .../engine/jsi/jsi_pa_engine_loader.cpp | 43 - .../engine/jsi/jsi_pa_engine_loader.h | 32 - .../pa_engine/engine/jsi/jsi_pa_utils.cpp | 29 - .../entrance/pa_engine/engine/jsi/paMgmt.js | 39 - .../pa_engine/engine/quickjs/BUILD.gn | 140 -- .../pa_engine/engine/quickjs/BUILD.gn.bak | 140 -- .../engine/quickjs/qjs_pa_engine.cpp | 1590 ----------------- .../pa_engine/engine/quickjs/qjs_pa_engine.h | 231 --- .../engine/quickjs/qjs_pa_engine_loader.cpp | 43 - .../engine/quickjs/qjs_pa_engine_loader.h | 32 - .../entrance/pa_engine/pa_backend.cpp | 490 ----- .../fangtian/entrance/pa_engine/pa_backend.h | 132 -- .../adapter/fangtian/ft_build/config.gni | 5 +- ace_engine/adapter/preview/ft_build/BUILD.gn | 38 - .../adapter/preview/ft_build/config.gni | 23 - .../adapter/preview/ft_build/config_linux.gni | 24 - .../adapter/preview/ft_build/config_mac.gni | 23 - .../preview/ft_build/config_windows.gni | 35 - .../adapter/preview/ft_build/platform.gni | 50 - .../preview/ft_build/preview_common.gni | 100 -- .../engine/declarative_engine_loader.cpp | 2 +- .../engine/jsi/ft_build/BUILD.gn | 172 ++ .../declarative_frontend/ft_build/BUILD.gn | 243 ++- .../jsview/js_canvas_renderer.h | 2 +- .../js_frontend/engine/common/js_engine.cpp | 12 +- .../js_frontend/engine/ft_build}/BUILD.gn | 59 +- .../js_frontend/engine/jsi/ft_build/BUILD.gn | 136 ++ .../core/components/qrcode/ft_build/BUILD.gn | 56 + .../components_ng/pattern/ft_build/BUILD.gn | 7 + .../pattern/qrcode/ft_build/BUILD.gn} | 25 +- .../components_ng/property/ft_build/BUILD.gn | 1 + ace_engine/frameworks/core/ft_build/BUILD.gn | 5 +- ace_engine/ft_build/BUILD.gn | 4 + ace_engine/ft_build/ace_config.gni | 2 +- ace_engine/ft_build/build/ace_lib.gni | 14 +- .../ft_build/ets_frontend_config.gni | 35 + .../ts2panda/ft_build/ts2abc_config.gni | 236 +++ build/configs/system_deps.toml | 1 + 57 files changed, 975 insertions(+), 7278 deletions(-) delete mode 100644 ace_engine/adapter/fangtian/build/BUILD.gn delete mode 100644 ace_engine/adapter/fangtian/build/config.gni delete mode 100644 ace_engine/adapter/fangtian/build/hisysevent.yaml delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/BUILD.gn delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/backend_delegate.h delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/backend_delegate_impl.cpp delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/backend_delegate_impl.h delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/engine/common/js_backend_engine.h delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/engine/common/js_backend_engine_loader.cpp delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/engine/common/js_backend_engine_loader.h delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/engine/common/js_backend_timer_module.cpp delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/engine/common/js_backend_timer_module.h delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/BUILD.gn delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/jsi_pa_engine.cpp delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/jsi_pa_engine.h delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/jsi_pa_engine_loader.cpp delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/jsi_pa_engine_loader.h delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/jsi_pa_utils.cpp delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/paMgmt.js delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/BUILD.gn delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/BUILD.gn.bak delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/qjs_pa_engine.cpp delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/qjs_pa_engine.h delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/qjs_pa_engine_loader.cpp delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/qjs_pa_engine_loader.h delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/pa_backend.cpp delete mode 100644 ace_engine/adapter/fangtian/entrance/pa_engine/pa_backend.h delete mode 100644 ace_engine/adapter/preview/ft_build/BUILD.gn delete mode 100644 ace_engine/adapter/preview/ft_build/config.gni delete mode 100644 ace_engine/adapter/preview/ft_build/config_linux.gni delete mode 100644 ace_engine/adapter/preview/ft_build/config_mac.gni delete mode 100644 ace_engine/adapter/preview/ft_build/config_windows.gni delete mode 100644 ace_engine/adapter/preview/ft_build/platform.gni delete mode 100644 ace_engine/adapter/preview/ft_build/preview_common.gni create mode 100644 ace_engine/frameworks/bridge/declarative_frontend/engine/jsi/ft_build/BUILD.gn rename ace_engine/{adapter/fangtian/entrance/pa_engine/engine => frameworks/bridge/js_frontend/engine/ft_build}/BUILD.gn (55%) create mode 100644 ace_engine/frameworks/bridge/js_frontend/engine/jsi/ft_build/BUILD.gn create mode 100644 ace_engine/frameworks/core/components/qrcode/ft_build/BUILD.gn rename ace_engine/{adapter/fangtian/build/platform.gni => frameworks/core/components_ng/pattern/qrcode/ft_build/BUILD.gn} (57%) create mode 100644 arkcompiler/ets_frontend/ft_build/ets_frontend_config.gni create mode 100755 arkcompiler/ets_frontend/ts2panda/ft_build/ts2abc_config.gni diff --git a/.gitignore b/.gitignore index 64ddc8814..b427458f7 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,4 @@ out/ prebuilts/ **/__pycache__ third_party/ft_engine -third_party/ft_flutter +third_party/flutter diff --git a/ace_engine/adapter/fangtian/build/BUILD.gn b/ace_engine/adapter/fangtian/build/BUILD.gn deleted file mode 100644 index 10212072f..000000000 --- a/ace_engine/adapter/fangtian/build/BUILD.gn +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -#import("//build/ohos.gni") -import("//build/gn/fangtian.gni") -import("//foundation/arkui/ace_engine/ace_config.gni") - -ft_shared_library("libace_engine") { - platform = "fangtian" - deps = [ - "$ace_root/build:libace_static_${platform}", - "$ace_flutter_engine_root/fangtian/glfw:flutter_glfw_$platform", -#"//base/hiviewdfx/hitrace/interfaces/native/innerkits:hitrace_meter", - ] -} - diff --git a/ace_engine/adapter/fangtian/build/config.gni b/ace_engine/adapter/fangtian/build/config.gni deleted file mode 100644 index 8796b1f7b..000000000 --- a/ace_engine/adapter/fangtian/build/config.gni +++ /dev/null @@ -1,167 +0,0 @@ -# Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -#import("//build/ohos/ace/ace_args.gni") -import("//build/gn/fangtian.gni") -import("//foundation/graphic/graphic_2d/graphic_config.gni") - -defines = [ - "LINUX_PLATFORM", - "UNICODE", - "GPU_DISABLED", - "SK_BUILD_FONT_MGR_FOR_PREVIEW_LINUX", -] - -js_engines = [] -ark_engine = { - engine_name = "ark" - engine_path = "jsi" - engine_defines = [ "USE_ARK_ENGINE" ] -} -js_engines += [ ark_engine ] - -if (ace_enable_gpu) { - disable_gpu = false -} else { - disable_gpu = true -} - -declare_args() { - ace_engine_feature_enable_accessibility = false - ace_engine_feature_enable_web = false -} - -if (ace_engine_feature_enable_accessibility) { - accessibility_support = true -} - -if (ace_engine_feature_enable_web) { - web_components_support = false -} - -is_experiment_build = false -use_build_in_js_engine = false -use_external_icu = "shared" -use_curl_download = true -ohos_standard_fontmgr = false -sk_use_hilog = false -rich_components_support = true -advance_components_support = false -form_components_support = false -remote_window_support = false -plugin_components_support = false -xcomponent_components_support = false -pixel_map_support = true -js_pa_support = false -connect_server_support = true -hdc_register_support = false -pa_engine_path = "adapter/linux/entrance/pa_engine" -enable_rosen_backend = false -enable_standard_input = false -build_container_scope_lib = false -multiple_window_support = false -enable_ability_component = false -video_components_support = false -image_components_support = false -preview_support = true -enable_system_clipboard = false -enable_image_compression = false - -if (defined(preview_support) && preview_support) { - defines += [ "PREVIEW" ] -} - -if (defined(image_components_support) && image_components_support) { - defines += [ "IMAGE_SUPPORTED" ] -} - -if (defined(video_components_support) && video_components_support) { - defines += [ "VIDEO_SUPPORTED" ] -} - -if (defined(is_experiment_build) && is_experiment_build) { - web_components_support = true - accessibility_support = true -} - -if (defined(web_components_support) && web_components_support) { - defines += [ "WEB_SUPPORTED" ] -} - -if (defined(enable_ability_component) && enable_ability_component) { - defines += [ "ABILITY_COMPONENT_SUPPORTED" ] -} - -if (disable_gpu || enable_rosen_backend) { - defines += [ "GPU_DISABLED" ] -} - -if (disable_gpu) { - defines += [ "UPLOAD_GPU_DISABLED" ] -} - -if (form_components_support) { - defines += [ "FORM_SUPPORTED" ] -} - -if (form_components_support) { - defines += [ "REMOTE_WINDOW_SUPPORTED" ] -} - -if (xcomponent_components_support) { - defines += [ "XCOMPONENT_SUPPORTED" ] -} - -if (plugin_components_support) { - defines += [ "PLUGIN_COMPONENT_SUPPORTED" ] -} - -if (pixel_map_support) { - defines += [ "PIXEL_MAP_SUPPORTED" ] -} - -if (enable_rosen_backend) { -#defines += [ "ENABLE_ROSEN_BACKEND" ] -} - -if (enable_standard_input) { - defines += [ "ENABLE_STANDARD_INPUT" ] -} - -if (multiple_window_support) { - defines += [ "MULTIPLE_WINDOW_SUPPORTED" ] -} - -if (use_build_in_js_engine) { - defines += [ "HIDDEN_SYMBOL" ] -} - -cflags_cc = [ - "-Wno-thread-safety-attributes", - "-Wno-thread-safety-analysis", -] -if (is_fangtian_build) { - platform_deps = [ - "//foundation/arkui/ace_engine/adapter/fangtian/entrance:ace_entrance_fangtian", - "//foundation/arkui/ace_engine/adapter/fangtian/external:external_source_fangtian", - "//foundation/arkui/ace_engine/adapter/fangtian/inspector:ace_inspector_fangtian", - "//foundation/arkui/ace_engine/adapter/fangtian/osal:ace_osal_fangtian", - ] -} else { - platform_deps = [ - "//foundation/arkui/ace_engine/adapter/linux/entrance:ace_ohos_standard_entrance", - "//foundation/arkui/ace_engine/adapter/linux/osal:ace_osal_ohos", - ] -} - -libace_target = "//foundation/arkui/ace_engine/adapter/fangtian/build:libace_engine" diff --git a/ace_engine/adapter/fangtian/build/hisysevent.yaml b/ace_engine/adapter/fangtian/build/hisysevent.yaml deleted file mode 100644 index 25a0b0378..000000000 --- a/ace_engine/adapter/fangtian/build/hisysevent.yaml +++ /dev/null @@ -1,155 +0,0 @@ -# Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -##################################################### -# below is the format of defining event # -##################################################### -#domain: domain name. [Only one domain name can be defined at the top] -# -#author: the author name who defined this event. -#date: the date when this event was defined, format is YYYY-MM-DD. -#logged: source file which refer to this event. -#usage: the usage of this event. -#//Define event name and event properties. -#@EVENT_NAME: the event definition part begin. -# // __BASE is used for defining the basic info of the event. -# // "type" optional values are: FAULT, STATISTICS, SECURITY, BEHAVIOR. -# // "level" optional values are: CRITICAL, MINOR. -# // "tag" set tags with may used by subscriber of this event, multiple tags divided by space. -# // "desc" full description of this event. -# @PARAMETER: {type: parameter type, arrsize: array length(optional), desc: parameter description}. -# // follow the __BASE block, each line defines a parameter of this event. -# // "type" optional values are: INT8, UINT8, INT16, UINT16, INT32, UINT32, INT64, UINT64, FLOAT, DOUBLE, STRING. -# // "arrsize" of the parameter is an array, set a non-zero value. -# // "desc" full description of this parameter. - -##################################################### -# Example of some hiviewdfx events definition # -##################################################### - -domain: ACE - -JS_CARD_FIRST_RENDER_TIME: - __BASE: {type: STATISTIC, level: MINOR, desc: js card first render duration} - SESSION_ID: {type: STRING, desc: session id} - DURATION: {type: UINT64, desc: duration from js card created to first render} - -JS_CARD_FIRST_UPDATE_TIME: - __BASE: {type: STATISTIC, level: MINOR, desc: js card first update duration} - SESSION_ID: {type: STRING, desc: session id} - DURATION: {type: UINT64, desc: duration from js card first update to render} - -FRAMEWORK_APP_START_EXCEPTION: - __BASE: { type: FAULT, level: MINOR, desc: application start exception } - ERROR_TYPE: { type: INT32, desc: error type } - PACKAGE_NAME: { type: STRING, desc: package name } - -FRAMEWORK_PAGE_ROUTER_EXCEPTION: - __BASE: { type: FAULT, level: MINOR, desc: page router exception } - ERROR_TYPE: { type: INT32, desc: error type } - PACKAGE_NAME: { type: STRING, desc: package name } - PAGE_NAME: { type: STRING, desc: page name } - -COMPONENT_EXCEPTION: - __BASE: { type: FAULT, level: MINOR, desc: component exception } - ERROR_TYPE: { type: INT32, desc: error type } - PACKAGE_NAME: { type: STRING, desc: package name } - -API_CHANNEL_EXCEPTION: - __BASE: { type: FAULT, level: MINOR, desc: API channel exception } - ERROR_TYPE: { type: INT32, desc: error type } - PACKAGE_NAME: { type: STRING, desc: package name } - -RENDER_EXCEPTION: - __BASE: { type: FAULT, level: MINOR, desc: render exception } - ERROR_TYPE: { type: INT32, desc: error type } - PACKAGE_NAME: { type: STRING, desc: package name } - RENDER_OBJECT_NAME: { type: STRING, desc: render object name } - -JS_EXCEPTION: - __BASE: { type: FAULT, level: MINOR, desc: JS exception } - ERROR_TYPE: { type: INT32, desc: error type } - PACKAGE_NAME: { type: STRING, desc: package name } - -ANIMATION_EXCEPTION: - __BASE: { type: FAULT, level: MINOR, desc: animation exception } - ERROR_TYPE: { type: INT32, desc: error type } - PACKAGE_NAME: { type: STRING, desc: package name } - -EVENT_EXCEPTION: - __BASE: { type: FAULT, level: MINOR, desc: event exception } - ERROR_TYPE: { type: INT32, desc: error type } - PACKAGE_NAME: { type: STRING, desc: package name } - -PLUGIN_EXCEPTION: - __BASE: { type: FAULT, level: MINOR, desc: plugin exception } - ERROR_TYPE: { type: INT32, desc: error type } - PACKAGE_NAME: { type: STRING, desc: package name } - -INTERNATIONALIZATION_EXCEPTION: - __BASE: { type: FAULT, level: MINOR, desc: internationalization exception } - ERROR_TYPE: { type: INT32, desc: error type } - PACKAGE_NAME: { type: STRING, desc: package name } - -ACCESSIBILITY_EXCEPTION: - __BASE: { type: FAULT, level: MINOR, desc: accessibility exception } - ERROR_TYPE: { type: INT32, desc: error type } - PACKAGE_NAME: { type: STRING, desc: package name } - -FORM_EXCEPTION: - __BASE: { type: FAULT, level: MINOR, desc: form exception } - ERROR_TYPE: { type: INT32, desc: error type } - PACKAGE_NAME: { type: STRING, desc: package name } - -JS_ERROR: - __BASE: { type: FAULT, level: MINOR, desc: JS runtime exception } - PACKAGE_NAME: { type: STRING, desc: package name } - REASON: { type: STRING, desc: js runtime error reason } - SUMMARY: { type: STRING, desc: js runtime error summary } - FINGERPRINT: {type: STRING, desc: unique id for grouping same fault} - PANME: {type: STRING, desc: process name} - FIRST_FRAME: {type: STRING, desc: first stack info} - SECOND_FRAME: {type: STRING, desc: second stack info} - LAST_FRAME: {type: STRING, desc: last stack info} - -UI_BLOCK_3S: - __BASE: {type: FAULT, level: CRITICAL, desc: The thread is blocked for 3s } - UID: {type: INT32, desc: application uid} - PACKAGE_NAME: {type: STRING, desc: application package name} - PROCESS_NAME: {type: STRING, desc: application process name} - MSG: {type: STRING, desc: application event message} - CMD: {type: STRING, desc: application event cmd} - -UI_BLOCK_6S: - __BASE: {type: FAULT, level: CRITICAL, desc: The thread is blocked for 6s } - UID: {type: INT32, desc: application uid} - PACKAGE_NAME: {type: STRING, desc: application package name} - PROCESS_NAME: {type: STRING, desc: application process name} - MSG: {type: STRING, desc: application event message} - CMD: {type: STRING, desc: application event cmd} - -UI_BLOCK_RECOVERED: - __BASE: {type: FAULT, level: CRITICAL, desc: The thread is recovered } - UID: {type: INT32, desc: application uid} - PACKAGE_NAME: {type: STRING, desc: application package name} - PROCESS_NAME: {type: STRING, desc: application process name} - MSG: {type: STRING, desc: application event message} - CMD: {type: STRING, desc: application event cmd} - -UI_BLOCK_DIALOG: - __BASE: {type: FAULT, level: CRITICAL, desc: Dialog is displayed when the thread is blocked } - PID: {type: INT32, desc: application pid} - UID: {type: INT32, desc: application uid} - PACKAGE_NAME: {type: STRING, desc: application package name} - PROCESS_NAME: {type: STRING, desc: application process name} - MSG: {type: STRING, desc: application event message} \ No newline at end of file diff --git a/ace_engine/adapter/fangtian/entrance/ace_ability.cpp b/ace_engine/adapter/fangtian/entrance/ace_ability.cpp index ef02b9101..da48a0895 100644 --- a/ace_engine/adapter/fangtian/entrance/ace_ability.cpp +++ b/ace_engine/adapter/fangtian/entrance/ace_ability.cpp @@ -196,7 +196,9 @@ std::unique_ptr AceAbility::CreateInstance(AceRunArgs& runArgs) controller->CreateWindow(runArgs.viewWidth, runArgs.viewHeight, true); - // EventDispatcher::GetInstance().SetGlfwWindowController(controller); + //auto controller = FlutterDesktopCreateWindow( + // runArgs.deviceWidth, runArgs.deviceHeight, runArgs.windowTitle.c_str(), runArgs.onRender); + //EventDispatcher::GetInstance().SetGlfwWindowController(controller); EventDispatcher::GetInstance().Initialize(); auto aceAbility = std::make_unique(runArgs); // aceAbility->SetGlfwWindowController(controller); diff --git a/ace_engine/adapter/fangtian/entrance/ace_container.cpp b/ace_engine/adapter/fangtian/entrance/ace_container.cpp index e3d84ceb0..4de570c1c 100644 --- a/ace_engine/adapter/fangtian/entrance/ace_container.cpp +++ b/ace_engine/adapter/fangtian/entrance/ace_container.cpp @@ -77,12 +77,15 @@ AceContainer::AceContainer(int32_t instanceId, FrontendType type, RefPtrGetStateById(instanceId); - auto taskExecutor = Referenced::MakeRefPtr(state->GetTaskRunners()); - if (type_ != FrontendType::DECLARATIVE_JS && type_ != FrontendType::ETS_CARD) { - taskExecutor->InitJsThread(); - } - taskExecutor_ = taskExecutor; */ + //auto state = flutter::UIDartState::Current()->GetStateById(instanceId); + //auto taskExecutor = Referenced::MakeRefPtr(state->GetTaskRunners()); + //if (type_ != FrontendType::DECLARATIVE_JS && type_ != FrontendType::ETS_CARD) { + // taskExecutor->InitJsThread(); + //} + + auto taskExecutor = Referenced::MakeRefPtr(); + taskExecutor->InitPlatformThread(false); + taskExecutor_ = taskExecutor; } void AceContainer::Initialize() @@ -790,94 +793,9 @@ void AceContainer::SetView(RSAceView* view, double density, int32_t width, int32 //auto rsWindow = new Rosen::Window(onRender); //auto window = std::make_unique(rsWindow, taskExecutor, view->GetInstanceId()); //container->AttachView(std::move(window), view, density, width, height, onRender); + container->AttachView(nullptr, view, density, width, height, onRender); } -#ifndef ENABLE_ROSEN_BACKEND -void AceContainer::AttachView( - std::unique_ptr window, FlutterAceView* view, double density, int32_t width, int32_t height) -{ - ContainerScope scope(instanceId_); - aceView_ = view; - auto instanceId = aceView_->GetInstanceId(); - - auto state = flutter::UIDartState::Current()->GetStateById(instanceId); - ACE_DCHECK(state != nullptr); - auto flutterTaskExecutor = AceType::DynamicCast(taskExecutor_); - flutterTaskExecutor->InitOtherThreads(state->GetTaskRunners()); - if (type_ == FrontendType::DECLARATIVE_JS) { - // For DECLARATIVE_JS frontend display UI in JS thread temporarily. - flutterTaskExecutor->InitJsThread(false); - InitializeFrontend(); - auto front = GetFrontend(); - if (front) { - front->UpdateState(Frontend::State::ON_CREATE); - front->SetJsMessageDispatcher(AceType::Claim(this)); - } - } - resRegister_ = aceView_->GetPlatformResRegister(); - auto pipelineContext = AceType::MakeRefPtr( - std::move(window), taskExecutor_, assetManager_, resRegister_, frontend_, instanceId); - pipelineContext->SetRootSize(density, width, height); - pipelineContext->SetTextFieldManager(AceType::MakeRefPtr()); - pipelineContext->SetIsRightToLeft(AceApplicationInfo::GetInstance().IsRightToLeft()); - pipelineContext->SetMessageBridge(messageBridge_); - pipelineContext->SetWindowModal(windowModal_); - pipelineContext->SetDrawDelegate(aceView_->GetDrawDelegate()); - pipelineContext->SetIsJsCard(type_ == FrontendType::JS_CARD); - pipelineContext_ = pipelineContext; - InitializeCallback(); - - ThemeConstants::InitDeviceType(); - // Only init global resource here, construct theme in UI thread - auto themeManager = AceType::MakeRefPtr(); - if (themeManager) { - pipelineContext_->SetThemeManager(themeManager); - // Init resource, load theme map. - themeManager->InitResource(resourceInfo_); - themeManager->LoadSystemTheme(resourceInfo_.GetThemeId()); - taskExecutor_->PostTask( - [themeManager, assetManager = assetManager_, colorScheme = colorScheme_, aceView = aceView_]() { - themeManager->ParseSystemTheme(); - themeManager->SetColorScheme(colorScheme); - themeManager->LoadCustomTheme(assetManager); - // get background color from theme - aceView->SetBackgroundColor(themeManager->GetBackgroundColor()); - }, - TaskExecutor::TaskType::UI); - } - - auto weak = AceType::WeakClaim(AceType::RawPtr(pipelineContext_)); - taskExecutor_->PostTask( - [weak]() { - auto context = weak.Upgrade(); - if (context == nullptr) { - LOGE("context is nullptr"); - return; - } - context->SetupRootElement(); - }, - TaskExecutor::TaskType::UI); - aceView_->Launch(); - - frontend_->AttachPipelineContext(pipelineContext_); - auto cardFronted = AceType::DynamicCast(frontend_); - if (cardFronted) { - cardFronted->SetDensity(static_cast(density)); - taskExecutor_->PostTask( - [weak, width, height]() { - auto context = weak.Upgrade(); - if (context == nullptr) { - LOGE("context is nullptr"); - return; - } - context->OnSurfaceChanged(width, height); - }, - TaskExecutor::TaskType::UI); - } - - AceEngine::Get().RegisterToWatchDog(instanceId, taskExecutor_, GetSettings().useUIAsJSThread); -} -#else void AceContainer::AttachView(std::unique_ptr window, RSAceView* view, double density, int32_t width, int32_t height, SendRenderDataCallback onRender) { @@ -885,10 +803,10 @@ void AceContainer::AttachView(std::unique_ptr window, RSAceView* view, d aceView_ = view; auto instanceId = aceView_->GetInstanceId(); - auto state = flutter::UIDartState::Current()->GetStateById(instanceId); + //auto state = flutter::UIDartState::Current()->GetStateById(instanceId); ACE_DCHECK(state != nullptr); auto rsTaskExecutor = AceType::DynamicCast(taskExecutor_); - rsTaskExecutor->InitOtherThreads(state->GetTaskRunners()); + //rsTaskExecutor->InitOtherThreads(state->GetTaskRunners()); if (type_ == FrontendType::DECLARATIVE_JS || type_ == FrontendType::ETS_CARD) { // For DECLARATIVE_JS frontend display UI in JS thread temporarily. rsTaskExecutor->InitJsThread(false); @@ -948,7 +866,8 @@ void AceContainer::AttachView(std::unique_ptr window, RSAceView* view, d TaskExecutor::TaskType::UI); } - taskExecutor_->PostTask( + // TODO adaptor to ft_engine + /* taskExecutor_->PostTask( [pipelineContext = AceType::DynamicCast(pipelineContext_), onRender, this]() { CHECK_NULL_VOID(pipelineContext); auto director = Rosen::RSUIDirector::Create(); @@ -973,7 +892,7 @@ void AceContainer::AttachView(std::unique_ptr window, RSAceView* view, d pipelineContext->SetRSUIDirector(director); LOGI("Init Rosen Backend"); }, - TaskExecutor::TaskType::UI); + TaskExecutor::TaskType::UI); */ auto weak = AceType::WeakClaim(AceType::RawPtr(pipelineContext_)); taskExecutor_->PostTask( @@ -1006,7 +925,6 @@ void AceContainer::AttachView(std::unique_ptr window, RSAceView* view, d AceEngine::Get().RegisterToWatchDog(instanceId, taskExecutor_, GetSettings().useUIAsJSThread); } -#endif void AceContainer::InitDeviceInfo(int32_t instanceId, const AceRunArgs& runArgs) { diff --git a/ace_engine/adapter/fangtian/entrance/ace_container.h b/ace_engine/adapter/fangtian/entrance/ace_container.h index 6ee43caa3..1f1a3df33 100644 --- a/ace_engine/adapter/fangtian/entrance/ace_container.h +++ b/ace_engine/adapter/fangtian/entrance/ace_container.h @@ -149,17 +149,10 @@ public: void SetWindowId(uint32_t windowId) override {} -#ifndef ENABLE_ROSEN_BACKEND - FlutterAceView* GetAceView() const - { - return aceView_; - } -#else RSAceView* GetAceView() const { return aceView_; } -#endif void* GetView() const override { @@ -264,19 +257,10 @@ private: void InitializeFrontend(); void InitializeCallback(); -#ifndef ENABLE_ROSEN_BACKEND - void AttachView( - std::unique_ptr window, FlutterAceView* view, double density, int32_t width, int32_t height); -#else void AttachView( std::unique_ptr window, RSAceView* view, double density, int32_t width, int32_t height, SendRenderDataCallback onRender); -#endif -#ifndef ENABLE_ROSEN_BACKEND - FlutterAceView* aceView_ = nullptr; -#else RSAceView* aceView_ = nullptr; -#endif int32_t instanceId_; RefPtr taskExecutor_; diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/BUILD.gn b/ace_engine/adapter/fangtian/entrance/pa_engine/BUILD.gn deleted file mode 100644 index e3027572b..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/BUILD.gn +++ /dev/null @@ -1,79 +0,0 @@ -# Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -#import("//build/ohos.gni") -import("//build/gn/fangtian.gni") -import("//foundation/arkui/ace_engine/ace_config.gni") - -template("pa_backend") { - forward_variables_from(invoker, "*") - - ft_source_set(target_name) { - subsystem_name = ace_engine_subsystem - part_name = ace_engine_part - configs = [ "$ace_root:ace_config" ] - - deps = [] - - include_dirs = [ - "$ability_runtime_services_path/common/include", - "$ability_runtime_path/interfaces/kits/native/ability/native", - "$ability_runtime_inner_api_path/ability_manager/include", - "$ability_runtime_services_path/abilitymgr/include", - "$ability_runtime_services_path/common/include", - "$ability_runtime_napi_path/context", - "$ability_runtime_napi_path/inner/napi_common", - ] - deps = [ -#"$ability_runtime_napi_path/inner/napi_common:napi_common", -#"$ability_runtime_path/frameworks/native/ability/native:abilitykit_native", -# "$ability_runtime_path/frameworks/native/appkit:appkit_native", -#"//foundation/arkui/napi:ace_napi", - "//foundation/systemabilitymgr/safwk/interfaces/innerkits/safwk:system_ability_fwk", - "//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", - ] - deps += [ -#"ability_base:want", -# "ability_base:zuri", -# "bundle_framework:appexecfwk_base", -#"bundle_framework:appexecfwk_core", - "//commonlibrary/c_utils/base:utils", -#"eventhandler:libeventhandler", - "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", - "//foundation/communication/ipc/interfaces/innerkits/ipc_core:ipc_core", -#"//foundation/communication/ipc/interfaces/innerkits/kits/js/napi:rpc", -#"napi:ace_napi", -#"relational_store:native_dataability", -#"relational_store:native_rdb", - "//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", - ] - - sources = [ - "backend_delegate_impl.cpp", - "pa_backend.cpp", - ] - - sources += [ "engine/common/js_backend_engine_loader.cpp" ] - } -} - -foreach(item, ace_platforms) { - pa_backend("pa_backend_" + item.name) { - config = { - } - - if (defined(item.config)) { - config = item.config - } - } -} diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/backend_delegate.h b/ace_engine/adapter/fangtian/entrance/pa_engine/backend_delegate.h deleted file mode 100644 index 794a6661b..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/backend_delegate.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_BACKEND_DELEGATE_H -#define FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_BACKEND_DELEGATE_H - -#include - -#include "base/json/json_util.h" -#include "base/memory/ace_type.h" -#include "base/utils/noncopyable.h" -#include "core/common/backend.h" -#include "core/event/ace_event_helper.h" -#include "frameworks/bridge/js_frontend/engine/common/group_js_bridge.h" - -namespace OHOS::Ace { - -class BackendDelegate : public AceType { - DECLARE_ACE_TYPE(BackendDelegate, AceType); - -public: - BackendDelegate() = default; - ~BackendDelegate() override = default; - - // posting js task from jsengine - virtual void PostJsTask(std::function&& task) = 0; - - // posting js task from jsengine - virtual void PostDelayedJsTask(std::function&& task, uint32_t delayTime) = 0; - - virtual BackendType GetType() const = 0; - - virtual SingleTaskExecutor GetAnimationJsTask() = 0; - - virtual bool GetAssetContent(const std::string& url, std::string& content) = 0; - virtual bool GetAssetContent(const std::string& url, std::vector& content) = 0; - virtual bool GetResourceData(const std::string& fileUri, std::vector& content, std::string& ami) = 0; - virtual std::string GetAssetPath(const std::string& url) = 0; - - virtual void AddTaskObserver(std::function&& task) = 0; - virtual void RemoveTaskObserver() = 0; - - virtual void SetCallBackResult(const std::string& callBackId, const std::string& result) = 0; - - virtual const RefPtr& GetGroupJsBridge() = 0; - - ACE_EXPORT void SetAssetManager(const RefPtr& assetManager) - { - assetManager_ = assetManager; - } - - ACE_EXPORT RefPtr GetAssetManager() const - { - return assetManager_; - } - -protected: - RefPtr assetManager_; - - ACE_DISALLOW_COPY_AND_MOVE(BackendDelegate); -}; - -} // namespace OHOS::Ace - -#endif // FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_BACKEND_DELEGATE_H diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/backend_delegate_impl.cpp b/ace_engine/adapter/fangtian/entrance/pa_engine/backend_delegate_impl.cpp deleted file mode 100644 index 25774ba42..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/backend_delegate_impl.cpp +++ /dev/null @@ -1,594 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "adapter/ohos/entrance/pa_engine/backend_delegate_impl.h" - -#include -#include - -#include "ability.h" -#include "ability_info.h" - -#include "base/log/ace_trace.h" -#include "base/log/event_report.h" -#include "base/utils/utils.h" -#include "core/common/ace_application_info.h" -#include "core/common/platform_bridge.h" -#include "core/components/dialog/dialog_component.h" -#include "core/components/toast/toast_component.h" -#include "frameworks/bridge/common/manifest/manifest_parser.h" -#include "frameworks/bridge/common/utils/utils.h" - -namespace OHOS::Ace { -namespace { -const char PA_MANIFEST_JSON[] = "manifest.json"; -} // namespace - -BackendDelegateImpl::BackendDelegateImpl(const BackendDelegateImplBuilder& builder) - : loadJs_(builder.loadCallback), dispatcherCallback_(builder.transferCallback), - asyncEvent_(builder.asyncEventCallback), syncEvent_(builder.syncEventCallback), insert_(builder.insertCallback), - call_(builder.callCallback), query_(builder.queryCallback), update_(builder.updateCallback), - delete_(builder.deleteCallback), batchInsert_(builder.batchInsertCallback), getType_(builder.getTypeCallback), - getFileTypes_(builder.getFileTypesCallback), openFile_(builder.openFileCallback), - openRawFile_(builder.openRawFileCallback), normalizeUri_(builder.normalizeUriCallback), - denormalizeUri_(builder.denormalizeUriCallback), destroyApplication_(builder.destroyApplicationCallback), - commandApplication_(builder.commandApplicationCallback), connectCallback_(builder.connectCallback), - disConnectCallback_(builder.disConnectCallback), createCallback_(builder.createFormCallback), - deleteCallback_(builder.deleteFormCallback), triggerEventCallback_(builder.triggerEventCallback), - updateCallback_(builder.updateFormCallback), castTemptoNormalCallback_(builder.castTemptoNormalCallback), - visibilityChangedCallback_(builder.visibilityChangedCallback), - acquireStateCallback_(builder.acquireStateCallback), commandCallback_(builder.commandCallback), - shareFormCallback_(builder.shareFormCallback), dumpHeapSnapshotCallback_(builder.dumpHeapSnapshotCallback), - manifestParser_(AceType::MakeRefPtr()), type_(builder.type), - taskExecutor_(builder.taskExecutor) -{} - -void BackendDelegateImpl::ParseManifest() -{ - std::call_once(onceFlag_, [this]() { - std::string jsonContent; - if (!GetAssetContent(PA_MANIFEST_JSON, jsonContent)) { - LOGE("RunPa parse manifest.json failed"); - EventReport::SendFormException(FormExcepType::RUN_PAGE_ERR); - return; - } - manifestParser_->Parse(jsonContent); - }); -} - -void BackendDelegateImpl::RunPa(const std::string& url, const OHOS::AAFwk::Want& want) -{ - ACE_SCOPED_TRACE("BackendDelegateImpl::RunService"); - LOGD("dDelegateImpl RunService url=%{private}s", url.c_str()); - ParseManifest(); - // if mutli pa in one hap should parse manifest get right url - LoadPa(url, want); -} - -void BackendDelegateImpl::SetJsMessageDispatcher(const RefPtr& dispatcher) const -{ - taskExecutor_->PostTask([dispatcherCallback = dispatcherCallback_, dispatcher] { dispatcherCallback(dispatcher); }, - TaskExecutor::TaskType::JS); -} - -void BackendDelegateImpl::SetCallBackResult(const std::string& callBackId, const std::string& result) -{ - jsCallBackResult_.try_emplace(Framework::StringToInt(callBackId), result); -} - -void BackendDelegateImpl::PostJsTask(std::function&& task) -{ - taskExecutor_->PostTask(task, TaskExecutor::TaskType::JS); -} - -void BackendDelegateImpl::PostDelayedJsTask(std::function&& task, uint32_t delayTime) -{ - taskExecutor_->PostDelayedTask(task, TaskExecutor::TaskType::JS, delayTime); -} - -bool BackendDelegateImpl::GetAssetContent(const std::string& url, std::string& content) -{ - return Framework::GetAssetContentImpl(assetManager_, url, content); -} - -bool BackendDelegateImpl::GetAssetContent(const std::string& url, std::vector& content) -{ - return Framework::GetAssetContentImpl(assetManager_, url, content); -} - -std::string BackendDelegateImpl::GetAssetPath(const std::string& url) -{ - return Framework::GetAssetPathImpl(assetManager_, url); -} - -void BackendDelegateImpl::LoadPa(const std::string& url, const OHOS::AAFwk::Want& want) -{ - LOGD("BackendDelegateImpl LoadPa: %{private}s.", url.c_str()); - - std::unique_lock lock(LoadPaMutex_); - if (isStagingPageExist_) { - if (condition_.wait_for(lock, std::chrono::seconds(1)) == std::cv_status::timeout) { - LOGE("BackendDelegateImpl, load page failed, waiting for current page loading finish."); - return; - } - } - - isStagingPageExist_ = true; - - if (GetType() == BackendType::FORM) { - taskExecutor_->PostSyncTask( - [weak = AceType::WeakClaim(this), url, want] { - auto delegate = weak.Upgrade(); - if (!delegate) { - return; - } - delegate->loadJs_(url, want); - }, - TaskExecutor::TaskType::JS); - } else { - taskExecutor_->PostTask( - [weak = AceType::WeakClaim(this), url, want] { - auto delegate = weak.Upgrade(); - CHECK_NULL_VOID_NOLOG(delegate); - delegate->loadJs_(url, want); - }, - TaskExecutor::TaskType::JS); - } -} - -void BackendDelegateImpl::TransferJsResponseData(int32_t callbackId, int32_t code, std::vector&& data) const -{ - LOGI("BackendDelegateImpl TransferJsResponseData"); - auto weak = AceType::WeakClaim(AceType::RawPtr(groupJsBridge_)); - taskExecutor_->PostTask( - [callbackId, code, data = std::move(data), weak]() mutable { - auto groupJsBridge = weak.Upgrade(); - if (groupJsBridge) { - groupJsBridge->TriggerModuleJsCallback(callbackId, code, std::move(data)); - } - }, - TaskExecutor::TaskType::JS); -} - -void BackendDelegateImpl::TransferJsPluginGetError( - int32_t callbackId, int32_t errorCode, std::string&& errorMessage) const -{ - LOGI("BackendDelegateImpl TransferJsPluginGetError"); - auto weak = AceType::WeakClaim(AceType::RawPtr(groupJsBridge_)); - taskExecutor_->PostTask( - [callbackId, errorCode, errorMessage = std::move(errorMessage), weak]() mutable { - auto groupJsBridge = weak.Upgrade(); - if (groupJsBridge) { - groupJsBridge->TriggerModulePluginGetErrorCallback(callbackId, errorCode, std::move(errorMessage)); - } - }, - TaskExecutor::TaskType::JS); -} - -void BackendDelegateImpl::TransferJsEventData(int32_t callbackId, int32_t code, std::vector&& data) const -{ - LOGI("BackendDelegateImpl TransferJsEventData"); - auto weak = AceType::WeakClaim(AceType::RawPtr(groupJsBridge_)); - taskExecutor_->PostTask( - [callbackId, code, data = std::move(data), weak]() mutable { - auto groupJsBridge = weak.Upgrade(); - if (groupJsBridge) { - groupJsBridge->TriggerEventJsCallback(callbackId, code, std::move(data)); - } - }, - TaskExecutor::TaskType::JS); -} - -void BackendDelegateImpl::LoadPluginJsCode(std::string&& jsCode) const -{ - LOGI("BackendDelegateImpl LoadPluginJsCode"); - auto weak = AceType::WeakClaim(AceType::RawPtr(groupJsBridge_)); - taskExecutor_->PostTask( - [jsCode = std::move(jsCode), weak]() mutable { - auto groupJsBridge = weak.Upgrade(); - if (groupJsBridge) { - groupJsBridge->LoadPluginJsCode(std::move(jsCode)); - } - }, - TaskExecutor::TaskType::JS); -} - -void BackendDelegateImpl::LoadPluginJsByteCode(std::vector&& jsCode, std::vector&& jsCodeLen) const -{ - LOGI("BackendDelegateImpl LoadPluginJsByteCode"); - auto weak = AceType::WeakClaim(AceType::RawPtr(groupJsBridge_)); - taskExecutor_->PostTask( - [jsCode = std::move(jsCode), jsCodeLen = std::move(jsCodeLen), weak]() mutable { - auto groupJsBridge = weak.Upgrade(); - if (groupJsBridge) { - groupJsBridge->LoadPluginJsByteCode(std::move(jsCode), std::move(jsCodeLen)); - } - }, - TaskExecutor::TaskType::JS); -} - -SingleTaskExecutor BackendDelegateImpl::GetAnimationJsTask() -{ - return SingleTaskExecutor::Make(taskExecutor_, TaskExecutor::TaskType::JS); -} - -void BackendDelegateImpl::AddTaskObserver(std::function&& task) -{ - taskExecutor_->AddTaskObserver(std::move(task)); -} - -void BackendDelegateImpl::RemoveTaskObserver() -{ - taskExecutor_->RemoveTaskObserver(); -} - -void BackendDelegateImpl::FireAsyncEvent( - const std::string& eventId, const std::string& param, const std::string& jsonArgs) -{ - LOGD("FireAsyncEvent eventId: %{public}s", eventId.c_str()); - std::string args = param; - args.append(",null").append(",null"); // callback and dom changes - if (!jsonArgs.empty()) { - args.append(",").append(jsonArgs); // method args - } - taskExecutor_->PostTask( - [weak = AceType::WeakClaim(this), eventId, args = std::move(args)] { - auto delegate = weak.Upgrade(); - if (delegate) { - delegate->asyncEvent_(eventId, args); - } - }, - TaskExecutor::TaskType::JS); -} - -bool BackendDelegateImpl::FireSyncEvent( - const std::string& eventId, const std::string& param, const std::string& jsonArgs) -{ - std::string resultStr; - FireSyncEvent(eventId, param, jsonArgs, resultStr); - return (resultStr == "true"); -} - -void BackendDelegateImpl::FireSyncEvent( - const std::string& eventId, const std::string& param, const std::string& jsonArgs, std::string& result) -{ - int32_t callbackId = callbackCnt_++; - std::string args = param; - args.append("{\"_callbackId\":\"").append(std::to_string(callbackId)).append("\"}").append(",null"); - if (!jsonArgs.empty()) { - args.append(",").append(jsonArgs); // method args - } - taskExecutor_->PostSyncTask( - [weak = AceType::WeakClaim(this), eventId, args = std::move(args)] { - auto delegate = weak.Upgrade(); - if (delegate) { - delegate->syncEvent_(eventId, args); - } - }, - TaskExecutor::TaskType::JS); - - result = jsCallBackResult_[callbackId]; - LOGD("FireSyncEvent eventId: %{public}s, callbackId: %{public}d", eventId.c_str(), callbackId); - jsCallBackResult_.erase(callbackId); -} - -void BackendDelegateImpl::OnApplicationDestroy(const std::string& packageName) -{ - taskExecutor_->PostSyncTask( - [destroyApplication = destroyApplication_, packageName] { destroyApplication(packageName); }, - TaskExecutor::TaskType::JS); -} - -void BackendDelegateImpl::OnApplicationCommand(const std::string& intent, int startId) -{ - taskExecutor_->PostTask( - [weak = AceType::WeakClaim(this), intent, startId] { - auto delegate = weak.Upgrade(); - CHECK_NULL_VOID_NOLOG(delegate); - delegate->commandApplication_(intent, startId); - }, - TaskExecutor::TaskType::JS); -} - -void BackendDelegateImpl::MethodChannel(const std::string& methodName, std::string& jsonStr) -{ - std::string resultStr; - FireSyncEvent("_root", std::string("\"").append(methodName).append("\","), jsonStr, resultStr); - jsonStr.assign(resultStr); -} - -int32_t BackendDelegateImpl::Insert(const Uri& uri, const OHOS::NativeRdb::ValuesBucket& value) -{ - int32_t ret = 0; - CallingInfo callingInfo; - NAPI_RemoteObject_getCallingInfo(callingInfo); - LOGD("BackendDelegateImpl Insert get callingInfo is %{public}u", callingInfo.callingTokenId); - taskExecutor_->PostSyncTask( - [insert = insert_, &ret, uri, value, callingInfo] { ret = insert(uri, value, callingInfo); }, - TaskExecutor::TaskType::JS); - return ret; -} - -std::shared_ptr BackendDelegateImpl::Call( - const Uri& uri, const std::string& method, const std::string& arg, const AppExecFwk::PacMap& pacMap) -{ - std::shared_ptr ret = nullptr; - CallingInfo callingInfo; - NAPI_RemoteObject_getCallingInfo(callingInfo); - LOGD("BackendDelegateImpl Call get callingInfo is %{public}u", callingInfo.callingTokenId); - taskExecutor_->PostSyncTask( - [call = call_, &ret, method, arg, pacMap, callingInfo] { ret = call(method, arg, pacMap, callingInfo); }, - TaskExecutor::TaskType::JS); - return ret; -} - -std::shared_ptr BackendDelegateImpl::Query( - const Uri& uri, const std::vector& columns, const OHOS::NativeRdb::DataAbilityPredicates& predicates) -{ - std::shared_ptr ret; - CallingInfo callingInfo; - NAPI_RemoteObject_getCallingInfo(callingInfo); - LOGD("BackendDelegateImpl Query get callingInfo is %{public}u", callingInfo.callingTokenId); - taskExecutor_->PostSyncTask([query = query_, &ret, uri, columns, predicates, - callingInfo] { ret = query(uri, columns, predicates, callingInfo); }, - TaskExecutor::TaskType::JS); - return ret; -} - -int32_t BackendDelegateImpl::Update(const Uri& uri, const OHOS::NativeRdb::ValuesBucket& value, - const OHOS::NativeRdb::DataAbilityPredicates& predicates) -{ - int32_t ret = 0; - CallingInfo callingInfo; - NAPI_RemoteObject_getCallingInfo(callingInfo); - LOGD("BackendDelegateImpl Update get callingInfo is %{public}u", callingInfo.callingTokenId); - taskExecutor_->PostSyncTask([update = update_, &ret, uri, value, predicates, - callingInfo] { ret = update(uri, value, predicates, callingInfo); }, - TaskExecutor::TaskType::JS); - return ret; -} - -int32_t BackendDelegateImpl::Delete(const Uri& uri, const OHOS::NativeRdb::DataAbilityPredicates& predicates) -{ - int32_t ret = 0; - CallingInfo callingInfo; - NAPI_RemoteObject_getCallingInfo(callingInfo); - LOGD("BackendDelegateImpl Delete get callingInfo is %{public}u", callingInfo.callingTokenId); - taskExecutor_->PostSyncTask([deleteCallback = delete_, &ret, uri, predicates, - callingInfo] { ret = deleteCallback(uri, predicates, callingInfo); }, - TaskExecutor::TaskType::JS); - return ret; -} - -int32_t BackendDelegateImpl::BatchInsert(const Uri& uri, const std::vector& values) -{ - int32_t ret = 0; - CallingInfo callingInfo; - NAPI_RemoteObject_getCallingInfo(callingInfo); - LOGD("BackendDelegateImpl BatchInsert get callingInfo is %{public}u", callingInfo.callingTokenId); - taskExecutor_->PostSyncTask( - [batchInsert = batchInsert_, &ret, uri, values, callingInfo] { ret = batchInsert(uri, values, callingInfo); }, - TaskExecutor::TaskType::JS); - return ret; -} - -std::string BackendDelegateImpl::GetType(const Uri& uri) -{ - std::string ret; - CallingInfo callingInfo; - NAPI_RemoteObject_getCallingInfo(callingInfo); - LOGD("BackendDelegateImpl GetType get callingInfo is %{public}u", callingInfo.callingTokenId); - taskExecutor_->PostSyncTask( - [getType = getType_, &ret, uri, callingInfo] { ret = getType(uri, callingInfo); }, TaskExecutor::TaskType::JS); - return ret; -} - -std::vector BackendDelegateImpl::GetFileTypes(const Uri& uri, const std::string& mimeTypeFilter) -{ - std::vector ret; - CallingInfo callingInfo; - NAPI_RemoteObject_getCallingInfo(callingInfo); - LOGD("BackendDelegateImpl GetFileTypes get callingInfo is %{public}u", callingInfo.callingTokenId); - taskExecutor_->PostSyncTask([getFileTypes = getFileTypes_, &ret, uri, mimeTypeFilter, - callingInfo] { ret = getFileTypes(uri, mimeTypeFilter, callingInfo); }, - TaskExecutor::TaskType::JS); - return ret; -} - -int32_t BackendDelegateImpl::OpenFile(const Uri& uri, const std::string& mode) -{ - int32_t ret = 0; - CallingInfo callingInfo; - NAPI_RemoteObject_getCallingInfo(callingInfo); - LOGD("BackendDelegateImpl OpenFile get callingInfo is %{public}u", callingInfo.callingTokenId); - taskExecutor_->PostSyncTask( - [openFile = openFile_, &ret, uri, mode, callingInfo] { ret = openFile(uri, mode, callingInfo); }, - TaskExecutor::TaskType::JS); - return ret; -} - -int32_t BackendDelegateImpl::OpenRawFile(const Uri& uri, const std::string& mode) -{ - int32_t ret = 0; - CallingInfo callingInfo; - NAPI_RemoteObject_getCallingInfo(callingInfo); - LOGD("BackendDelegateImpl OpenRawFile get callingInfo is %{public}u", callingInfo.callingTokenId); - taskExecutor_->PostSyncTask( - [openRawFile = openRawFile_, &ret, uri, mode, callingInfo] { ret = openRawFile(uri, mode, callingInfo); }, - TaskExecutor::TaskType::JS); - return ret; -} - -Uri BackendDelegateImpl::NormalizeUri(const Uri& uri) -{ - Uri ret(""); - CallingInfo callingInfo; - NAPI_RemoteObject_getCallingInfo(callingInfo); - LOGD("BackendDelegateImpl NormalizeUri get callingInfo is %{public}u", callingInfo.callingTokenId); - taskExecutor_->PostSyncTask( - [normalizeUri = normalizeUri_, &ret, uri, callingInfo] { ret = normalizeUri(uri, callingInfo); }, - TaskExecutor::TaskType::JS); - return ret; -} - -Uri BackendDelegateImpl::DenormalizeUri(const Uri& uri) -{ - Uri ret(""); - CallingInfo callingInfo; - NAPI_RemoteObject_getCallingInfo(callingInfo); - LOGD("BackendDelegateImpl DenormalizeUri get callingInfo is %{public}u", callingInfo.callingTokenId); - taskExecutor_->PostSyncTask( - [denormalizeUri = denormalizeUri_, &ret, uri, callingInfo] { ret = denormalizeUri(uri, callingInfo); }, - TaskExecutor::TaskType::JS); - return ret; -} - -sptr BackendDelegateImpl::OnConnect(const OHOS::AAFwk::Want& want) -{ - sptr ret = nullptr; - taskExecutor_->PostSyncTask([connectCallback = connectCallback_, want, &ret]() { ret = connectCallback(want); }, - TaskExecutor::TaskType::JS); - return ret; -} - -void BackendDelegateImpl::OnDisConnect(const OHOS::AAFwk::Want& want) -{ - taskExecutor_->PostTask( - [disConnectCallback = disConnectCallback_, want] { disConnectCallback(want); }, TaskExecutor::TaskType::JS); -} - -void BackendDelegateImpl::OnCreate(const OHOS::AAFwk::Want& want) -{ - taskExecutor_->PostSyncTask( - [createCallback = createCallback_, want] { createCallback(want); }, TaskExecutor::TaskType::JS); -} - -void BackendDelegateImpl::OnDelete(const int64_t formId) -{ - taskExecutor_->PostTask( - [deleteCallback = deleteCallback_, formId] { deleteCallback(formId); }, TaskExecutor::TaskType::JS); -} - -void BackendDelegateImpl::OnTriggerEvent(const int64_t formId, const std::string& message) -{ - taskExecutor_->PostTask( - [triggerEventCallback = triggerEventCallback_, formId, message] { triggerEventCallback(formId, message); }, - TaskExecutor::TaskType::JS); -} - -void BackendDelegateImpl::OnUpdate(const int64_t formId) -{ - taskExecutor_->PostTask( - [updateCallback = updateCallback_, formId] { updateCallback(formId); }, TaskExecutor::TaskType::JS); -} - -void BackendDelegateImpl::OnCastTemptoNormal(const int64_t formId) -{ - taskExecutor_->PostTask( - [castTemptoNormalCallback = castTemptoNormalCallback_, formId] { castTemptoNormalCallback(formId); }, - TaskExecutor::TaskType::JS); -} - -void BackendDelegateImpl::OnVisibilityChanged(const std::map& formEventsMap) -{ - taskExecutor_->PostTask([visibilityChangedCallback = visibilityChangedCallback_, - formEventsMap] { visibilityChangedCallback(formEventsMap); }, - TaskExecutor::TaskType::JS); -} - -int32_t BackendDelegateImpl::OnAcquireFormState(const OHOS::AAFwk::Want& want) -{ - auto ret = (int32_t)AppExecFwk::FormState::UNKNOWN; - taskExecutor_->PostSyncTask( - [acquireStateCallback = acquireStateCallback_, &ret, want] { ret = acquireStateCallback(want); }, - TaskExecutor::TaskType::JS); - return ret; -} - -void BackendDelegateImpl::OnCommand(const OHOS::AAFwk::Want& want, int startId) -{ - taskExecutor_->PostTask([commandCallback = commandCallback_, want, startId] { commandCallback(want, startId); }, - TaskExecutor::TaskType::JS); -} - -void BackendDelegateImpl::DumpHeapSnapshot(bool isPrivate) -{ - taskExecutor_->PostTask( - [dumpHeapSnapshotCallback = dumpHeapSnapshotCallback_, isPrivate] { dumpHeapSnapshotCallback(isPrivate); }, - TaskExecutor::TaskType::JS); -} - -bool BackendDelegateImpl::ParseFileUri( - const RefPtr& assetManager, const std::string& fileUri, std::string& assetsFilePath) -{ - if (!assetManager || fileUri.empty() || (fileUri.length() > PATH_MAX)) { - return false; - } - - std::string fileName; - std::string filePath; - size_t slashPos = fileUri.find_last_of("/"); - if (slashPos == std::string::npos) { - fileName = fileUri; - } else { - fileName = fileUri.substr(slashPos + 1); - filePath = fileUri.substr(0, slashPos); - } - - if (Framework::StartWith(filePath, "/")) { - filePath = filePath.substr(1); - } - - std::vector files; - assetManager->GetAssetList(filePath, files); - - bool fileExist = false; - for (const auto& file : files) { - bool startWithSlash = Framework::StartWith(file, "/"); - if ((startWithSlash && (file.substr(1) == fileName)) || (!startWithSlash && (file == fileName))) { - assetsFilePath = filePath + file; - fileExist = true; - break; - } - } - - return fileExist; -} - -bool BackendDelegateImpl::GetResourceData(const std::string& fileUri, std::vector& content, std::string& ami) -{ - std::string targetFilePath; - if (!ParseFileUri(assetManager_, fileUri, targetFilePath)) { - LOGE("GetResourceData parse file uri failed."); - return false; - } - ami = assetManager_->GetAssetPath(targetFilePath) + targetFilePath; - if (!Framework::GetAssetContentAllowEmpty(assetManager_, targetFilePath, content)) { - LOGE("GetResourceData GetAssetContent failed."); - return false; - } - - return true; -} - -bool BackendDelegateImpl::OnShare(int64_t formId, OHOS::AAFwk::WantParams& wantParams) -{ - bool result = false; - taskExecutor_->PostSyncTask([shareFormCallback = shareFormCallback_, formId, &wantParams, - &result]() { result = shareFormCallback(formId, wantParams); }, - TaskExecutor::TaskType::JS); - - return result; -} -} // namespace OHOS::Ace diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/backend_delegate_impl.h b/ace_engine/adapter/fangtian/entrance/pa_engine/backend_delegate_impl.h deleted file mode 100644 index 194570cb7..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/backend_delegate_impl.h +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_BACKEND_DELEGATE_IMPL_H -#define FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_BACKEND_DELEGATE_IMPL_H - -#include -#include -#include - -#include "abs_shared_result_set.h" -#include "data_ability_predicates.h" -#include "form_provider_info.h" -#include "iremote_object.h" -#include "napi_remote_object.h" -#include "pac_map.h" -#include "values_bucket.h" -#include "want.h" - -#include "adapter/ohos/entrance/pa_engine/backend_delegate.h" -#include "base/memory/ace_type.h" -#include "base/thread/cancelable_callback.h" -#include "core/common/backend.h" -#include "core/common/js_message_dispatcher.h" -#include "core/pipeline/pipeline_context.h" -#include "frameworks/bridge/common/manifest/manifest_parser.h" - -namespace OHOS::Ace { - -using LoadJsCallback = std::function; -using JsMessageDispatcherSetterCallback = std::function&)>; -using PaEventCallback = std::function; -using DestroyApplicationCallback = std::function; -using InsertCallback = - std::function; -using CallCallback = std::function(const std::string& method, - const std::string& arg, const AppExecFwk::PacMap& pacMap, const CallingInfo& callingInfo)>; -using QueryCallback = std::function(const Uri& uri, - const std::vector& columns, const OHOS::NativeRdb::DataAbilityPredicates& predicates, - const CallingInfo& callingInfo)>; -using UpdateCallback = std::function; -using DeleteCallback = std::function; -using BatchInsertCallback = std::function& values, const CallingInfo& callingInfo)>; -using GetTypeCallback = std::function; -using GetFileTypesCallback = std::function( - const Uri& uri, const std::string& mimeTypeFilter, const CallingInfo& callingInfo)>; -using OpenFileCallback = - std::function; -using OpenRawFileCallback = - std::function; -using NormalizeUriCallback = std::function; -using DenormalizeUriCallback = std::function; -using ConnectCallback = std::function(const OHOS::AAFwk::Want& want)>; -using DisConnectCallback = std::function; -using CreateFormCallback = std::function; -using DeleteFormCallback = std::function; -using TriggerEventCallback = std::function; -using UpdateFormCallback = std::function; -using CastTemptoNormalCallback = std::function; -using VisibilityChangedCallback = std::function& formEventsMap)>; -using AcquireStateCallback = std::function; -using CommandCallback = std::function; -using CommandApplicationCallback = std::function; -using ShareFormCallback = std::function; -using DumpHeapSnapshotCallback = std::function; - -struct BackendDelegateImplBuilder { - RefPtr taskExecutor; - LoadJsCallback loadCallback; - PaEventCallback asyncEventCallback; - PaEventCallback syncEventCallback; - JsMessageDispatcherSetterCallback transferCallback; - DestroyApplicationCallback destroyApplicationCallback; - InsertCallback insertCallback; - CallCallback callCallback; - QueryCallback queryCallback; - UpdateCallback updateCallback; - DeleteCallback deleteCallback; - BatchInsertCallback batchInsertCallback; - GetTypeCallback getTypeCallback; - GetFileTypesCallback getFileTypesCallback; - OpenFileCallback openFileCallback; - OpenRawFileCallback openRawFileCallback; - NormalizeUriCallback normalizeUriCallback; - DenormalizeUriCallback denormalizeUriCallback; - ConnectCallback connectCallback; - DisConnectCallback disConnectCallback; - CreateFormCallback createFormCallback; - DeleteFormCallback deleteFormCallback; - TriggerEventCallback triggerEventCallback; - UpdateFormCallback updateFormCallback; - CastTemptoNormalCallback castTemptoNormalCallback; - VisibilityChangedCallback visibilityChangedCallback; - AcquireStateCallback acquireStateCallback; - CommandCallback commandCallback; - CommandApplicationCallback commandApplicationCallback; - ShareFormCallback shareFormCallback; - DumpHeapSnapshotCallback dumpHeapSnapshotCallback; - BackendType type; -}; - -class BackendDelegateImpl : public BackendDelegate { - DECLARE_ACE_TYPE(BackendDelegateImpl, BackendDelegate); - -public: - explicit BackendDelegateImpl(const BackendDelegateImplBuilder& builder); - ~BackendDelegateImpl() override = default; - - // JsBackend delegate functions. - void RunPa(const std::string& url, const OHOS::AAFwk::Want& want); - void SetJsMessageDispatcher(const RefPtr& dispatcher) const; - - // BackendDelegate overrides. - void PostJsTask(std::function&& task) override; - - void PostDelayedJsTask(std::function&& task, uint32_t delayTime) override; - - SingleTaskExecutor GetAnimationJsTask() override; - - void AddTaskObserver(std::function&& task) override; - void RemoveTaskObserver() override; - - BackendType GetType() const override - { - return type_; - } - - const RefPtr& GetGroupJsBridge() override - { - return groupJsBridge_; - } - - void SetGroupJsBridge(const RefPtr& groupJsBridge) - { - groupJsBridge_ = groupJsBridge; - } - - void SetCallBackResult(const std::string& callBackId, const std::string& result) override; - - bool GetAssetContent(const std::string& url, std::string& content) override; - bool GetAssetContent(const std::string& url, std::vector& content) override; - bool GetResourceData(const std::string& fileUri, std::vector& content, std::string& ami) override; - std::string GetAssetPath(const std::string& url) override; - - // JsEventHandler delegate functions. - void FireAsyncEvent(const std::string& eventId, const std::string& param, const std::string& jsonArgs); - bool FireSyncEvent(const std::string& eventId, const std::string& param, const std::string& jsonArgs); - void FireSyncEvent( - const std::string& eventId, const std::string& param, const std::string& jsonArgs, std::string& result); - - // special JsEventHandler - void OnApplicationDestroy(const std::string& packageName); - sptr OnConnect(const OHOS::AAFwk::Want& want); - void OnDisConnect(const OHOS::AAFwk::Want& want); - void OnCommand(const OHOS::AAFwk::Want& want, int startId); - void OnApplicationCommand(const std::string& intent, int startId); - void DumpHeapSnapshot(bool isPrivate); - - void TransferJsResponseData(int32_t callbackId, int32_t code, std::vector&& data) const; - void TransferJsPluginGetError(int32_t callbackId, int32_t errorCode, std::string&& errorMessage) const; - void TransferJsEventData(int32_t callbackId, int32_t code, std::vector&& data) const; - void LoadPluginJsCode(std::string&& jsCode) const; - void LoadPluginJsByteCode(std::vector&& jsCode, std::vector&& jsCodeLen) const; - - void MethodChannel(const std::string& methodName, std::string& jsonStr); - - int32_t Insert(const Uri& uri, const OHOS::NativeRdb::ValuesBucket& value); - std::shared_ptr Call( - const Uri& uri, const std::string& method, const std::string& arg, const AppExecFwk::PacMap& pacMap); - std::shared_ptr Query(const Uri& uri, const std::vector& columns, - const OHOS::NativeRdb::DataAbilityPredicates& predicates); - int32_t Update(const Uri& uri, const OHOS::NativeRdb::ValuesBucket& value, - const OHOS::NativeRdb::DataAbilityPredicates& predicates); - int32_t Delete(const Uri& uri, const OHOS::NativeRdb::DataAbilityPredicates& predicates); - - int32_t BatchInsert(const Uri& uri, const std::vector& values); - std::string GetType(const Uri& uri); - std::vector GetFileTypes(const Uri& uri, const std::string& mimeTypeFilter); - int32_t OpenFile(const Uri& uri, const std::string& mode); - int32_t OpenRawFile(const Uri& uri, const std::string& mode); - Uri NormalizeUri(const Uri& uri); - Uri DenormalizeUri(const Uri& uri); - - void OnCreate(const OHOS::AAFwk::Want& want); - void OnDelete(const int64_t formId); - void OnTriggerEvent(const int64_t formId, const std::string& message); - void OnUpdate(const int64_t formId); - void OnCastTemptoNormal(const int64_t formId); - void OnVisibilityChanged(const std::map& formEventsMap); - int32_t OnAcquireFormState(const OHOS::AAFwk::Want& want); - bool OnShare(int64_t formId, OHOS::AAFwk::WantParams& wantParams); - -private: - void LoadPa(const std::string& url, const OHOS::AAFwk::Want& want); - bool ParseFileUri( - const RefPtr& assetManager, const std::string& fileUri, std::string& assetsFilePath); - - void ParseManifest(); - int32_t callbackCnt_ = 0; - bool isStagingPageExist_ = false; - std::unordered_map jsCallBackResult_; - - LoadJsCallback loadJs_; - JsMessageDispatcherSetterCallback dispatcherCallback_; - - PaEventCallback asyncEvent_; - PaEventCallback syncEvent_; - - InsertCallback insert_; - CallCallback call_; - QueryCallback query_; - UpdateCallback update_; - DeleteCallback delete_; - BatchInsertCallback batchInsert_; - GetTypeCallback getType_; - GetFileTypesCallback getFileTypes_; - OpenFileCallback openFile_; - OpenRawFileCallback openRawFile_; - NormalizeUriCallback normalizeUri_; - DenormalizeUriCallback denormalizeUri_; - - DestroyApplicationCallback destroyApplication_; - CommandApplicationCallback commandApplication_; - ConnectCallback connectCallback_; - DisConnectCallback disConnectCallback_; - - CreateFormCallback createCallback_; - DeleteFormCallback deleteCallback_; - TriggerEventCallback triggerEventCallback_; - UpdateFormCallback updateCallback_; - CastTemptoNormalCallback castTemptoNormalCallback_; - VisibilityChangedCallback visibilityChangedCallback_; - AcquireStateCallback acquireStateCallback_; - CommandCallback commandCallback_; - ShareFormCallback shareFormCallback_; - DumpHeapSnapshotCallback dumpHeapSnapshotCallback_; - - RefPtr manifestParser_; - BackendType type_ = BackendType::SERVICE; - - RefPtr taskExecutor_; - RefPtr groupJsBridge_; - mutable std::mutex mutex_; - mutable std::once_flag onceFlag_; - - std::mutex LoadPaMutex_; - std::condition_variable condition_; -}; - -} // namespace OHOS::Ace - -#endif // FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_BACKEND_DELEGATE_IMPL_H diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/common/js_backend_engine.h b/ace_engine/adapter/fangtian/entrance/pa_engine/engine/common/js_backend_engine.h deleted file mode 100644 index acc91f494..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/common/js_backend_engine.h +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_COMMON_JS_BACKEND_ENGINE_H -#define FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_COMMON_JS_BACKEND_ENGINE_H - -#include -#include - -#include "abs_shared_result_set.h" -#include "data_ability_predicates.h" -#include "form_provider_info.h" -#include "iremote_object.h" -#include "napi_remote_object.h" -#include "pac_map.h" -#include "values_bucket.h" -#include "want.h" - -#include "adapter/ohos/entrance/pa_engine/backend_delegate.h" -#include "core/common/backend.h" - -namespace OHOS::Ace { - -class JsBackendEngineInstance { -public: - JsBackendEngineInstance() = default; - virtual ~JsBackendEngineInstance() = default; -}; - -class JsBackendEngine : public AceType { - DECLARE_ACE_TYPE(JsBackendEngine, AceType); - -public: - JsBackendEngine() = default; - virtual ~JsBackendEngine() = default; - - virtual bool Initialize(const RefPtr& delegate) = 0; - - virtual void LoadJs(const std::string& url, const OHOS::AAFwk::Want& want) = 0; - - virtual void SetJsMessageDispatcher(const RefPtr& dispatcher) = 0; - - virtual void FireAsyncEvent(const std::string& eventId, const std::string& param) = 0; - - virtual void FireSyncEvent(const std::string& eventId, const std::string& param) = 0; - - virtual void DestroyApplication(const std::string& packageName) = 0; - - virtual int32_t Insert( - const Uri& uri, const OHOS::NativeRdb::ValuesBucket& value, const CallingInfo& callingInfo) = 0; - virtual std::shared_ptr Call(const std::string& method, const std::string& arg, - const AppExecFwk::PacMap& pacMap, const CallingInfo& callingInfo) = 0; - virtual std::shared_ptr Query(const Uri& uri, - const std::vector& columns, const OHOS::NativeRdb::DataAbilityPredicates& predicates, - const CallingInfo& callingInfo) = 0; - virtual int32_t Update(const Uri& uri, const OHOS::NativeRdb::ValuesBucket& value, - const OHOS::NativeRdb::DataAbilityPredicates& predicates, const CallingInfo& callingInfo) = 0; - virtual int32_t Delete( - const Uri& uri, const OHOS::NativeRdb::DataAbilityPredicates& predicates, const CallingInfo& callingInfo) = 0; - - virtual int32_t BatchInsert( - const Uri& uri, const std::vector& values, const CallingInfo& callingInfo) = 0; - virtual std::string GetType(const Uri& uri, const CallingInfo& callingInfo) = 0; - virtual std::vector GetFileTypes( - const Uri& uri, const std::string& mimeTypeFilter, const CallingInfo& callingInfo) = 0; - virtual int32_t OpenFile(const Uri& uri, const std::string& mode, const CallingInfo& callingInfo) = 0; - virtual int32_t OpenRawFile(const Uri& uri, const std::string& mode, const CallingInfo& callingInfo) = 0; - virtual Uri NormalizeUri(const Uri& uri, const CallingInfo& callingInfo) = 0; - virtual Uri DenormalizeUri(const Uri& uri, const CallingInfo& callingInfo) = 0; - virtual sptr OnConnectService(const OHOS::AAFwk::Want& want) = 0; - virtual void OnDisconnectService(const OHOS::AAFwk::Want& want) = 0; - virtual void OnCreate(const OHOS::AAFwk::Want& want) = 0; - virtual void OnDelete(const int64_t formId) = 0; - virtual void OnTriggerEvent(const int64_t formId, const std::string& message) = 0; - virtual void OnUpdate(const int64_t formId) = 0; - virtual void OnCastTemptoNormal(const int64_t formId) = 0; - virtual void OnVisibilityChanged(const std::map& formEventsMap) = 0; - virtual int32_t OnAcquireFormState(const OHOS::AAFwk::Want& want) = 0; - virtual void OnCommand(const OHOS::AAFwk::Want& want, int startId) = 0; - virtual bool OnShare(int64_t formId, OHOS::AAFwk::WantParams& wantParams) = 0; - virtual void DumpHeapSnapshot(bool isPrivate) = 0; - - void SetFormData(const AppExecFwk::FormProviderData& formProviderData) - { - formProviderData_ = formProviderData; - } - - AppExecFwk::FormProviderData GetFormData() const - { - return formProviderData_; - } - - virtual void OnCommandApplication(const std::string& intent, int startId) = 0; - - virtual RefPtr GetGroupJsBridge() = 0; - - void AddExtraNativeObject(const std::string& key, void* value) - { - extraNativeObject_[key] = value; - } - - const std::unordered_map& GetExtraNativeObject() const - { - return extraNativeObject_; - } - - bool IsDebugVersion() const - { - return isDebugVersion_; - } - - void SetDebugVersion(bool value) - { - isDebugVersion_ = value; - } - - bool NeedDebugBreakPoint() const - { - return needDebugBreakPoint_; - } - - void SetNeedDebugBreakPoint(bool value) - { - needDebugBreakPoint_ = value; - } - -private: - std::string instanceName_; - AppExecFwk::FormProviderData formProviderData_; - std::unordered_map extraNativeObject_; - // weather the app has debugger.so. - bool isDebugVersion_ = false; - // if debug, '-D' means need debug breakpoint, by default, do not enter breakpoint. - bool needDebugBreakPoint_ = false; -}; - -} // namespace OHOS::Ace - -#endif // FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_COMMON_JS_BACKEND_ENGINE_H diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/common/js_backend_engine_loader.cpp b/ace_engine/adapter/fangtian/entrance/pa_engine/engine/common/js_backend_engine_loader.cpp deleted file mode 100644 index 9909ac5eb..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/common/js_backend_engine_loader.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "adapter/ohos/entrance/pa_engine/engine/common/js_backend_engine_loader.h" - -#include - -#include "base/log/log.h" -#include "base/utils/singleton.h" -#include "base/utils/system_properties.h" -#include "base/utils/utils.h" -#include "core/common/ace_application_info.h" - -namespace OHOS::Ace { -namespace { - -constexpr char BACKEND_ENGINE_ENTRY[] = "OHOS_ACE_GetJsBackendEngineLoader"; - -using DynamicEntry = void* (*)(); -class DummyJsBackendEngineLoader final : public JsBackendEngineLoader, public Singleton { - DECLARE_SINGLETON(DummyJsBackendEngineLoader); - -public: - RefPtr CreateJsBackendEngine(int32_t instanceId) const override - { - return nullptr; - } -}; - -DummyJsBackendEngineLoader::DummyJsBackendEngineLoader() = default; -DummyJsBackendEngineLoader::~DummyJsBackendEngineLoader() = default; - -JsBackendEngineLoader& GetJsBackendEngineLoader(const char* sharedLibrary) -{ - CHECK_NULL_RETURN(sharedLibrary, DummyJsBackendEngineLoader::GetInstance()); - void* handle = dlopen(sharedLibrary, RTLD_LAZY); - if (handle == nullptr) { - LOGE("Failed to open shared library %{public}s, reason: %{public}sn", sharedLibrary, dlerror()); - return DummyJsBackendEngineLoader::GetInstance(); - } - - auto entry = reinterpret_cast(dlsym(handle, BACKEND_ENGINE_ENTRY)); - if (entry == nullptr) { - dlclose(handle); - LOGE("Failed to get symbol %{public}s in %{public}s", BACKEND_ENGINE_ENTRY, sharedLibrary); - return DummyJsBackendEngineLoader::GetInstance(); - } - - auto loader = reinterpret_cast(entry()); - if (loader == nullptr) { - dlclose(handle); - LOGE("Failed to get js engine loader in %{public}s", sharedLibrary); - return DummyJsBackendEngineLoader::GetInstance(); - } - - return *loader; -} - -} // namespace - -JsBackendEngineLoader& JsBackendEngineLoader::Get(const char* sharedLibrary) -{ - static JsBackendEngineLoader& instance = GetJsBackendEngineLoader(sharedLibrary); - return instance; -} - -} // namespace OHOS::Ace diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/common/js_backend_engine_loader.h b/ace_engine/adapter/fangtian/entrance/pa_engine/engine/common/js_backend_engine_loader.h deleted file mode 100644 index 4bf430309..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/common/js_backend_engine_loader.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_COMMON_JS_BACKEND_ENGINE_LOADER_H -#define FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_COMMON_JS_BACKEND_ENGINE_LOADER_H - -#include "adapter/ohos/entrance/pa_engine/engine/common/js_backend_engine.h" - -namespace OHOS::Ace { - -class JsBackendEngineLoader { -public: - virtual ~JsBackendEngineLoader() = default; - - static JsBackendEngineLoader& Get(const char* sharedLibrary); - - virtual RefPtr CreateJsBackendEngine(int32_t instanceId) const = 0; -}; - -} // namespace OHOS::Ace - -#endif // FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_COMMON_JS_BACKEND_ENGINE_LOADER_H diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/common/js_backend_timer_module.cpp b/ace_engine/adapter/fangtian/entrance/pa_engine/engine/common/js_backend_timer_module.cpp deleted file mode 100644 index 266b6b580..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/common/js_backend_timer_module.cpp +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "js_backend_timer_module.h" - -#include "base/log/log.h" - -namespace OHOS::Ace { -namespace { -template -inline T* ConvertNativeValueTo(NativeValue* value) -{ - return (value != nullptr) ? static_cast(value->GetInterface(T::INTERFACE_ID)) : nullptr; -} - -void BindNativeFunction(NativeEngine& engine, NativeObject& object, const char* name, - const char* moduleName, NativeCallback func) -{ - std::string fullName(moduleName); - fullName += "."; - fullName += name; - object.SetProperty(name, engine.CreateFunction(fullName.c_str(), fullName.length(), func, nullptr)); -} - -NativeValue* SetCallbackTimer(NativeEngine& engine, NativeCallbackInfo& info, bool isInterval) -{ - // Parameter check, must have at least 2 params - if (info.argc < 2 || info.argv[0]->TypeOf() != NATIVE_FUNCTION || info.argv[1]->TypeOf() != NATIVE_NUMBER) { - LOGE("Set callback timer failed with invalid parameter."); - return engine.CreateUndefined(); - } - - // Parse parameter - std::shared_ptr func(engine.CreateReference(info.argv[0], 1)); - int64_t delayTime = *ConvertNativeValueTo(info.argv[1]); - std::vector> params; - for (size_t index = 2; index < info.argc; ++index) { - params.emplace_back(std::shared_ptr(engine.CreateReference(info.argv[index], 1))); - } - - // Get callbackId - uint32_t callbackId = JsBackendTimerModule::GetInstance()->AddCallBack(func, params, &engine); - - // Post task - JsBackendTimerModule::GetInstance()->PostTimerCallback(callbackId, delayTime, isInterval, true, &engine); - - return engine.CreateNumber(callbackId); -} - -NativeValue* ClearCallbackTimer(NativeEngine& engine, NativeCallbackInfo& info) -{ - // parameter check, must have at least 1 param - if (info.argc < 1 || info.argv[0]->TypeOf() != NATIVE_NUMBER) { - LOGE("Clear callback timer failed with invalid parameter."); - return engine.CreateUndefined(); - } - - uint32_t callbackId = *ConvertNativeValueTo(info.argv[0]); - JsBackendTimerModule::GetInstance()->RemoveTimerCallback(callbackId); - return engine.CreateUndefined(); -} - -NativeValue* SetTimeout(NativeEngine* engine, NativeCallbackInfo* info) -{ - if (engine == nullptr || info == nullptr) { - LOGE("Set timeout failed with engine or callback info is nullptr."); - return nullptr; - } - - return SetCallbackTimer(*engine, *info, false); -} - -NativeValue* SetInterval(NativeEngine* engine, NativeCallbackInfo* info) -{ - if (engine == nullptr || info == nullptr) { - LOGE("Set interval failed with engine or callback info is nullptr."); - return nullptr; - } - - return SetCallbackTimer(*engine, *info, true); -} - -NativeValue* ClearTimeoutOrInterval(NativeEngine* engine, NativeCallbackInfo* info) -{ - if (engine == nullptr || info == nullptr) { - LOGE("Clear timer failed with engine or callback info is nullptr."); - return nullptr; - } - - return ClearCallbackTimer(*engine, *info); -} -} // namespace - -void JsBackendTimerModule::TimerCallback(uint32_t callbackId, int64_t delayTime, bool isInterval) -{ - std::shared_ptr func; - std::vector> params; - NativeEngine* engine = nullptr; - if (!GetCallBackById(callbackId, func, params, &engine)) { - return; - } - - if (!engine) { - LOGE("engine is nullptr."); - return; - } - - std::vector argc; - argc.reserve(params.size()); - for (auto arg : params) { - argc.emplace_back(arg->Get()); - } - - engine->CallFunction(engine->CreateUndefined(), func->Get(), argc.data(), argc.size()); - - if (isInterval) { - PostTimerCallback(callbackId, delayTime, isInterval, false, engine); - } else { - RemoveTimerCallback(callbackId); - } -} - -void JsBackendTimerModule::PostTimerCallback(uint32_t callbackId, int64_t delayTime, bool isInterval, bool isFirst, - NativeEngine* engine) -{ - std::lock_guard lock(mutex_); - if (!isFirst) { - auto taskNode = timeoutTaskMap_.find(callbackId); - if (taskNode == timeoutTaskMap_.end()) { - LOGE("Post timer callback failed, callbackId %{public}u not found.", callbackId); - return; - } - } - - // CancelableCallback class can only be executed once. - CancelableCallback cancelableTimer; - cancelableTimer.Reset([callbackId, delayTime, isInterval] { - JsBackendTimerModule::GetInstance()->TimerCallback(callbackId, delayTime, isInterval); - }); - auto result = timeoutTaskMap_.try_emplace(callbackId, cancelableTimer); - if (!result.second) { - result.first->second = cancelableTimer; - } - - RefPtr delegate = GetDelegateWithoutLock(engine); - if (delegate) { - delegate->PostDelayedJsTask(cancelableTimer, delayTime); - } -} - -void JsBackendTimerModule::RemoveTimerCallback(uint32_t callbackId) -{ - std::lock_guard lock(mutex_); - if (callbackNodeMap_.find(callbackId) != callbackNodeMap_.end()) { - callbackNodeMap_.erase(callbackId); - } - - auto timeoutNode = timeoutTaskMap_.find(callbackId); - if (timeoutNode != timeoutTaskMap_.end()) { - timeoutNode->second.Cancel(); - timeoutTaskMap_.erase(callbackId); - } -} - -uint32_t JsBackendTimerModule::AddCallBack(const std::shared_ptr& func, - const std::vector>& params, NativeEngine* engine) -{ - std::lock_guard lock(mutex_); - ++callbackId_; - callbackNodeMap_[callbackId_].func = func; - callbackNodeMap_[callbackId_].params = params; - callbackNodeMap_[callbackId_].engine = engine; - return callbackId_; -} - -bool JsBackendTimerModule::GetCallBackById(uint32_t callbackId, std::shared_ptr& func, - std::vector>& params, NativeEngine** engine) -{ - std::lock_guard lock(mutex_); - auto taskNode = callbackNodeMap_.find(callbackId); - if (taskNode == callbackNodeMap_.end()) { - LOGE("Get callback failed, callbackId %{public}u not found.", callbackId); - return false; - } - - func = taskNode->second.func; - params = taskNode->second.params; - *engine = taskNode->second.engine; - return true; -} - -JsBackendTimerModule* JsBackendTimerModule::GetInstance() -{ - static JsBackendTimerModule instance; - return &instance; -} - -RefPtr JsBackendTimerModule::GetDelegateWithoutLock(NativeEngine* engine) -{ - auto delegateNode = delegateMap_.find(engine); - if (delegateNode == delegateMap_.end()) { - LOGE("Get delegate failed."); - return nullptr; - } - - return delegateNode->second; -} - -void JsBackendTimerModule::AddDelegate(NativeEngine* engine, const RefPtr& delegate) -{ - std::lock_guard lock(mutex_); - delegateMap_[engine] = delegate; -} - -void JsBackendTimerModule::InitTimerModule(NativeEngine* engine, const RefPtr& delegate) -{ - if (engine == nullptr || delegate == nullptr) { - LOGE("InitTimerModule failed with engine or delegate is nullptr."); - return; - } - - AddDelegate(engine, delegate); - - NativeObject* globalObject = ConvertNativeValueTo(engine->GetGlobal()); - if (!globalObject) { - LOGE("Failed to get global object."); - return; - } - - const char *moduleName = "JsBackendTimer"; - BindNativeFunction(*engine, *globalObject, "setTimeout", moduleName, SetTimeout); - BindNativeFunction(*engine, *globalObject, "setInterval", moduleName, SetInterval); - BindNativeFunction(*engine, *globalObject, "clearTimeout", moduleName, ClearTimeoutOrInterval); - BindNativeFunction(*engine, *globalObject, "clearInterval", moduleName, ClearTimeoutOrInterval); -} -} // namespace OHOS::Ace \ No newline at end of file diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/common/js_backend_timer_module.h b/ace_engine/adapter/fangtian/entrance/pa_engine/engine/common/js_backend_timer_module.h deleted file mode 100644 index bbc9fa646..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/common/js_backend_timer_module.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_COMMON_JS_BACKEND_TIMER_MODULE_H -#define FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_COMMON_JS_BACKEND_TIMER_MODULE_H - -#include -#include - -#include "adapter/ohos/entrance/pa_engine/backend_delegate.h" -#include "base/thread/cancelable_callback.h" -#include "native_engine/native_engine.h" - -namespace OHOS::Ace { -struct TimerCallbackNode { - std::shared_ptr func; - std::vector> params; - NativeEngine* engine; -}; - -class JsBackendTimerModule final { -public: - JsBackendTimerModule() = default; - ~JsBackendTimerModule() = default; - - static JsBackendTimerModule* GetInstance(); - void InitTimerModule(NativeEngine* engine, const RefPtr& delegate); - - uint32_t AddCallBack(const std::shared_ptr& func, - const std::vector>& params, NativeEngine* engine); - bool GetCallBackById(uint32_t callbackId, std::shared_ptr& func, - std::vector>& params, NativeEngine** engine); - void TimerCallback(uint32_t callbackId, int64_t delayTime, bool isInterval); - void PostTimerCallback(uint32_t callbackId, int64_t delayTime, bool isInterval, bool isFirst, NativeEngine* engine); - void RemoveTimerCallback(uint32_t callbackId); - -private: - void AddDelegate(NativeEngine* engine, const RefPtr& delegate); - RefPtr GetDelegateWithoutLock(NativeEngine* engine); - - std::mutex mutex_; - uint32_t callbackId_ = 0; - std::unordered_map callbackNodeMap_; - std::unordered_map> timeoutTaskMap_; - std::unordered_map> delegateMap_; -}; -} // namespace OHOS::Ace - -#endif // FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_COMMON_JS_BACKEND_TIMER_MODULE_H diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/BUILD.gn b/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/BUILD.gn deleted file mode 100644 index 895b0978e..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/BUILD.gn +++ /dev/null @@ -1,137 +0,0 @@ -# Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") -import("//build/ohos.gni") -import("//foundation/arkui/ace_engine/ace_config.gni") -import("//foundation/arkui/ace_engine/build/ace_gen_obj.gni") - -base_output_path = get_label_info(":gen_abc_proxyclass", "target_out_dir") -abcproxyclass_obj_path = base_output_path + "/abc_pamgmt_class.o" - -es2abc_gen_abc("gen_paMgmt_abc") { - extra_visibility = [ ":*" ] # Only targets in this file can depend on this. - src_js = rebase_path( - "//foundation/arkui/ace_engine/adapter/ohos/entrance/pa_engine/engine/jsi/paMgmt.js") - dst_file = rebase_path(base_output_path + "/paMgmt.abc") - - in_puts = [ "//foundation/arkui/ace_engine/adapter/ohos/entrance/pa_engine/engine/jsi/paMgmt.js" ] - out_puts = [ base_output_path + "/paMgmt.abc" ] -} - -gen_obj("abc_proxyclass") { - input = base_output_path + "/paMgmt.abc" - if (use_mac) { - abcproxyclass_obj_path = base_output_path + "/abc_pamgmt_class.c" - } - output = abcproxyclass_obj_path - snapshot_dep = [ ":gen_paMgmt_abc" ] -} - -template("js_pa_engine_ark") { - forward_variables_from(invoker, "*") - - ohos_source_set(target_name) { - subsystem_name = ace_engine_subsystem - part_name = ace_engine_part - defines += invoker.defines - - configs = [ - "$ace_root:ace_config", - "$ark_runtime_path/libpandabase:arkbase_public_config", - "//arkcompiler/ets_runtime:ark_jsruntime_public_config", - ] - - include_dirs = [ - "$ability_runtime_inner_api_path/ability_manager/include", - "$ability_runtime_path/interfaces/kits/native/ability/native", - "$ability_runtime_services_path/common/include", - "$ability_runtime_services_path/abilitymgr/include", - "$ability_runtime_napi_path/context", - "$ability_runtime_napi_path/inner/napi_common", - "//foundation/arkui/ace_engine/adapter/ohos/entrance/pa_engine/engine/common", - ] - deps = [ - "$ability_runtime_napi_path/inner/napi_common:napi_common", - "$ability_runtime_path/frameworks/native/ability/native:abilitykit_native", - "$ability_runtime_path/frameworks/native/appkit:appkit_native", - "//arkcompiler/ets_runtime:libark_jsruntime", - "//foundation/arkui/napi:ace_napi", - "//foundation/arkui/napi:ace_napi_ark", - "//foundation/systemabilitymgr/safwk/interfaces/innerkits/safwk:system_ability_fwk", - "//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", - ] - external_deps = [ - "ability_base:want", - "ability_base:zuri", - "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", - "c_utils:utils", - "eventhandler:libeventhandler", - "form_fwk:form_manager", - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "ipc_js:rpc", - "napi:ace_napi", - "relational_store:native_dataability", - "relational_store:native_rdb", - ] - - public_deps = - [ "//base/global/resource_management/frameworks/resmgr:global_resmgr" ] - - sources = [ - "$ace_root/adapter/ohos/entrance/pa_engine/engine/common/js_backend_timer_module.cpp", - "$ace_root/frameworks/bridge/js_frontend/engine/jsi/ark_js_runtime.cpp", - "$ace_root/frameworks/bridge/js_frontend/engine/jsi/ark_js_value.cpp", - "$ace_root/frameworks/bridge/js_frontend/engine/jsi/jsi_base_utils.cpp", - "jsi_pa_engine.cpp", - "jsi_pa_engine_loader.cpp", - ] - - defines += [ "PA_SUPPORT" ] - - deps += [ ":gen_obj_src_abc_proxyclass" ] - - if (target_cpu == "arm64") { - defines += [ "APP_USE_ARM64" ] - } else if (target_cpu == "arm") { - defines += [ "APP_USE_ARM" ] - } - } -} - -foreach(item, ace_platforms) { - platform = item.name - engine_config = { - } - engine_config = item.config - support_engines = [] - support_engines = engine_config.js_engines - foreach(engine, support_engines) { - if (engine.engine_name == "ark") { - js_pa_engine_ark("js_pa_engine_bridge_ark_$platform") { - defines = engine.engine_defines - config = { - } - - if (defined(item.config)) { - config = item.config - } - if (defined(config.defines)) { - defines += config.defines - } - } - } - } -} diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/jsi_pa_engine.cpp b/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/jsi_pa_engine.cpp deleted file mode 100644 index ce10b7e0d..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/jsi_pa_engine.cpp +++ /dev/null @@ -1,1570 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "adapter/ohos/entrance/pa_engine/engine/jsi/jsi_pa_engine.h" - -#include - -#include "form_provider_info.h" -#include "js_backend_timer_module.h" -#include "napi/native_node_api.h" -#include "napi_common_ability.h" -#include "napi_common_want.h" -#include "napi_remote_object.h" - -#include "base/log/ace_trace.h" -#include "base/log/event_report.h" -#include "base/log/log.h" -#include "frameworks/bridge/js_frontend/engine/common/runtime_constants.h" -#include "frameworks/bridge/js_frontend/engine/jsi/ark_js_value.h" -#include "frameworks/bridge/js_frontend/engine/jsi/jsi_base_utils.h" - -extern const char _binary_paMgmt_abc_start[]; -extern const char _binary_paMgmt_abc_end[]; - -namespace OHOS::Ace { -namespace { -#ifdef APP_USE_ARM -const std::string ARK_DEBUGGER_LIB_PATH = "/system/lib/libark_debugger.z.so"; -#else -const std::string ARK_DEBUGGER_LIB_PATH = "/system/lib64/libark_debugger.z.so"; -#endif - -bool UnwrapRawImageDataMap(NativeEngine* engine, NativeValue* argv, std::map& rawImageDataMap) -{ - LOGI("%{public}s called.", __func__); - auto env = reinterpret_cast(engine); - auto param = reinterpret_cast(argv); - - if (!AppExecFwk::IsTypeForNapiValue(env, param, napi_object)) { - LOGW("%{public}s failed, param is not napi_object.", __func__); - return false; - } - - napi_valuetype jsValueType = napi_undefined; - napi_value jsProNameList = nullptr; - uint32_t jsProCount = 0; - - NAPI_CALL_BASE(env, napi_get_property_names(env, param, &jsProNameList), false); - NAPI_CALL_BASE(env, napi_get_array_length(env, jsProNameList, &jsProCount), false); - LOGI("%{public}s called. Property size=%{public}d.", __func__, jsProCount); - - napi_value jsProName = nullptr; - napi_value jsProValue = nullptr; - for (uint32_t index = 0; index < jsProCount; index++) { - NAPI_CALL_BASE(env, napi_get_element(env, jsProNameList, index, &jsProName), false); - std::string strProName = AppExecFwk::UnwrapStringFromJS(env, jsProName); - LOGI("%{public}s called. Property name=%{public}s.", __func__, strProName.c_str()); - NAPI_CALL_BASE(env, napi_get_named_property(env, param, strProName.c_str(), &jsProValue), false); - NAPI_CALL_BASE(env, napi_typeof(env, jsProValue, &jsValueType), false); - int natValue = AppExecFwk::UnwrapInt32FromJS(env, jsProValue); - rawImageDataMap.emplace(strProName, natValue); - LOGI("%{public}s called. Property value=%{public}d.", __func__, natValue); - } - return true; -} - -// native implementation for js function: Particle.onCreateFinish() -shared_ptr JsOnCreateFinish(const shared_ptr& runtime, const shared_ptr& thisObj, - const std::vector>& argv, int32_t argc) -{ - LOGD("JsOnCreateFinish"); - return runtime->NewUndefined(); -} - -// native implementation for js function: Particle.JsHandleCallback() -shared_ptr JsHandleCallback(const shared_ptr& runtime, const shared_ptr& thisObj, - const std::vector>& argv, int32_t argc) -{ - LOGI("JsHandleCallback"); - if (argc != 2) { - LOGE("the arg is error"); - return runtime->NewUndefined(); - } - std::string callbackId = argv[0]->ToString(runtime); - std::string result = argv[1]->ToString(runtime); - - auto engineInstance = static_cast(runtime->GetEmbedderData()); - if (engineInstance == nullptr) { - LOGE("engineInstance is nullptr"); - return runtime->NewUndefined(); - } - auto delegate = engineInstance->GetDelegate(); - if (delegate == nullptr) { - LOGE("delegate is nullptr"); - return runtime->NewUndefined(); - } - delegate->SetCallBackResult(std::string(callbackId), result); - - return runtime->NewUndefined(); -} - -// native implementation for js function: Particle.JsRunLoopOnce() -shared_ptr JsRunLoopOnce(const shared_ptr& runtime, const shared_ptr& thisObj, - const std::vector>& argv, int32_t argc) -{ - LOGD("JsRunLoopOnce"); - auto engineInstance = static_cast(runtime->GetEmbedderData()); - if (engineInstance == nullptr) { - LOGE("engineInstance is nullptr"); - return runtime->NewUndefined(); - } - auto nativeEngine = engineInstance->GetArkNativeEngine(); - if (nativeEngine == nullptr) { - LOGE("nativeEngine is nullptr"); - return runtime->NewUndefined(); - } - - nativeEngine->Loop(LOOP_ONCE); - runtime->ExecutePendingJob(); - return runtime->NewUndefined(); -} - -// native implementation for js function: Particle.JsRunMicrotasks() -shared_ptr JsRunMicrotasks(const shared_ptr& runtime, const shared_ptr& thisObj, - const std::vector>& argv, int32_t argc) -{ - LOGD("JsRunMicrotasks"); - runtime->ExecutePendingJob(); - return runtime->NewUndefined(); -} - -shared_ptr AsyncFuncCallBack(const shared_ptr& runtime, const shared_ptr& thisObj, - const std::vector>& argv, int32_t argc) -{ - LOGI("AsyncFuncCallBack"); - auto engineInstance = static_cast(runtime->GetEmbedderData()); - if (engineInstance == nullptr) { - LOGE("engineInstance is nullptr"); - return runtime->NewUndefined(); - } - if (argc != 2) { - LOGE("args length is error"); - engineInstance->SetBlockWaiting(true); - engineInstance->SetAsyncResult(runtime->NewUndefined()); - return runtime->NewUndefined(); - } - int32_t code = argv[0]->ToInt32(runtime); - if (code != 0) { - LOGE("AsyncFuncCallBack error code: %{public}d", code); - } - engineInstance->SetBlockWaiting(true); - engineInstance->SetAsyncResult(argv[1]); - return runtime->NewUndefined(); -} - -inline std::string ToJSONStringInt(std::string sKey, std::string sValue) -{ - char szDoubleQuotes[] = "\""; - char szColon[] = ":"; - std::string strResult; - strResult.append(szDoubleQuotes); - strResult.append(sKey); - strResult.append(szDoubleQuotes); - - strResult.append(szColon); - strResult.append(sValue); - return strResult; -} -} // namespace - -JsiPaEngineInstance::~JsiPaEngineInstance() -{ - if (runtime_) { - runtime_->RegisterUncaughtExceptionHandler(nullptr); - runtime_->Reset(); - } - runtime_.reset(); - runtime_ = nullptr; -} - -void JsiPaEngineInstance::RegisterConsoleModule() -{ - ACE_SCOPED_TRACE("JsiPaEngineInstance::RegisterConsoleModule"); - LOGD("JsiPaEngineInstance RegisterConsoleModule"); - shared_ptr global = runtime_->GetGlobal(); - - // app log method - shared_ptr consoleObj = runtime_->NewObject(); - consoleObj->SetProperty(runtime_, "log", runtime_->NewFunction(JsiBaseUtils::AppInfoLogPrint)); - consoleObj->SetProperty(runtime_, "debug", runtime_->NewFunction(JsiBaseUtils::AppDebugLogPrint)); - consoleObj->SetProperty(runtime_, "info", runtime_->NewFunction(JsiBaseUtils::AppInfoLogPrint)); - consoleObj->SetProperty(runtime_, "warn", runtime_->NewFunction(JsiBaseUtils::AppWarnLogPrint)); - consoleObj->SetProperty(runtime_, "error", runtime_->NewFunction(JsiBaseUtils::AppErrorLogPrint)); - global->SetProperty(runtime_, "console", consoleObj); -} - -void JsiPaEngineInstance::RegisterConsoleModule(ArkNativeEngine* engine) -{ - ACE_SCOPED_TRACE("JsiEngineInstance::RegisterConsoleModule"); - LOGD("JsiEngineInstance RegisterConsoleModule to nativeEngine"); - NativeValue* global = engine->GetGlobal(); - if (global->TypeOf() != NATIVE_OBJECT) { - LOGE("global is not NativeObject"); - return; - } - auto nativeGlobal = reinterpret_cast(global->GetInterface(NativeObject::INTERFACE_ID)); - - // app log method - NativeValue* console = engine->CreateObject(); - auto consoleObj = reinterpret_cast(console->GetInterface(NativeObject::INTERFACE_ID)); - consoleObj->SetProperty("log", engine->CreateFunction("log", strlen("log"), AppInfoLogPrint, nullptr)); - consoleObj->SetProperty("debug", engine->CreateFunction("debug", strlen("debug"), AppDebugLogPrint, nullptr)); - consoleObj->SetProperty("info", engine->CreateFunction("info", strlen("info"), AppInfoLogPrint, nullptr)); - consoleObj->SetProperty("warn", engine->CreateFunction("warn", strlen("warn"), AppWarnLogPrint, nullptr)); - consoleObj->SetProperty("error", engine->CreateFunction("error", strlen("error"), AppErrorLogPrint, nullptr)); - nativeGlobal->SetProperty("console", console); -} - -void JsiPaEngineInstance::RegisterPaModule() -{ - ACE_SCOPED_TRACE("JsiPaEngineInstance::RegisterAceModule"); - LOGD("JsiPaEngineInstance RegisterAceModule"); - - shared_ptr aceObj = runtime_->NewObject(); - if (!aceObj) { - LOGE("RegisterPaModule failed. aceObj is null"); - return; - } - if (!aceObj->SetProperty(runtime_, "onCreateFinish", runtime_->NewFunction(JsOnCreateFinish))) { - LOGE("RegisterPaModule onCreateFinish failed."); - } - if (!aceObj->SetProperty(runtime_, "handleCallback", runtime_->NewFunction(JsHandleCallback))) { - LOGE("RegisterPaModule handleCallback failed."); - } - if (!aceObj->SetProperty(runtime_, "runLoopOnce", runtime_->NewFunction(JsRunLoopOnce))) { - LOGE("RegisterPaModule runLoopOnce failed."); - } - if (!aceObj->SetProperty(runtime_, "runMicrotasks", runtime_->NewFunction(JsRunMicrotasks))) { - LOGE("RegisterPaModule runMicrotasks failed."); - } - - shared_ptr global = runtime_->GetGlobal(); - if (!global->SetProperty(runtime_, "Particle", aceObj)) { - LOGE("RegisterPaModule ace failed."); - } -} - -void JsiPaEngineInstance::EvaluateJsCode() -{ - ACE_SCOPED_TRACE("JsiPaEngineInstance::EvaluateJsCode"); - LOGD("JsiPaEngineInstance EvaluateJsCode"); - - // load jsfwk - if (!runtime_->ExecuteJsBin("/system/etc/strip.native.min.abc")) { - LOGE("Failed to load js framework!"); - } - - // load paMgmt.js - bool result = - runtime_->EvaluateJsCode((uint8_t*)_binary_paMgmt_abc_start, _binary_paMgmt_abc_end - _binary_paMgmt_abc_start); - if (!result) { - LOGE("EvaluateJsCode paMgmt abc failed"); - } -} - -bool JsiPaEngineInstance::InitJsEnv(bool debuggerMode, const std::unordered_map& extraNativeObject) -{ - ACE_SCOPED_TRACE("JsiPaEngineInstance::InitJsEnv"); - runtime_.reset(new ArkJSRuntime()); - if (runtime_ == nullptr) { - LOGE("JsiPaEngineInstance cannot allocate JSI JSRuntime"); - EventReport::SendJsException(JsExcepType::JS_ENGINE_INIT_ERR); - return false; - } - - runtime_->SetLogPrint(PrintLog); - std::string libraryPath = ""; - if (debuggerMode) { - libraryPath = ARK_DEBUGGER_LIB_PATH; - SetDebuggerPostTask(); - } - if (!runtime_->Initialize(libraryPath, isDebugMode_, instanceId_)) { - LOGE("JsiPaEngineInstance initialize runtime failed"); - return false; - } - -#if !defined(PREVIEW) - for (const auto& [key, value] : extraNativeObject) { - shared_ptr nativeValue = runtime_->NewNativePointer(value); - runtime_->GetGlobal()->SetProperty(runtime_, key, nativeValue); - } -#endif - - // Register pa native functions - RegisterPaModule(); - RegisterConsoleModule(); - // load abc file - EvaluateJsCode(); - - runtime_->SetEmbedderData(this); - runtime_->RegisterUncaughtExceptionHandler(JsiBaseUtils::ReportJsErrorEvent); - LOGI("JsiPaEngineInstance InitJsEnv success"); - return true; -} - -bool JsiPaEngineInstance::FireJsEvent(const std::string& eventStr) -{ - LOGD("JsiPaEngineInstance FireJsEvent"); - - shared_ptr global = runtime_->GetGlobal(); - shared_ptr func = global->GetProperty(runtime_, "callJS"); - if (!func->IsFunction(runtime_)) { - LOGE("\"callJS\" is not a function!"); - return false; - } - - const std::vector>& argv = { runtime_->ParseJson(eventStr) }; - func->Call(runtime_, global, argv, argv.size()); - return true; -} - -void JsiPaEngineInstance::CallJs(const std::string& callbackId, const std::string& args, bool keepAlive, bool isGlobal) -{ - LOGI("JsiPaEngineInstance CallJs"); - std::string keepAliveStr = keepAlive ? "true" : "false"; - std::string callBuff = std::string("[{\"args\": [\"") - .append(callbackId) - .append("\",") - .append(args) - .append(",") - .append(keepAliveStr) - .append("], \"method\":\"callback\"}]"); - LOGD("CallJs string: %{private}s", callBuff.c_str()); - - std::vector> argv; - argv.push_back(runtime_->NewString(std::to_string(instanceId_))); - argv.push_back(runtime_->ParseJson(callBuff)); - - shared_ptr global = runtime_->GetGlobal(); - shared_ptr func = global->GetProperty(runtime_, "callJS"); - if (!func->IsFunction(runtime_)) { - LOGE("\"callJs\" is not a function!"); - return; - } - func->Call(runtime_, global, argv, argv.size()); -} - -bool JsiPaEngineInstance::CallPlatformFunction(const std::string& channel, std::vector&& data, int32_t id) -{ - auto dispatcher = dispatcher_.Upgrade(); - if (dispatcher) { - dispatcher->Dispatch(channel, std::move(data), id); - return true; - } else { - LOGW("Dispatcher Upgrade fail when dispatch request message to platform"); - return false; - } -} - -bool JsiPaEngineInstance::PluginErrorCallback(int32_t callbackId, int32_t errorCode, std::string&& errorMessage) -{ - auto dispatcher = dispatcher_.Upgrade(); - if (dispatcher) { - dispatcher->DispatchPluginError(callbackId, errorCode, std::move(errorMessage)); - return true; - } else { - LOGW("Dispatcher Upgrade fail when dispatch error message to platform"); - return false; - } -} - -RefPtr JsiPaEngineInstance::GetDelegate() const -{ - return backendDelegate_; -} - -std::shared_ptr JsiPaEngineInstance::GetJsRuntime() const -{ - return runtime_; -} - -void JsiPaEngineInstance::SetJsMessageDispatcher(const RefPtr& dispatcher) -{ - dispatcher_ = dispatcher; -} - -void JsiPaEngineInstance::SetArkNativeEngine(ArkNativeEngine* nativeEngine) -{ - nativeEngine_ = nativeEngine; -} - -ArkNativeEngine* JsiPaEngineInstance::GetArkNativeEngine() const -{ - return nativeEngine_; -} - -void JsiPaEngineInstance::SetDebuggerPostTask() -{ - auto weakDelegate = AceType::WeakClaim(AceType::RawPtr(backendDelegate_)); - auto&& postTask = [weakDelegate](std::function&& task) { - auto delegate = weakDelegate.Upgrade(); - if (delegate == nullptr) { - LOGE("delegate is nullptr"); - return; - } - delegate->PostJsTask(std::move(task)); - }; - std::static_pointer_cast(runtime_)->SetDebuggerPostTask(postTask); -} - -// ----------------------- -// Start JsiPaEngine -// ----------------------- -JsiPaEngine::~JsiPaEngine() -{ - UnloadLibrary(); - engineInstance_->GetDelegate()->RemoveTaskObserver(); - if (nativeEngine_ != nullptr) { -#if !defined(PREVIEW) - nativeEngine_->CancelCheckUVLoop(); -#endif - nativeEngine_->DeleteEngine(); - delete nativeEngine_; - } -} - -void JsiPaEngine::RegisterWorker() -{ - RegisterInitWorkerFunc(); - RegisterAssetFunc(); -} - -void JsiPaEngine::RegisterInitWorkerFunc() -{ - auto weakInstance = AceType::WeakClaim(AceType::RawPtr(engineInstance_)); - auto&& initWorkerFunc = [weak = AceType::WeakClaim(this), weakInstance](NativeEngine* nativeEngine) { - LOGI("WorkerCore RegisterInitWorkerFunc called"); - auto paEngine = weak.Upgrade(); - if (nativeEngine == nullptr) { - LOGE("nativeEngine is nullptr"); - return; - } - auto arkNativeEngine = static_cast(nativeEngine); - if (arkNativeEngine == nullptr) { - LOGE("arkNativeEngine is nullptr"); - return; - } - auto instance = weakInstance.Upgrade(); - if (instance == nullptr) { - LOGE("instance is nullptr"); - return; - } - - auto runtime = instance->GetJsRuntime(); - - instance->RegisterConsoleModule(arkNativeEngine); - -#if !defined(PREVIEW) - for (const auto& [key, value] : paEngine->GetExtraNativeObject()) { - shared_ptr nativeValue = runtime->NewNativePointer(value); - runtime->GetGlobal()->SetProperty(runtime, key, nativeValue); - } -#endif - // load jsfwk - if (!arkNativeEngine->ExecuteJsBin("/system/etc/strip.native.min.abc")) { - LOGE("Failed to load js framework!"); - } - }; - nativeEngine_->SetInitWorkerFunc(initWorkerFunc); -} - -void JsiPaEngine::RegisterAssetFunc() -{ - auto weakDelegate = AceType::WeakClaim(AceType::RawPtr(engineInstance_->GetDelegate())); - auto&& assetFunc = [weakDelegate](const std::string& uri, std::vector& content, std::string& ami) { - LOGI("WorkerCore RegisterAssetFunc called"); - auto delegate = weakDelegate.Upgrade(); - if (delegate == nullptr) { - LOGE("delegate is nullptr"); - return; - } - size_t index = uri.find_last_of("."); - if (index == std::string::npos) { - LOGE("invalid uri"); - } else { - delegate->GetResourceData(uri.substr(0, index) + ".abc", content, ami); - } - }; - nativeEngine_->SetGetAssetFunc(assetFunc); -} - -bool JsiPaEngine::Initialize(const RefPtr& delegate) -{ - ACE_SCOPED_TRACE("JsiPaEngine::Initialize"); - LOGD("JsiPaEngine initialize"); - engineInstance_ = AceType::MakeRefPtr(delegate, instanceId_); - engineInstance_->SetDebugMode(NeedDebugBreakPoint()); - bool result = engineInstance_->InitJsEnv(IsDebugVersion(), GetExtraNativeObject()); - if (!result) { - LOGE("JsiPaEngine Initialize, init js env failed"); - return false; - } - - auto runtime = engineInstance_->GetJsRuntime(); - auto vm = std::static_pointer_cast(runtime)->GetEcmaVm(); - if (vm == nullptr) { - LOGE("JsiPaEngine Initialize, vm is null"); - return false; - } - - LoadLibrary(); - - nativeEngine_ = new ArkNativeEngine(const_cast(vm), static_cast(this)); - engineInstance_->SetArkNativeEngine(nativeEngine_); - ACE_DCHECK(delegate); - delegate->AddTaskObserver([nativeEngine = nativeEngine_, id = instanceId_]() { - ContainerScope scope(id); - nativeEngine->Loop(LOOP_NOWAIT); - }); - JsBackendTimerModule::GetInstance()->InitTimerModule(nativeEngine_, delegate); - SetPostTask(nativeEngine_); -#if !defined(PREVIEW) - nativeEngine_->CheckUVLoop(); -#endif - if (delegate && delegate->GetAssetManager()) { - std::vector packagePath = delegate->GetAssetManager()->GetLibPath(); - auto appLibPathKey = delegate->GetAssetManager()->GetAppLibPathKey(); - if (!packagePath.empty()) { - auto arkNativeEngine = static_cast(nativeEngine_); - arkNativeEngine->SetPackagePath(appLibPathKey, packagePath); - } - } - RegisterWorker(); - return true; -} - -void JsiPaEngine::SetPostTask(NativeEngine* nativeEngine) -{ - LOGD("SetPostTask"); - auto weakDelegate = AceType::WeakClaim(AceType::RawPtr(engineInstance_->GetDelegate())); - auto&& postTask = [weakDelegate, nativeEngine = nativeEngine_, id = instanceId_](bool needSync) { - auto delegate = weakDelegate.Upgrade(); - if (delegate == nullptr) { - LOGE("delegate is nullptr"); - return; - } - delegate->PostJsTask([nativeEngine, needSync, id]() { - ContainerScope scope(id); - if (nativeEngine == nullptr) { - return; - } - nativeEngine->Loop(LOOP_NOWAIT, needSync); - }); - }; - nativeEngine_->SetPostTask(postTask); -} - -void JsiPaEngine::LoadJs(const std::string& url, const OHOS::AAFwk::Want& want) -{ - ACE_SCOPED_TRACE("JsiPaEngine::LoadJs"); - LOGI("JsiPaEngine LoadJs: %{private}s", url.c_str()); - - ACE_DCHECK(engineInstance_); - auto runtime = engineInstance_->GetJsRuntime(); - auto delegate = engineInstance_->GetDelegate(); - - // js file to abc file and execute abc file - const char js_ext[] = ".js"; - const char bin_ext[] = ".abc"; - auto pos = url.rfind(js_ext); - if (pos != std::string::npos && pos == url.length() - (sizeof(js_ext) - 1)) { - std::string urlName = url.substr(0, pos) + bin_ext; - LOGI("GetAssetContent: %{public}s", urlName.c_str()); - std::vector content; - if (!delegate->GetAssetContent(urlName, content)) { - LOGE("GetAssetContent \"%{public}s\" failed.", urlName.c_str()); - return; - } - std::string abcPath = delegate->GetAssetPath(urlName).append(urlName); - if (!runtime->EvaluateJsCode(content.data(), content.size(), abcPath)) { - LOGE("EvaluateJsCode \"%{public}s\" failed.", urlName.c_str()); - return; - } - - // only ace1.0 need - shared_ptr mainEntryFunc = runtime->GetGlobal()->GetProperty(runtime, "___mainEntry___"); - if (mainEntryFunc->IsFunction(runtime)) { - LOGI("JsiPaEngine call mainEntryFunc"); - runtime->GetGlobal()->SetProperty(runtime, "___mainEntry___", runtime->NewUndefined()); - const std::vector>& argv = { runtime->GetGlobal() }; - shared_ptr retVal = CallFunc(mainEntryFunc, argv); - auto arkJSRuntime = std::static_pointer_cast(runtime); - if (arkJSRuntime->HasPendingException()) { - LOGE("JsiPaEngine call mainEntryFunc FAILED!"); - } - } - } - - // call start pa func - BackendType type = delegate->GetType(); - if (type == BackendType::SERVICE) { - StartService(); - } else if (type == BackendType::DATA) { - StartData(); - } else if (type == BackendType::FORM) { - LOGI("Form Ability LoadJS finish."); - } else { - LOGE("backend type not support"); - } -} - -void JsiPaEngine::LoadLibrary() -{ -#ifdef APP_USE_ARM - const char* rdbPath = "/system/lib/module/data/librdb.z.so"; -#else - const char* rdbPath = "/system/lib64/module/data/librdb.z.so"; -#endif - if (strlen(rdbPath) == 0) { - LOGE("module path is empty"); - return; - } - - libRdb_ = dlopen(rdbPath, RTLD_LAZY); - if (libRdb_ == nullptr) { - LOGE("dlopen failed: %{public}s", dlerror()); - } - - rdbValueBucketNewInstance_ = reinterpret_cast( - dlsym(libRdb_, "NAPI_OHOS_Data_RdbJsKit_ValuesBucketProxy_NewInstance")); - if (rdbValueBucketNewInstance_ == nullptr) { - LOGE("symbol not found: %{public}s", dlerror()); - } - - rdbValueBucketGetNativeObject_ = reinterpret_cast( - dlsym(libRdb_, "NAPI_OHOS_Data_RdbJsKit_ValuesBucketProxy_GetNativeObject")); - if (rdbValueBucketGetNativeObject_ == nullptr) { - LOGE("symbol not found: %{public}s", dlerror()); - } - - rdbResultSetProxyNewInstance_ = reinterpret_cast( - dlsym(libRdb_, "NAPI_OHOS_Data_RdbJsKit_ResultSetProxy_NewInstance")); - if (rdbResultSetProxyNewInstance_ == nullptr) { - LOGE("symbol not found: %{public}s", dlerror()); - } - - rdbResultSetProxyGetNativeObject_ = reinterpret_cast( - dlsym(libRdb_, "NAPI_OHOS_Data_RdbJsKit_ResultSetProxy_GetNativeObject")); - if (rdbResultSetProxyGetNativeObject_ == nullptr) { - LOGE("symbol not found: %{public}s", dlerror()); - } - -#ifdef APP_USE_ARM - const char* dataAbilityPath = "/system/lib/module/data/libdataability.z.so"; -#else - const char* dataAbilityPath = "/system/lib64/module/data/libdataability.z.so"; -#endif - if (strlen(dataAbilityPath) == 0) { - LOGE("module path is empty"); - return; - } - - libDataAbility_ = dlopen(dataAbilityPath, RTLD_LAZY); - if (libDataAbility_ == nullptr) { - LOGE("dlopen failed: %{public}s", dlerror()); - } - - dataAbilityPredicatesNewInstance_ = reinterpret_cast( - dlsym(libDataAbility_, "NAPI_OHOS_Data_DataAbilityJsKit_DataAbilityPredicatesProxy_NewInstance")); - if (dataAbilityPredicatesNewInstance_ == nullptr) { - LOGE("symbol not found: %{public}s", dlerror()); - } - - dataAbilityPredicatesGetNativeObject_ = reinterpret_cast( - dlsym(libDataAbility_, "NAPI_OHOS_Data_DataAbilityJsKit_DataAbilityPredicatesProxy_GetNativeObject")); - if (dataAbilityPredicatesGetNativeObject_ == nullptr) { - LOGE("symbol not found: %{public}s", dlerror()); - } -} - -void JsiPaEngine::UnloadLibrary() -{ - dlclose(libRdb_); - dlclose(libDataAbility_); -} - -shared_ptr JsiPaEngine::GetPaFunc(const std::string& funcName) -{ - LOGI("JsiPaEngine GetPaFunc funcName: %{public}s", funcName.c_str()); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - ACE_DCHECK(runtime); - shared_ptr global = runtime->GetGlobal(); - shared_ptr exportsObject = global->GetProperty(runtime, "exports"); - if (!exportsObject->IsObject(runtime)) { - LOGE("property \"exports\" is not a object"); - return nullptr; - } - shared_ptr defaultObject = exportsObject->GetProperty(runtime, "default"); - if (!defaultObject->IsObject(runtime)) { - LOGE("property \"default\" is not a object"); - return nullptr; - } - - shared_ptr func = defaultObject->GetProperty(runtime, funcName); - if (!func->IsFunction(runtime)) { - LOGE("%{public}s not found or is not a function!", funcName.c_str()); - return nullptr; - } - return func; -} - -shared_ptr JsiPaEngine::CallFunc(const shared_ptr& func) -{ - const std::vector>& argv = {}; - return CallFunc(func, argv); -} - -shared_ptr JsiPaEngine::CallFunc(const shared_ptr& func, const std::vector>& argv) -{ - LOGD("JsiPaEngine CallFunc"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - ACE_DCHECK(runtime); - if (func == nullptr) { - LOGE("func is nullptr!"); - return runtime->NewUndefined(); - } - if (!func->IsFunction(runtime)) { - LOGE("func is not a function!"); - return runtime->NewUndefined(); - } - shared_ptr global = runtime->GetGlobal(); - return func->Call(runtime, global, argv, argv.size()); -} - -shared_ptr JsiPaEngine::CallFunc( - const shared_ptr& func, const std::vector>& argv, const CallingInfo& callingInfo) -{ - LOGD("JsiPaEngine CallFunc"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - ACE_DCHECK(runtime); - if (func == nullptr) { - LOGE("func is nullptr!"); - return runtime->NewUndefined(); - } - if (!func->IsFunction(runtime)) { - LOGE("func is not a function!"); - return runtime->NewUndefined(); - } - shared_ptr global = runtime->GetGlobal(); - - napi_env env = reinterpret_cast(nativeEngine_); - NAPI_CallingInfo oldCallingInfo; - NAPI_RemoteObject_saveOldCallingInfo(env, oldCallingInfo); - NAPI_RemoteObject_setNewCallingInfo(env, callingInfo); - NAPI_RemoteObject_resetOldCallingInfo(env, oldCallingInfo); - - return func->Call(runtime, global, argv, argv.size()); -} - -shared_ptr JsiPaEngine::CallAsyncFunc( - const shared_ptr& func, std::vector>& argv, const CallingInfo& callingInfo) -{ - LOGD("JsiPaEngine CallAsyncFunc"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - ACE_DCHECK(runtime); - if (func == nullptr) { - LOGE("func is nullptr!"); - return runtime->NewUndefined(); - } - if (!func->IsFunction(runtime)) { - LOGE("func is not a function!"); - return runtime->NewUndefined(); - } - shared_ptr global = runtime->GetGlobal(); - - napi_env env = reinterpret_cast(nativeEngine_); - NAPI_CallingInfo oldCallingInfo; - NAPI_RemoteObject_saveOldCallingInfo(env, oldCallingInfo); - NAPI_RemoteObject_setNewCallingInfo(env, callingInfo); - - argv.push_back(runtime->NewFunction(AsyncFuncCallBack)); - - engineInstance_->SetBlockWaiting(false); - func->Call(runtime, global, argv, argv.size()); - runtime->ExecutePendingJob(); - while (!engineInstance_->GetBlockWaiting()) { - nativeEngine_->Loop(LOOP_ONCE); - runtime->ExecutePendingJob(); - } - NAPI_RemoteObject_resetOldCallingInfo(env, oldCallingInfo); - LOGD("JsiPaEngine CallAsyncFunc end"); - return engineInstance_->GetAsyncResult(); -} - -shared_ptr JsiPaEngine::NativeValueToJsValue(NativeValue* nativeValue) -{ - ACE_DCHECK(engineInstance_); - if (nativeValue == nullptr) { - LOGE("nativeValue is nullptr!"); - return engineInstance_->GetJsRuntime()->NewUndefined(); - } - Global globalRef = *nativeValue; - auto arkRuntime = std::static_pointer_cast(engineInstance_->GetJsRuntime()); - return std::make_shared(arkRuntime, globalRef.ToLocal(arkRuntime->GetEcmaVm())); -} - -shared_ptr JsiPaEngine::WantToJsValue(const OHOS::AAFwk::Want& want) -{ - napi_value napiWant = OHOS::AppExecFwk::WrapWant(reinterpret_cast(nativeEngine_), want); - NativeValue* nativeWant = reinterpret_cast(napiWant); - return NativeValueToJsValue(nativeWant); -} - -void JsiPaEngine::StartService() -{ - LOGI("JsiPaEngine StartService"); - auto func = GetPaFunc("onStart"); - CallFunc(func); -} - -void JsiPaEngine::StartData() -{ - LOGI("JsiPaEngine StartData"); - - const auto& nativeObjects = GetExtraNativeObject(); - auto it = nativeObjects.find("ability"); - if (it == nativeObjects.end() || it->second == nullptr) { - LOGE("Can't find ability object"); - return; - } - - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - - const std::shared_ptr abilityInfo = - reinterpret_cast(it->second)->GetAbilityInfo(); - const AppExecFwk::AbilityInfo abilityInfoInstance = *(abilityInfo.get()); - napi_value abilityInfoNapi = - AppExecFwk::ConvertAbilityInfo(reinterpret_cast(nativeEngine_), abilityInfoInstance); - NativeValue* abilityInfoNative = reinterpret_cast(abilityInfoNapi); - const std::vector>& argv = { NativeValueToJsValue(abilityInfoNative) }; - - auto func = GetPaFunc("onInitialized"); - CallFunc(func, argv); -} - -RefPtr JsiPaEngine::GetGroupJsBridge() -{ - return nullptr; -} - -void JsiPaEngine::SetJsMessageDispatcher(const RefPtr& dispatcher) -{ - ACE_DCHECK(engineInstance_); - engineInstance_->SetJsMessageDispatcher(dispatcher); -} - -void JsiPaEngine::FireAsyncEvent(const std::string& eventId, const std::string& param) -{ - LOGD("JsiPaEngine FireAsyncEvent"); - std::string callBuf = std::string("[{\"args\": [\"") - .append(eventId) - .append("\",") - .append(param) - .append("], \"method\":\"fireEvent\"}]"); - LOGD("FireASyncEvent string: %{private}s", callBuf.c_str()); - - ACE_DCHECK(engineInstance_); - if (!engineInstance_->FireJsEvent(callBuf.c_str())) { - LOGE("Js Engine FireSyncEvent FAILED!"); - } -} - -void JsiPaEngine::FireSyncEvent(const std::string& eventId, const std::string& param) -{ - LOGD("JsiPaEngine FireSyncEvent"); - std::string callBuf = std::string("[{\"args\": [\"") - .append(eventId) - .append("\",") - .append(param) - .append("], \"method\":\"fireEventSync\"}]"); - LOGD("FireSyncEvent string: %{private}s", callBuf.c_str()); - - ACE_DCHECK(engineInstance_); - if (!engineInstance_->FireJsEvent(callBuf.c_str())) { - LOGE("Js Engine FireSyncEvent FAILED!"); - } -} - -void JsiPaEngine::DestroyApplication(const std::string& packageName) -{ - LOGI("JsiPaEngine DestroyApplication"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - const std::vector>& argv = { runtime->NewString(packageName) }; - auto func = GetPaFunc("onStop"); - CallFunc(func, argv); -} - -void JsiPaEngine::OnCommandApplication(const std::string& intent, int startId) -{ - LOGI("JsiPaEngine OnCommandApplication"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - const std::vector>& argv = { runtime->NewString(intent), runtime->NewInt32(startId) }; - auto func = GetPaFunc("onCommand"); - CallFunc(func, argv); -} - -int32_t JsiPaEngine::Insert(const Uri& uri, const OHOS::NativeRdb::ValuesBucket& value, const CallingInfo& callingInfo) -{ - LOGI("JsiPaEngine Insert"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - napi_env env = reinterpret_cast(nativeEngine_); - napi_value argNapiValue = rdbValueBucketNewInstance_(env, const_cast(value)); - NativeValue* argNapiNativeValue = reinterpret_cast(argNapiValue); - std::vector> argv; - argv.push_back(runtime->NewString(uri.ToString())); - argv.push_back(NativeValueToJsValue(argNapiNativeValue)); - auto func = GetPaFunc("insert"); - shared_ptr retVal = CallAsyncFunc(func, argv, callingInfo); - - auto arkJSRuntime = std::static_pointer_cast(runtime); - if (arkJSRuntime->HasPendingException()) { - LOGE("JsiPaEngine Insert FAILED!"); - return 0; - } - auto arkJSValue = std::static_pointer_cast(retVal); - return arkJSValue->ToInt32(runtime); -} - -std::string JsiPaEngine::ExcludeTag(const std::string& jsonString, const std::string& tagString) -{ - size_t pos = jsonString.find(tagString); - if (pos == std::string::npos) { - return jsonString; - } - std::string valueString = jsonString.substr(pos); - pos = valueString.find(":"); - if (pos == std::string::npos) { - return ""; - } - size_t valuePos = pos + 1; - while (valuePos < valueString.size()) { - if (valueString.at(valuePos) != ' ' && valueString.at(valuePos) != '\t') { - break; - } - valuePos++; - } - if (valuePos >= valueString.size()) { - return ""; - } - valueString = valueString.substr(valuePos); - return valueString.substr(0, valueString.size() - 1); -} - -std::string JsiPaEngine::IncludeTag(const std::string& jsonString, const std::string& tagString) -{ - std::string result = "{\"" + tagString + "\":"; - result += jsonString; - result += "}"; - return result; -} - -std::shared_ptr JsiPaEngine::Call( - const std::string& method, const std::string& arg, const AppExecFwk::PacMap& pacMap, const CallingInfo& callingInfo) -{ - LOGD("JsiPaEngine Call"); - ACE_DCHECK(engineInstance_); - - std::string pacString = const_cast(pacMap).ToString(); - std::string params = ExcludeTag(pacString, "pacmap"); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - std::vector> argv; - argv.push_back(runtime->NewString(method)); - argv.push_back(runtime->NewString(arg)); - argv.push_back(runtime->NewString(params)); - auto func = GetPaFunc("call"); - if (func == nullptr) { - return nullptr; - } - shared_ptr retVal = CallFunc(func, argv, callingInfo); - auto arkJSRuntime = std::static_pointer_cast(runtime); - if (arkJSRuntime->HasPendingException()) { - LOGE("JsiPaEngine Query FAILED!"); - return nullptr; - } - auto arkJSValue = std::static_pointer_cast(retVal); - if (arkJSValue->IsUndefined(runtime)) { - LOGE("JsiPaEngine Query return value is undefined!"); - return nullptr; - } - std::string retStr = IncludeTag(arkJSValue->ToString(runtime), "pacmap"); - auto result = std::make_shared(); - if (result == nullptr) { - LOGE("fail to create PacMap"); - return nullptr; - } - result->FromString(retStr); - LOGD("JsiPaEngine Call End: %{public}s", result->ToString().c_str()); - return result; -} - -int32_t JsiPaEngine::BatchInsert( - const Uri& uri, const std::vector& values, const CallingInfo& callingInfo) -{ - LOGI("JsiPaEngine BatchInsert"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - - napi_env env = reinterpret_cast(nativeEngine_); - napi_value argColumnsNapiValue = nullptr; - napi_create_array(env, &argColumnsNapiValue); - bool isArray = false; - if (napi_is_array(env, argColumnsNapiValue, &isArray) != napi_ok || !isArray) { - LOGE("JsiPaEngine create array failed"); - return 0; - } - int32_t index = 0; - for (auto value : values) { - napi_value result = rdbValueBucketNewInstance_(env, const_cast(value)); - napi_set_element(env, argColumnsNapiValue, index++, result); - } - NativeValue* argColumnsNativeValue = reinterpret_cast(argColumnsNapiValue); - - std::vector> argv; - argv.push_back(runtime->NewString(uri.ToString())); - argv.push_back(NativeValueToJsValue(argColumnsNativeValue)); - auto func = GetPaFunc("batchInsert"); - shared_ptr retVal = CallAsyncFunc(func, argv, callingInfo); - auto arkJSRuntime = std::static_pointer_cast(runtime); - if (arkJSRuntime->HasPendingException()) { - LOGE("JsiPaEngine BatchInsert FAILED!"); - return 0; - } - auto arkJSValue = std::static_pointer_cast(retVal); - return arkJSValue->ToInt32(runtime); -} - -std::shared_ptr JsiPaEngine::Query(const Uri& uri, - const std::vector& columns, const OHOS::NativeRdb::DataAbilityPredicates& predicates, - const CallingInfo& callingInfo) -{ - LOGI("JsiPaEngine Query"); - ACE_DCHECK(engineInstance_); - std::shared_ptr resultSet = nullptr; - shared_ptr runtime = engineInstance_->GetJsRuntime(); - - napi_env env = reinterpret_cast(nativeEngine_); - napi_value argColumnsNapiValue = nullptr; - napi_create_array(env, &argColumnsNapiValue); - bool isArray = false; - if (napi_is_array(env, argColumnsNapiValue, &isArray) != napi_ok || !isArray) { - LOGE("JsiPaEngine create array failed"); - return resultSet; - } - int32_t index = 0; - for (auto column : columns) { - napi_value result = nullptr; - napi_create_string_utf8(env, column.c_str(), column.length(), &result); - napi_set_element(env, argColumnsNapiValue, index++, result); - } - NativeValue* argColumnsNativeValue = reinterpret_cast(argColumnsNapiValue); - - OHOS::NativeRdb::DataAbilityPredicates* predicatesPtr = new OHOS::NativeRdb::DataAbilityPredicates(); - *predicatesPtr = predicates; - napi_value argPredicatesNapiValue = dataAbilityPredicatesNewInstance_(env, predicatesPtr); - NativeValue* argPredicatesNativeValue = reinterpret_cast(argPredicatesNapiValue); - if (argPredicatesNativeValue == nullptr) { - LOGE("JsiPaEngine Query argPredicatesNativeValue is nullptr"); - return resultSet; - } - - std::vector> argv; - argv.push_back(runtime->NewString(uri.ToString())); - argv.push_back(NativeValueToJsValue(argColumnsNativeValue)); - argv.push_back(NativeValueToJsValue(argPredicatesNativeValue)); - auto func = GetPaFunc("query"); - shared_ptr retVal = CallAsyncFunc(func, argv, callingInfo); - - auto arkJSRuntime = std::static_pointer_cast(runtime); - if (arkJSRuntime->HasPendingException()) { - LOGE("JsiPaEngine Query FAILED!"); - return resultSet; - } - auto arkJSValue = std::static_pointer_cast(retVal); - if (arkJSValue->IsUndefined(runtime)) { - LOGE("JsiPaEngine Query return value is undefined!"); - return resultSet; - } - - NativeValue* nativeValue = - ArkNativeEngine::ArkValueToNativeValue(nativeEngine_, arkJSValue->GetValue(arkJSRuntime)); - if (nativeValue == nullptr) { - LOGE("JsiPaEngine nativeValue is nullptr"); - return resultSet; - } - auto nativeObject = rdbResultSetProxyGetNativeObject_(env, reinterpret_cast(nativeValue)); - if (nativeObject == nullptr) { - LOGE("JsiPaEngine AbsSharedResultSet from JS to Native failed"); - return resultSet; - } - - resultSet.reset(nativeObject); - return resultSet; -} - -int32_t JsiPaEngine::Update(const Uri& uri, const OHOS::NativeRdb::ValuesBucket& value, - const OHOS::NativeRdb::DataAbilityPredicates& predicates, const CallingInfo& callingInfo) -{ - LOGI("JsiPaEngine Update"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - - napi_env env = reinterpret_cast(nativeEngine_); - napi_value argNapiValue = rdbValueBucketNewInstance_(env, const_cast(value)); - NativeValue* argNapiNativeValue = reinterpret_cast(argNapiValue); - - OHOS::NativeRdb::DataAbilityPredicates* predicatesPtr = new OHOS::NativeRdb::DataAbilityPredicates(); - *predicatesPtr = predicates; - napi_value argPredicatesNapiValue = dataAbilityPredicatesNewInstance_(env, predicatesPtr); - NativeValue* argPredicatesNativeValue = reinterpret_cast(argPredicatesNapiValue); - if (argPredicatesNativeValue == nullptr) { - LOGE("JsiPaEngine Update argPredicatesNativeValue is nullptr"); - return 0; - } - - std::vector> argv; - argv.push_back(runtime->NewString(uri.ToString())); - argv.push_back(NativeValueToJsValue(argNapiNativeValue)); - argv.push_back(NativeValueToJsValue(argPredicatesNativeValue)); - auto func = GetPaFunc("update"); - shared_ptr retVal = CallAsyncFunc(func, argv, callingInfo); - - auto arkJSRuntime = std::static_pointer_cast(runtime); - if (arkJSRuntime->HasPendingException()) { - LOGE("JsiPaEngine Update FAILED!"); - return 0; - } - auto arkJSValue = std::static_pointer_cast(retVal); - return arkJSValue->ToInt32(runtime); -} - -int32_t JsiPaEngine::Delete( - const Uri& uri, const OHOS::NativeRdb::DataAbilityPredicates& predicates, const CallingInfo& callingInfo) -{ - LOGI("JsiPaEngine Delete"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - - napi_env env = reinterpret_cast(nativeEngine_); - OHOS::NativeRdb::DataAbilityPredicates* predicatesPtr = new OHOS::NativeRdb::DataAbilityPredicates(); - *predicatesPtr = predicates; - napi_value argPredicatesNapiValue = dataAbilityPredicatesNewInstance_(env, predicatesPtr); - NativeValue* argPredicatesNativeValue = reinterpret_cast(argPredicatesNapiValue); - if (argPredicatesNativeValue == nullptr) { - LOGE("JsiPaEngine Delete argPredicatesNativeValue is nullptr"); - return 0; - } - - std::vector> argv; - argv.push_back(runtime->NewString(uri.ToString())); - argv.push_back(NativeValueToJsValue(argPredicatesNativeValue)); - auto func = GetPaFunc("delete"); - shared_ptr retVal = CallAsyncFunc(func, argv, callingInfo); - - auto arkJSRuntime = std::static_pointer_cast(runtime); - if (arkJSRuntime->HasPendingException()) { - LOGE("JsiPaEngine Delete FAILED!"); - return 0; - } - auto arkJSValue = std::static_pointer_cast(retVal); - return arkJSValue->ToInt32(runtime); -} - -std::string JsiPaEngine::GetType(const Uri& uri, const CallingInfo& callingInfo) -{ - LOGD("JsiPaEngine GetType"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - std::vector> argv; - argv.push_back(runtime->NewString(uri.ToString())); - auto func = GetPaFunc("getType"); - shared_ptr retVal = CallAsyncFunc(func, argv, callingInfo); - - auto arkJSRuntime = std::static_pointer_cast(runtime); - if (arkJSRuntime->HasPendingException()) { - LOGE("JsiPaEngine GetType FAILED!"); - return std::string(); - } - auto arkJSValue = std::static_pointer_cast(retVal); - return arkJSValue->ToString(runtime); -} - -std::vector JsiPaEngine::GetFileTypes( - const Uri& uri, const std::string& mimeTypeFilter, const CallingInfo& callingInfo) -{ - LOGD("JsiPaEngine GetFileTypes"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - std::vector> argv; - argv.push_back(runtime->NewString(uri.ToString())); - argv.push_back(runtime->NewString(mimeTypeFilter)); - auto func = GetPaFunc("getFileTypes"); - shared_ptr retVal = CallAsyncFunc(func, argv, callingInfo); - - std::vector ret; - auto arkJSRuntime = std::static_pointer_cast(runtime); - if (arkJSRuntime->HasPendingException()) { - LOGE("JsiPaEngine GetFileTypes FAILED!"); - return ret; - } - auto arkJSValue = std::static_pointer_cast(retVal); - if (!arkJSValue->IsArray(runtime)) { - LOGE("JsiPaEngine GetFileTypes return not array!"); - return ret; - } - int32_t length = arkJSValue->GetArrayLength(runtime); - LOGI("JsiPaEngine GetFileTypes array length %{public}d", length); - for (int i = 0; i < length; i++) { - auto itemVal = arkJSValue->GetProperty(runtime, i); - ret.push_back(itemVal->ToString(runtime)); - } - return ret; -} - -int32_t JsiPaEngine::OpenFile(const Uri& uri, const std::string& mode, const CallingInfo& callingInfo) -{ - LOGI("JsiPaEngine OpenFile"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - std::vector> argv; - argv.push_back(runtime->NewString(uri.ToString())); - argv.push_back(runtime->NewString(mode)); - auto func = GetPaFunc("openFile"); - shared_ptr retVal = CallAsyncFunc(func, argv, callingInfo); - - auto arkJSRuntime = std::static_pointer_cast(runtime); - if (arkJSRuntime->HasPendingException()) { - LOGE("JsiPaEngine OpenFile FAILED!"); - return 0; - } - auto arkJSValue = std::static_pointer_cast(retVal); - return arkJSValue->ToInt32(runtime); -} - -int32_t JsiPaEngine::OpenRawFile(const Uri& uri, const std::string& mode, const CallingInfo& callingInfo) -{ - LOGI("JsiPaEngine OpenRawFile"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - std::vector> argv; - argv.push_back(runtime->NewString(uri.ToString())); - argv.push_back(runtime->NewString(mode)); - auto func = GetPaFunc("openRawFile"); - shared_ptr retVal = CallAsyncFunc(func, argv, callingInfo); - - auto arkJSRuntime = std::static_pointer_cast(runtime); - if (arkJSRuntime->HasPendingException()) { - LOGE("JsiPaEngine OpenRawFile FAILED!"); - return 0; - } - auto arkJSValue = std::static_pointer_cast(retVal); - return arkJSValue->ToInt32(runtime); -} - -Uri JsiPaEngine::NormalizeUri(const Uri& uri, const CallingInfo& callingInfo) -{ - LOGI("JsiPaEngine NormalizeUri"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - std::vector> argv; - argv.push_back(runtime->NewString(uri.ToString())); - auto func = GetPaFunc("normalizeUri"); - shared_ptr retVal = CallAsyncFunc(func, argv, callingInfo); - - auto arkJSRuntime = std::static_pointer_cast(runtime); - if (arkJSRuntime->HasPendingException()) { - LOGE("JsiPaEngine NormalizeUri FAILED!"); - return Uri(""); - } - auto arkJSValue = std::static_pointer_cast(retVal); - return Uri(arkJSValue->ToString(runtime)); -} - -Uri JsiPaEngine::DenormalizeUri(const Uri& uri, const CallingInfo& callingInfo) -{ - LOGI("JsiPaEngine DenormalizeUri"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - std::vector> argv; - argv.push_back(runtime->NewString(uri.ToString())); - auto func = GetPaFunc("denormalizeUri"); - shared_ptr retVal = CallAsyncFunc(func, argv, callingInfo); - - auto arkJSRuntime = std::static_pointer_cast(runtime); - if (arkJSRuntime->HasPendingException()) { - LOGE("JsiPaEngine DenormalizeUri FAILED!"); - return Uri(""); - } - auto arkJSValue = std::static_pointer_cast(retVal); - return Uri(arkJSValue->ToString(runtime)); -} - -sptr JsiPaEngine::OnConnectService(const OHOS::AAFwk::Want& want) -{ - ContainerScope scope(instanceId_); - LOGI("JsiPaEngine OnConnectService"); - ACE_DCHECK(engineInstance_); - auto arkJSRuntime = std::static_pointer_cast(engineInstance_->GetJsRuntime()); - const std::vector>& argv = { WantToJsValue(want) }; - auto func = GetPaFunc("onConnect"); - shared_ptr retVal = CallFunc(func, argv); - - if (arkJSRuntime->HasPendingException()) { - LOGE("JsiPaEngine onConnectService FAILED!"); - return nullptr; - } - - auto arkJSValue = std::static_pointer_cast(retVal); - NativeValue* nativeValue = - ArkNativeEngine::ArkValueToNativeValue(nativeEngine_, arkJSValue->GetValue(arkJSRuntime)); - if (nativeValue == nullptr) { - LOGE("JsiPaEngine nativeValue is nullptr"); - return nullptr; - } - auto remoteObj = NAPI_ohos_rpc_getNativeRemoteObject( - reinterpret_cast(nativeEngine_), reinterpret_cast(nativeValue)); - return remoteObj; -} - -void JsiPaEngine::OnDisconnectService(const OHOS::AAFwk::Want& want) -{ - ContainerScope scope(instanceId_); - LOGI("JsiPaEngine OnDisconnectService"); - const std::vector>& argv = { WantToJsValue(want) }; - auto func = GetPaFunc("onDisconnect"); - CallFunc(func, argv); -} - -void JsiPaEngine::OnCommand(const OHOS::AAFwk::Want& want, int startId) -{ - ContainerScope scope(instanceId_); - LOGI("JsiPaEngine OnCommand"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - const std::vector>& argv = { WantToJsValue(want), runtime->NewInt32(startId) }; - auto func = GetPaFunc("onCommand"); - CallFunc(func, argv); -} - -void JsiPaEngine::OnCreate(const OHOS::AAFwk::Want& want) -{ - ContainerScope scope(instanceId_); - LOGI("JsiPaEngine OnCreate"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - - const std::vector>& argv = { WantToJsValue(want) }; - auto func = GetPaFunc("onCreate"); - auto result = CallFunc(func, argv); - auto arkJSRuntime = std::static_pointer_cast(runtime); - if (arkJSRuntime->HasPendingException()) { - LOGE("JsiPaEngine CallFunc FAILED!"); - return; - } - - auto arkJSValue = std::static_pointer_cast(result); - shared_ptr propertyNames; - int32_t len = 0; - if (!arkJSValue->GetPropertyNames(runtime, propertyNames, len)) { - LOGE("JsiPaEngine StartForm GetPropertyNames error"); - return; - } - LOGD("JsiPaEngine onCreate return property num %{public}d", len); - - std::string jsonStr; - shared_ptr formJsonData = arkJSValue->GetProperty(runtime, "data"); - if (formJsonData != nullptr) { - jsonStr = formJsonData->ToString(runtime); - LOGI("Add FormBindingData json:%{public}s", jsonStr.c_str()); - } - AppExecFwk::FormProviderData formData = AppExecFwk::FormProviderData(jsonStr); - shared_ptr formImageData = arkJSValue->GetProperty(runtime, "image"); - if (formImageData != nullptr) { - std::map rawImageDataMap; - auto arkJSRuntime = std::static_pointer_cast(runtime); - NativeValue* nativeValue = ArkNativeEngine::ArkValueToNativeValue( - nativeEngine_, std::static_pointer_cast(formImageData)->GetValue(arkJSRuntime)); - UnwrapRawImageDataMap(nativeEngine_, nativeValue, rawImageDataMap); - for (const auto& data : rawImageDataMap) { - formData.AddImageData(data.first, data.second); - } - } - SetFormData(formData); -} - -void JsiPaEngine::OnDelete(const int64_t formId) -{ - LOGI("JsiPaEngine OnDelete"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - const std::vector>& argv = { runtime->NewString(std::to_string(formId)) }; - auto func = GetPaFunc("onDestroy"); - CallFunc(func, argv); -} - -void JsiPaEngine::OnTriggerEvent(const int64_t formId, const std::string& message) -{ - LOGI("JsiPaEngine OnTriggerEvent"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - const std::vector>& argv = { runtime->NewString(std::to_string(formId)), - runtime->NewString(message) }; - auto func = GetPaFunc("onEvent"); - CallFunc(func, argv); -} - -void JsiPaEngine::OnUpdate(const int64_t formId) -{ - LOGI("JsiPaEngine OnUpdate"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - const std::vector>& argv = { runtime->NewString(std::to_string(formId)) }; - auto func = GetPaFunc("onUpdate"); - CallFunc(func, argv); -} - -void JsiPaEngine::OnCastTemptoNormal(const int64_t formId) -{ - LOGD("JsiPaEngine OnCastTemptoNormal"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - const std::vector>& argv = { runtime->NewString(std::to_string(formId)) }; - auto func = GetPaFunc("onCastToNormal"); - CallFunc(func, argv); -} - -void JsiPaEngine::OnVisibilityChanged(const std::map& formEventsMap) -{ - LOGI("JsiPaEngine OnVisibilityChanged"); - ACE_DCHECK(engineInstance_); - - std::string strJsonResult("{"); - for (auto item = formEventsMap.begin(); item != formEventsMap.end(); item++) { - strJsonResult.append(ToJSONStringInt(std::to_string(item->first), std::to_string(item->second))); - strJsonResult.append(","); - } - strJsonResult = strJsonResult.substr(0, strJsonResult.size() - 1); - strJsonResult.append("}"); - LOGI("JsiPaEngine strJsonResult = %{public}s", strJsonResult.c_str()); - - shared_ptr runtime = engineInstance_->GetJsRuntime(); - const std::vector>& argv = { runtime->ParseJson(strJsonResult) }; - auto func = GetPaFunc("onVisibilityChange"); - CallFunc(func, argv); -} - -int32_t JsiPaEngine::OnAcquireFormState(const OHOS::AAFwk::Want& want) -{ - LOGI("JsiPaEngine OnAcquireFormState"); - ACE_DCHECK(engineInstance_); - shared_ptr runtime = engineInstance_->GetJsRuntime(); - - const std::vector>& argv = { WantToJsValue(want) }; - auto func = GetPaFunc("onAcquireFormState"); - - if (func == nullptr) { - LOGI("no OnAcquireFormState!"); - return (int32_t)AppExecFwk::FormState::DEFAULT; - } - - auto result = CallFunc(func, argv); - auto arkJSRuntime = std::static_pointer_cast(runtime); - if (arkJSRuntime->HasPendingException()) { - LOGE("JsiPaEngine CallFunc FAILED!"); - return (int32_t)AppExecFwk::FormState::DEFAULT; - } - - auto arkJSValue = std::static_pointer_cast(result); - if (!arkJSValue->IsInt32(runtime)) { - LOGE("invalid return value!"); - return (int32_t)AppExecFwk::FormState::DEFAULT; - } - - int32_t formState = arkJSValue->ToInt32(runtime); - LOGI("JsiPaEngine OnAcquireFormState, formState: %{public}d", formState); - return formState; -} - -bool JsiPaEngine::OnShare(int64_t formId, OHOS::AAFwk::WantParams& wantParams) -{ - LOGD("JsiPaEngine OnShare, create"); - ACE_DCHECK(engineInstance_); - auto runtime = engineInstance_->GetJsRuntime(); - if (runtime == nullptr) { - LOGE("JsiPaEngine JsRuntime Get nullptr!"); - return false; - } - - const std::vector> argv = { runtime->NewString(std::to_string(formId)) }; - auto func = GetPaFunc("onShare"); - auto result = CallFunc(func, argv); - if (result == nullptr) { - LOGE("JsiPaEngine Call function result is nullptr!"); - return false; - } - - auto arkJSValue = std::static_pointer_cast(result); - if (arkJSValue == nullptr) { - LOGE("JsiPaEngine JsValue convert failed!"); - return false; - } - - auto arkJSRuntime = std::static_pointer_cast(runtime); - if (arkJSRuntime == nullptr) { - LOGE("JsiPaEngine JSRuntime convert failed!"); - return false; - } - - if (arkJSRuntime->HasPendingException()) { - LOGE("JsiPaEngine CallFunc FAILED!"); - return false; - } - - auto nativeValue = ArkNativeEngine::ArkValueToNativeValue(nativeEngine_, arkJSValue->GetValue(arkJSRuntime)); - if (nativeValue == nullptr) { - LOGE("JsiPaEngine nativeValue convert failed!"); - return false; - } - - if (nativeValue->TypeOf() != NativeValueType::NATIVE_OBJECT) { - LOGE("%{public}s OnShare return value`s type is %{public}d", __func__, static_cast(nativeValue->TypeOf())); - return false; - } - - if (!OHOS::AppExecFwk::UnwrapWantParams( - reinterpret_cast(nativeEngine_), reinterpret_cast(nativeValue), wantParams)) { - LOGE("%{public}s OnShare UnwrapWantParams failed, return false", __func__); - return false; - } - - LOGD("JsiPaEngine OnShare, end"); - return true; -} - -void JsiPaEngine::DumpHeapSnapshot(bool isPrivate) -{ - if (engineInstance_ && engineInstance_->GetJsRuntime()) { - engineInstance_->GetJsRuntime()->DumpHeapSnapshot(isPrivate); - } -} -} // namespace OHOS::Ace diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/jsi_pa_engine.h b/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/jsi_pa_engine.h deleted file mode 100644 index 2115ec0da..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/jsi_pa_engine.h +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_JSI_JSI_PA_ENGINE_H -#define FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_JSI_JSI_PA_ENGINE_H - -#include - -#include "abs_shared_result_set.h" -#include "data_ability_predicates.h" -#include "napi/native_api.h" -#include "napi/native_node_api.h" -#include "native_engine/impl/ark/ark_native_engine.h" -#include "result_set.h" -#include "uri.h" -#include "values_bucket.h" -#include "want.h" - -#include "adapter/ohos/entrance/pa_engine/backend_delegate.h" -#include "adapter/ohos/entrance/pa_engine/engine/common/js_backend_engine.h" -#include "base/memory/ace_type.h" -#include "base/utils/noncopyable.h" -#include "core/common/js_message_dispatcher.h" -#include "frameworks/bridge/js_frontend/engine/jsi/js_runtime.h" - -namespace OHOS::Ace { - -using namespace OHOS::Ace::Framework; - -// Each JsFrontend holds only one JsiPaEngineInstance. -class JsiPaEngineInstance final : public AceType, public JsBackendEngineInstance { -public: - explicit JsiPaEngineInstance(const RefPtr& delegate, int32_t instanceId) - : backendDelegate_(delegate), instanceId_(instanceId) - {} - ~JsiPaEngineInstance() override; - - bool InitJsEnv(bool debuggerMode, const std::unordered_map& extraNativeObject); - void CallJs(const std::string& callbackId, const std::string& args, bool keepAlive = false, bool isGlobal = false); - bool FireJsEvent(const std::string& eventId); - bool CallPlatformFunction(const std::string& channel, std::vector&& data, int32_t id); - bool PluginErrorCallback(int32_t callbackId, int32_t errorCode, std::string&& errorMessage); - - RefPtr GetDelegate() const; - std::shared_ptr GetJsRuntime() const; - void SetJsMessageDispatcher(const RefPtr& dispatcher); - void SetArkNativeEngine(ArkNativeEngine* nativeEngine); - ArkNativeEngine* GetArkNativeEngine() const; - - // add Console object to worker - void RegisterConsoleModule(ArkNativeEngine* engine); - - bool GetBlockWaiting() const - { - return blockWaiting_; - } - - void SetBlockWaiting(bool blockWaiting) - { - blockWaiting_ = blockWaiting; - } - - shared_ptr GetAsyncResult() const - { - return asyncResult_; - } - - void SetAsyncResult(shared_ptr asyncResult) - { - asyncResult_ = asyncResult; - } - - void SetDebugMode(bool isDebugMode) - { - isDebugMode_ = isDebugMode; - } - -private: - void RegisterPaModule(); - void RegisterConsoleModule(); - void EvaluateJsCode(); - void SetDebuggerPostTask(); - - std::shared_ptr runtime_; - RefPtr backendDelegate_; - int32_t instanceId_ = 0; - WeakPtr dispatcher_; - ArkNativeEngine* nativeEngine_ = nullptr; - bool blockWaiting_ = false; - shared_ptr asyncResult_ = nullptr; - bool isDebugMode_ = true; - - ACE_DISALLOW_COPY_AND_MOVE(JsiPaEngineInstance); -}; - -using RdbValueBucketNewInstance = napi_value (*)(napi_env env, OHOS::NativeRdb::ValuesBucket& valueBucket); -using RdbValueBucketGetNativeObject = OHOS::NativeRdb::ValuesBucket* (*)(napi_env env, napi_value& value); -using RdbResultSetProxyNewInstance = napi_value (*)(napi_env env, OHOS::NativeRdb::AbsSharedResultSet* resultSet); -using RdbResultSetProxyGetNativeObject = OHOS::NativeRdb::AbsSharedResultSet* (*)(const napi_env& env, - const napi_value& arg); -using DataAbilityPredicatesNewInstance = napi_value (*)( - napi_env env, OHOS::NativeRdb::DataAbilityPredicates* predicates); -using DataAbilityPredicatesGetNativeObject = OHOS::NativeRdb::DataAbilityPredicates* (*)(const napi_env env, - const napi_value& arg); - -class JsiPaEngine : public JsBackendEngine { -public: - explicit JsiPaEngine(int32_t instanceId) : instanceId_(instanceId) {} - ~JsiPaEngine() override; - - bool Initialize(const RefPtr& delegate) override; - // Load and initialize a JS bundle into the JS Framework - void LoadJs(const std::string& url, const OHOS::AAFwk::Want& want) override; - // Fire AsyncEvent on JS - void FireAsyncEvent(const std::string& eventId, const std::string& param) override; - // Fire SyncEvent on JS - void FireSyncEvent(const std::string& eventId, const std::string& param) override; - - RefPtr GetGroupJsBridge() override; - void SetJsMessageDispatcher(const RefPtr& dispatcher) override; - - // destroy application instance according packageName - void DestroyApplication(const std::string& packageName) override; - void OnCommandApplication(const std::string& intent, int startId) override; - - // data - int32_t Insert(const Uri& uri, const OHOS::NativeRdb::ValuesBucket& value, const CallingInfo& callingInfo) override; - std::shared_ptr Call(const std::string& method, const std::string& arg, - const AppExecFwk::PacMap& pacMap, const CallingInfo& callingInfo) override; - - int32_t BatchInsert(const Uri& uri, const std::vector& values, - const CallingInfo& callingInfo) override; - std::shared_ptr Query(const Uri& uri, const std::vector& columns, - const OHOS::NativeRdb::DataAbilityPredicates& predicates, const CallingInfo& callingInfo) override; - int32_t Update(const Uri& uri, const OHOS::NativeRdb::ValuesBucket& value, - const OHOS::NativeRdb::DataAbilityPredicates& predicates, const CallingInfo& callingInfo) override; - int32_t Delete(const Uri& uri, const OHOS::NativeRdb::DataAbilityPredicates& predicates, - const CallingInfo& callingInfo) override; - - std::string GetType(const Uri& uri, const CallingInfo& callingInfo) override; - std::vector GetFileTypes( - const Uri& uri, const std::string& mimeTypeFilter, const CallingInfo& callingInfo) override; - int32_t OpenFile(const Uri& uri, const std::string& mode, const CallingInfo& callingInfo) override; - int32_t OpenRawFile(const Uri& uri, const std::string& mode, const CallingInfo& callingInfo) override; - Uri NormalizeUri(const Uri& uri, const CallingInfo& callingInfo) override; - Uri DenormalizeUri(const Uri& uri, const CallingInfo& callingInfo) override; - - // service - sptr OnConnectService(const OHOS::AAFwk::Want& want) override; - void OnDisconnectService(const OHOS::AAFwk::Want& want) override; - void OnCommand(const OHOS::AAFwk::Want& want, int startId) override; - - // form - void OnCreate(const OHOS::AAFwk::Want& want) override; - void OnDelete(const int64_t formId) override; - void OnTriggerEvent(const int64_t formId, const std::string& message) override; - void OnUpdate(const int64_t formId) override; - void OnCastTemptoNormal(const int64_t formId) override; - void OnVisibilityChanged(const std::map& formEventsMap) override; - int32_t OnAcquireFormState(const OHOS::AAFwk::Want& want) override; - bool OnShare(int64_t formId, OHOS::AAFwk::WantParams& wantParams) override; - void DumpHeapSnapshot(bool isPrivate) override; - -private: - void SetPostTask(NativeEngine* nativeEngine); - void LoadLibrary(); - void UnloadLibrary(); - shared_ptr GetPaFunc(const std::string& funcName); - shared_ptr CallFunc(const shared_ptr& func); - shared_ptr CallFunc(const shared_ptr& func, const std::vector>& argv); - shared_ptr CallFunc( - const shared_ptr& func, const std::vector>& argv, const CallingInfo& callingInfo); - shared_ptr CallAsyncFunc( - const shared_ptr& func, std::vector>& argv, const CallingInfo& callingInfo); - shared_ptr NativeValueToJsValue(NativeValue* nativeValue); - shared_ptr WantToJsValue(const OHOS::AAFwk::Want& want); - void StartService(); - void StartData(); - void StartForm(const OHOS::AAFwk::Want& want); - - void RegisterWorker(); - void RegisterInitWorkerFunc(); - void RegisterAssetFunc(); - - std::string ExcludeTag(const std::string& jsonString, const std::string& tagString); - std::string IncludeTag(const std::string& jsonString, const std::string& tagString); - std::shared_ptr BuildPacMap(const napi_env& env, const napi_value& arg); - void SetPacMapObject( - std::shared_ptr pacMap, const napi_env& env, std::string keyStr, napi_value value); - std::string UnwrapStringFromJS(napi_env env, napi_value param, const std::string& defaultValue = ""); - std::vector ConvertStringVector(napi_env env, napi_value jsValue); - - int32_t instanceId_ = 0; - ArkNativeEngine* nativeEngine_ = nullptr; - RefPtr engineInstance_; - - void* libRdb_ = nullptr; - void* libDataAbility_ = nullptr; - RdbValueBucketNewInstance rdbValueBucketNewInstance_ = nullptr; - RdbValueBucketGetNativeObject rdbValueBucketGetNativeObject_ = nullptr; - RdbResultSetProxyNewInstance rdbResultSetProxyNewInstance_ = nullptr; - RdbResultSetProxyGetNativeObject rdbResultSetProxyGetNativeObject_ = nullptr; - DataAbilityPredicatesNewInstance dataAbilityPredicatesNewInstance_ = nullptr; - DataAbilityPredicatesGetNativeObject dataAbilityPredicatesGetNativeObject_ = nullptr; - - ACE_DISALLOW_COPY_AND_MOVE(JsiPaEngine); -}; - -} // namespace OHOS::Ace - -#endif // FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_JSI_JSI_PA_ENGINE_H diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/jsi_pa_engine_loader.cpp b/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/jsi_pa_engine_loader.cpp deleted file mode 100644 index eff707e4f..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/jsi_pa_engine_loader.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "adapter/ohos/entrance/pa_engine/engine/jsi/jsi_pa_engine_loader.h" - -#include "adapter/ohos/entrance/pa_engine/engine/jsi/jsi_pa_engine.h" -#include "base/utils/macros.h" - -namespace OHOS::Ace { - -JsiPaEngineLoader::JsiPaEngineLoader() = default; -JsiPaEngineLoader::~JsiPaEngineLoader() = default; - -RefPtr JsiPaEngineLoader::CreateJsBackendEngine(int32_t instanceId) const -{ - return AceType::MakeRefPtr(instanceId); -} - -#if defined(BUILT_IN_JS_ENGINE) -JsBackendEngineLoader& JsBackendEngineLoader::Get(const char* sharedLibrary) -{ - return JsiPaEngineLoader::GetInstance(); -} -#else -extern "C" ACE_FORCE_EXPORT void* OHOS_ACE_GetJsBackendEngineLoader() -{ - return &JsiPaEngineLoader::GetInstance(); -} -#endif - -} // namespace OHOS::Ace diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/jsi_pa_engine_loader.h b/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/jsi_pa_engine_loader.h deleted file mode 100644 index c96354258..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/jsi_pa_engine_loader.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_JSI_JSI_PA_ENGINE_LOADER_H -#define FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_JSI_JSI_PA_ENGINE_LOADER_H - -#include "adapter/ohos/entrance/pa_engine/engine/common/js_backend_engine_loader.h" -#include "base/utils/singleton.h" - -namespace OHOS::Ace { - -class JsiPaEngineLoader : public JsBackendEngineLoader, public Singleton { - DECLARE_SINGLETON(JsiPaEngineLoader) -public: - RefPtr CreateJsBackendEngine(int32_t instanceId) const final; -}; - -} // namespace OHOS::Ace - -#endif // FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_JSI_JSI_PA_ENGINE_LOADER_H diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/jsi_pa_utils.cpp b/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/jsi_pa_utils.cpp deleted file mode 100644 index db28e45c8..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/jsi_pa_utils.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "frameworks/bridge/js_frontend/engine/jsi/jsi_base_utils.h" - -namespace OHOS::Ace::Framework { -int32_t GetLineOffset(const AceType *data) -{ - const int32_t offset = 14; - return offset; -} - -RefPtr GetRunningPage([[maybe_unused]] const AceType *data) -{ - return nullptr; -} -} // namespace OHOS::Ace::Framework diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/paMgmt.js b/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/paMgmt.js deleted file mode 100644 index a28e7e52d..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/jsi/paMgmt.js +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -function isSystemplugin(shortName, moduleType) { - const plugin = moduleType === 'ohos' ? globalThis.ohosplugin : globalThis.systemplugin; - if (typeof (plugin) !== 'undefined') { - var target = plugin; - for (let key of shortName.split('.')) { - target = target[key]; - if (!target) { - break; - } - } - return typeof (target) !== 'undefined'; - } -} - -var global = globalThis; -globalThis.exports = {default: {}}; -function $app_define$(page, packageName, parseContent) { - const module = {exports: {}}; - parseContent({}, module.exports, module); - globalThis.exports.default = module.exports; -} -function $app_bootstrap$() {}; - -console.info("PA Mgmt init success"); \ No newline at end of file diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/BUILD.gn b/ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/BUILD.gn deleted file mode 100644 index 1924f95d8..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/BUILD.gn +++ /dev/null @@ -1,140 +0,0 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//foundation/arkui/ace_engine/ace_config.gni") - -template("js_pa_engine_qjs") { - forward_variables_from(invoker, "*") - - ohos_source_set(target_name) { - subsystem_name = ace_engine_subsystem - part_name = ace_engine_part - defines += invoker.defines - - configs = [ "$ace_root:ace_config" ] - - include_dirs = [ - "$ability_runtime_inner_api_path/ability_manager/include", - "$ability_runtime_path/interfaces/kits/native/ability/native", - "$ability_runtime_services_path/common/include", - "$ability_runtime_services_path/abilitymgr/include", - "$ability_runtime_napi_path/context", - "$ability_runtime_napi_path/inner/napi_common", - "//foundation/arkui/ace_engine/adapter/ohos/entrance/pa_engine/engine/common", - ] - deps = [ - "$ability_runtime_napi_path/inner/napi_common:napi_common", - "$ability_runtime_path/frameworks/native/ability/native:abilitykit_native", - "$ability_runtime_path/frameworks/native/appkit:appkit_native", - "//foundation/arkui/napi:ace_napi", - "//foundation/systemabilitymgr/safwk/interfaces/innerkits/safwk:system_ability_fwk", - "//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", - ] - external_deps = [ - "ability_base:want", - "ability_base:zuri", - "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", - "c_utils:utils", - "eventhandler:libeventhandler", - "form_fwk:form_manager", - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "ipc_js:rpc", - "napi:ace_napi", - "relational_store:native_dataability", - "relational_store:native_rdb", - "samgr:samgr_proxy", - ] - - public_deps = - [ "//base/global/resource_management/frameworks/resmgr:global_resmgr" ] - - sources = [ - "$ace_root/adapter/ohos/entrance/pa_engine/engine/common/js_backend_timer_module.cpp", - "qjs_pa_engine.cpp", - "qjs_pa_engine_loader.cpp", - ] - - if (target_cpu == "arm64") { - defines += [ "_ARM64_" ] - } else if (target_cpu == "arm") { - defines += [ "_ARM_" ] - } - - if (use_js_debug) { - deps += [ "//third_party/quickjs:qjs_debugger" ] - defines += [ "ENABLE_JS_DEBUG" ] - configs += [ "//third_party/quickjs:qjs_debug_config" ] - } else { - deps += [ "//third_party/quickjs:qjs" ] - } - - if (defined(config.use_build_in_js_engine) && - config.use_build_in_js_engine) { - defines += [ "BUILT_IN_JS_ENGINE" ] - } else { - sources += [ - "$ace_root/frameworks/bridge/js_frontend/engine/quickjs/qjs_group_js_bridge.cpp", - "$ace_root/frameworks/bridge/js_frontend/engine/quickjs/qjs_utils.cpp", - ] - } - - if (use_js_debug) { - deps += [ "//foundation/arkui/napi:ace_napi_quickjs_debug" ] - } else { - deps += [ "//foundation/arkui/napi:ace_napi_quickjs" ] - } - } -} - -foreach(item, ace_platforms) { - platform = item.name - engine_config = { - } - engine_config = item.config - support_engines = [] - support_engines = engine_config.js_engines - foreach(engine, support_engines) { - if (engine.engine_name == "qjs") { - js_pa_engine_qjs("js_pa_engine_bridge_qjs_$platform") { - defines = engine.engine_defines - use_js_debug = false - config = { - } - - if (defined(item.config)) { - config = item.config - } - if (defined(config.defines)) { - defines += config.defines - } - } - - js_pa_engine_qjs("js_pa_engine_bridge_qjs_debug_$platform") { - defines = engine.engine_defines - use_js_debug = true - config = { - } - - if (defined(item.config)) { - config = item.config - } - if (defined(config.defines)) { - defines += config.defines - } - } - } - } -} diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/BUILD.gn.bak b/ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/BUILD.gn.bak deleted file mode 100644 index 1924f95d8..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/BUILD.gn.bak +++ /dev/null @@ -1,140 +0,0 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//foundation/arkui/ace_engine/ace_config.gni") - -template("js_pa_engine_qjs") { - forward_variables_from(invoker, "*") - - ohos_source_set(target_name) { - subsystem_name = ace_engine_subsystem - part_name = ace_engine_part - defines += invoker.defines - - configs = [ "$ace_root:ace_config" ] - - include_dirs = [ - "$ability_runtime_inner_api_path/ability_manager/include", - "$ability_runtime_path/interfaces/kits/native/ability/native", - "$ability_runtime_services_path/common/include", - "$ability_runtime_services_path/abilitymgr/include", - "$ability_runtime_napi_path/context", - "$ability_runtime_napi_path/inner/napi_common", - "//foundation/arkui/ace_engine/adapter/ohos/entrance/pa_engine/engine/common", - ] - deps = [ - "$ability_runtime_napi_path/inner/napi_common:napi_common", - "$ability_runtime_path/frameworks/native/ability/native:abilitykit_native", - "$ability_runtime_path/frameworks/native/appkit:appkit_native", - "//foundation/arkui/napi:ace_napi", - "//foundation/systemabilitymgr/safwk/interfaces/innerkits/safwk:system_ability_fwk", - "//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", - ] - external_deps = [ - "ability_base:want", - "ability_base:zuri", - "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", - "c_utils:utils", - "eventhandler:libeventhandler", - "form_fwk:form_manager", - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "ipc_js:rpc", - "napi:ace_napi", - "relational_store:native_dataability", - "relational_store:native_rdb", - "samgr:samgr_proxy", - ] - - public_deps = - [ "//base/global/resource_management/frameworks/resmgr:global_resmgr" ] - - sources = [ - "$ace_root/adapter/ohos/entrance/pa_engine/engine/common/js_backend_timer_module.cpp", - "qjs_pa_engine.cpp", - "qjs_pa_engine_loader.cpp", - ] - - if (target_cpu == "arm64") { - defines += [ "_ARM64_" ] - } else if (target_cpu == "arm") { - defines += [ "_ARM_" ] - } - - if (use_js_debug) { - deps += [ "//third_party/quickjs:qjs_debugger" ] - defines += [ "ENABLE_JS_DEBUG" ] - configs += [ "//third_party/quickjs:qjs_debug_config" ] - } else { - deps += [ "//third_party/quickjs:qjs" ] - } - - if (defined(config.use_build_in_js_engine) && - config.use_build_in_js_engine) { - defines += [ "BUILT_IN_JS_ENGINE" ] - } else { - sources += [ - "$ace_root/frameworks/bridge/js_frontend/engine/quickjs/qjs_group_js_bridge.cpp", - "$ace_root/frameworks/bridge/js_frontend/engine/quickjs/qjs_utils.cpp", - ] - } - - if (use_js_debug) { - deps += [ "//foundation/arkui/napi:ace_napi_quickjs_debug" ] - } else { - deps += [ "//foundation/arkui/napi:ace_napi_quickjs" ] - } - } -} - -foreach(item, ace_platforms) { - platform = item.name - engine_config = { - } - engine_config = item.config - support_engines = [] - support_engines = engine_config.js_engines - foreach(engine, support_engines) { - if (engine.engine_name == "qjs") { - js_pa_engine_qjs("js_pa_engine_bridge_qjs_$platform") { - defines = engine.engine_defines - use_js_debug = false - config = { - } - - if (defined(item.config)) { - config = item.config - } - if (defined(config.defines)) { - defines += config.defines - } - } - - js_pa_engine_qjs("js_pa_engine_bridge_qjs_debug_$platform") { - defines = engine.engine_defines - use_js_debug = true - config = { - } - - if (defined(item.config)) { - config = item.config - } - if (defined(config.defines)) { - defines += config.defines - } - } - } - } -} diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/qjs_pa_engine.cpp b/ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/qjs_pa_engine.cpp deleted file mode 100644 index 57fbcba93..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/qjs_pa_engine.cpp +++ /dev/null @@ -1,1590 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "adapter/ohos/entrance/pa_engine/engine/quickjs/qjs_pa_engine.h" - -#include -#include -#include -#include -#include - -#include "form_provider_info.h" -#include "js_backend_timer_module.h" -#include "napi/native_node_api.h" -#include "napi_common_ability.h" -#include "napi_common_want.h" -#include "napi_remote_object.h" -#include "third_party/quickjs/message_server.h" - -#include "base/i18n/localization.h" -#include "base/json/json_util.h" -#include "base/log/ace_trace.h" -#include "base/log/event_report.h" -#include "base/log/log.h" -#include "base/utils/linear_map.h" -#include "base/utils/system_properties.h" -#include "base/utils/time_util.h" -#include "base/utils/utils.h" -#include "core/common/ace_application_info.h" -#include "core/common/backend.h" -#include "core/common/container_scope.h" -#include "core/event/ace_event_helper.h" -#include "core/event/back_end_event_manager.h" -#include "frameworks/bridge/common/dom/dom_type.h" -#include "frameworks/bridge/common/media_query/media_query_info.h" -#include "frameworks/bridge/common/utils/utils.h" -#include "frameworks/bridge/js_frontend/engine/common/js_constants.h" -#include "frameworks/bridge/js_frontend/engine/common/runtime_constants.h" -#include "frameworks/bridge/js_frontend/engine/quickjs/qjs_utils.h" - -namespace OHOS::Ace { - -FromBindingData::FromBindingData(JSContext* ctx, JSValue value) -{ - ctx_ = ctx; - valueFromJs_ = value; -} - -void FromBindingData::Constructor(const std::string& param) -{ - JSValue paFunc = Framework::QJSUtils::GetPropertyStr(ctx_, valueFromJs_, "constructor"); - if (!JS_IsFunction(ctx_, paFunc)) { - LOGE("Constructor is not found"); - return; - } - - JSValue jsParam = Framework::QJSUtils::NewString(ctx_, param.c_str()); - JSValueConst argv[] = { jsParam }; - JS_Call(ctx_, paFunc, JS_UNDEFINED, countof(argv), argv); - js_std_loop(ctx_); - return; -} - -void FromBindingData::UpdateData(const std::string& data) -{ - JSValue paFunc = Framework::QJSUtils::GetPropertyStr(ctx_, valueFromJs_, "updateData"); - if (!JS_IsFunction(ctx_, paFunc)) { - LOGE("UpdateData is not found"); - return; - } - - JSValue param = Framework::QJSUtils::NewString(ctx_, data.c_str()); - JSValueConst argv[] = { param }; - JS_Call(ctx_, paFunc, JS_UNDEFINED, countof(argv), argv); - js_std_loop(ctx_); - return; -} - -std::string FromBindingData::GetDataString() const -{ - JSValue paFunc = Framework::QJSUtils::GetPropertyStr(ctx_, valueFromJs_, "getDataString"); - if (!JS_IsFunction(ctx_, paFunc)) { - LOGE("Constructor is not found"); - return ""; - } - - JSValueConst argv[] = {}; - JS_Call(ctx_, paFunc, JS_UNDEFINED, countof(argv), argv); - js_std_loop(ctx_); - return ""; -} - -void FromBindingData::AddImageData(const std::string& name, void* buffer) -{ - JSValue paFunc = Framework::QJSUtils::GetPropertyStr(ctx_, valueFromJs_, "addImageData"); - if (!JS_IsFunction(ctx_, paFunc)) { - LOGE("AddImageData is not found"); - return; - } - - JSValue param = Framework::QJSUtils::NewString(ctx_, name.c_str()); - JSValueConst argv[] = { param }; - JS_Call(ctx_, paFunc, JS_UNDEFINED, countof(argv), argv); - js_std_loop(ctx_); - return; -} - -void FromBindingData::RemoveImageData(const std::string& name) -{ - JSValue paFunc = Framework::QJSUtils::GetPropertyStr(ctx_, valueFromJs_, "removeImageData"); - if (!JS_IsFunction(ctx_, paFunc)) { - LOGE("RemoveImageData is not found"); - return; - } - - JSValue param = Framework::QJSUtils::NewString(ctx_, name.c_str()); - JSValueConst argv[] = { param }; - JS_Call(ctx_, paFunc, JS_UNDEFINED, countof(argv), argv); - js_std_loop(ctx_); - return; -} - -namespace { -#define JS_CFUNC_DEF_CPP(name, length, func) \ - { \ - name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, 0, \ - { \ - { \ - length, JS_CFUNC_generic, \ - { \ - func \ - } \ - } \ - } \ - } - -bool UnwrapRawImageDataMap(NativeEngine* engine, NativeValue* argv, std::map& rawImageDataMap) -{ - LOGI("%{public}s called.", __func__); - auto env = reinterpret_cast(engine); - auto param = reinterpret_cast(argv); - - if (!AppExecFwk::IsTypeForNapiValue(env, param, napi_object)) { - LOGW("%{public}s failed, param is not napi_object.", __func__); - return false; - } - - napi_valuetype jsValueType = napi_undefined; - napi_value jsProNameList = nullptr; - uint32_t jsProCount = 0; - - NAPI_CALL_BASE(env, napi_get_property_names(env, param, &jsProNameList), false); - NAPI_CALL_BASE(env, napi_get_array_length(env, jsProNameList, &jsProCount), false); - LOGI("%{public}s called. Property size=%{public}d.", __func__, jsProCount); - - napi_value jsProName = nullptr; - napi_value jsProValue = nullptr; - for (uint32_t index = 0; index < jsProCount; index++) { - NAPI_CALL_BASE(env, napi_get_element(env, jsProNameList, index, &jsProName), false); - std::string strProName = AppExecFwk::UnwrapStringFromJS(env, jsProName); - LOGI("%{public}s called. Property name=%{public}s.", __func__, strProName.c_str()); - NAPI_CALL_BASE(env, napi_get_named_property(env, param, strProName.c_str(), &jsProValue), false); - NAPI_CALL_BASE(env, napi_typeof(env, jsProValue, &jsValueType), false); - int natValue = AppExecFwk::UnwrapInt32FromJS(env, jsProValue); - rawImageDataMap.emplace(strProName, natValue); - LOGI("%{public}s called. Property value=%{public}d.", __func__, natValue); - } - return true; -} - -JSValue JsOnCreateFinish(JSContext* ctx, JSValueConst value, int32_t argc, JSValueConst* argv) -{ - LOGD("JsOnCreateFinish"); - return JS_NULL; -} - -const JSCFunctionListEntry JS_PA_FUNCS[] = { - JS_CFUNC_DEF_CPP("onCreateFinish", 0, JsOnCreateFinish), -}; - -JSValue AppLogPrint(JSContext* ctx, Framework::JsLogLevel level, JSValueConst value, int32_t argc, JSValueConst* argv) -{ - ACE_SCOPED_TRACE("AppLogPrint(level=%d)", static_cast(level)); - - if ((argv == nullptr) || (argc == 0)) { - LOGE("the arg is error"); - return JS_EXCEPTION; - } - Framework::ScopedString printLog(ctx, argv[0]); - - switch (level) { - case Framework::JsLogLevel::DEBUG: - APP_LOGD("app Log: %{public}s", printLog.get()); - break; - case Framework::JsLogLevel::INFO: - APP_LOGI("app Log: %{public}s", printLog.get()); - break; - case Framework::JsLogLevel::WARNING: - APP_LOGW("app Log: %{public}s", printLog.get()); - break; - case Framework::JsLogLevel::ERROR: - APP_LOGE("app Log: %{public}s", printLog.get()); - break; - default: - break; - } - - return JS_NULL; -} - -JSValue AppLogPrint(JSContext* ctx, JSValueConst value, int32_t argc, JSValueConst* argv) -{ - return AppLogPrint(ctx, Framework::JsLogLevel::INFO, value, argc, argv); -} - -JSValue AppDebugLogPrint(JSContext* ctx, JSValueConst value, int32_t argc, JSValueConst* argv) -{ - return AppLogPrint(ctx, Framework::JsLogLevel::DEBUG, value, argc, argv); -} - -JSValue AppInfoLogPrint(JSContext* ctx, JSValueConst value, int32_t argc, JSValueConst* argv) -{ - return AppLogPrint(ctx, Framework::JsLogLevel::INFO, value, argc, argv); -} - -JSValue AppWarnLogPrint(JSContext* ctx, JSValueConst value, int32_t argc, JSValueConst* argv) -{ - return AppLogPrint(ctx, Framework::JsLogLevel::WARNING, value, argc, argv); -} - -JSValue AppErrorLogPrint(JSContext* ctx, JSValueConst value, int32_t argc, JSValueConst* argv) -{ - return AppLogPrint(ctx, Framework::JsLogLevel::ERROR, value, argc, argv); -} - -void InitJsConsoleObject(JSContext* ctx, const JSValue& globalObj) -{ - JSValue console; - // app log method - console = JS_NewObject(ctx); - JS_SetPropertyStr(ctx, console, "log", JS_NewCFunction(ctx, AppLogPrint, "log", 1)); - JS_SetPropertyStr(ctx, console, "debug", JS_NewCFunction(ctx, AppDebugLogPrint, "debug", 1)); - JS_SetPropertyStr(ctx, console, "info", JS_NewCFunction(ctx, AppInfoLogPrint, "info", 1)); - JS_SetPropertyStr(ctx, console, "warn", JS_NewCFunction(ctx, AppWarnLogPrint, "warn", 1)); - JS_SetPropertyStr(ctx, console, "error", JS_NewCFunction(ctx, AppErrorLogPrint, "error", 1)); - JS_SetPropertyStr(ctx, globalObj, "console", console); -} - -int32_t JsPaInit(JSContext* ctx, JSModuleDef* moduleDef) -{ - return JS_SetModuleExportList(ctx, moduleDef, JS_PA_FUNCS, countof(JS_PA_FUNCS)); -} - -JSModuleDef* InitPaModules(JSContext* ctx) -{ - LOGD("QjsPaEngine: InitPaModules"); - JSModuleDef* jsModule = JS_NewCModule(ctx, "Particle", JsPaInit); - if (jsModule == nullptr) { - return nullptr; - } - JS_AddModuleExportList(ctx, jsModule, JS_PA_FUNCS, countof(JS_PA_FUNCS)); - return jsModule; -} - -bool InitJsContext(JSContext* ctx, size_t maxStackSize, int32_t instanceId, - const QjsPaEngineInstance* qjsPaEngineInstance, const std::unordered_map& extraNativeObject) -{ - LOGI("QjsPaEngine: InitJsContext"); - if (ctx == nullptr) { - LOGE("Qjs cannot allocate JS context"); - EventReport::SendJsException(JsExcepType::JS_ENGINE_INIT_ERR); - return false; - } - - // Note: default 256KB is not enough - JS_SetMaxStackSize(ctx, maxStackSize); - - // Inject pa native functions module - InitPaModules(ctx); - - JSValue globalObj = JS_GetGlobalObject(ctx); - InitJsConsoleObject(ctx, globalObj); - - for (const auto& [key, value] : extraNativeObject) { - auto nativeObjectInfo = std::make_unique(); - nativeObjectInfo->nativeObject = value; - JSValue abilityValue = JS_NewExternal( - ctx, nativeObjectInfo.release(), - [](JSContext* ctx, void* data, void* hint) { - std::unique_ptr info(static_cast(data)); - }, - nullptr); - JS_SetPropertyStr(ctx, globalObj, key.c_str(), abilityValue); - } - - JS_FreeValue(ctx, globalObj); - return true; -} -} // namespace -// ----------------------- -// Start QjsPaEngineInstance -// ----------------------- -JSValue QjsPaEngineInstance::FireJsEvent(const std::string& eventId, const std::string& param) -{ - LOGI("FireJsEvent"); - JSContext* ctx = GetQjsContext(); - ACE_DCHECK(ctx); - Framework::QJSHandleScope handleScope(ctx); - JSValue globalObj = JS_GetGlobalObject(ctx); - JSValue callJsFunc = Framework::QJSUtils::GetPropertyStr(ctx, globalObj, "callJS"); - if (!JS_IsFunction(ctx, callJsFunc)) { - LOGE("cannot find 'callJS' function from global object, this should not happen!"); - JS_FreeValue(ctx, globalObj); - return JS_UNDEFINED; - } - - JSValueConst argv[] = { - Framework::QJSUtils::NewString(ctx, std::to_string(0).c_str()), - Framework::QJSUtils::ParseJSON(ctx, param.c_str(), param.size(), nullptr), - }; - - JSValue retVal = JS_Call(ctx, callJsFunc, JS_UNDEFINED, countof(argv), argv); - js_std_loop(ctx); - JS_FreeValue(ctx, globalObj); - - // It is up to the caller to check this value. No exception checks here. - return retVal; -} - -bool QjsPaEngineInstance::InitJsEnv( - JSRuntime* runtime, JSContext* context, const std::unordered_map& extraNativeObject) -{ - LOGI("InitJsEnv"); - if (runtime == nullptr) { - runtime = JS_NewRuntime(); - } - if (runtime_ != nullptr) { - JS_FreeRuntime(runtime_); - } - runtime_ = runtime; - if (runtime_ == nullptr) { - LOGE("Qjs cannot allocate JS runtime"); - EventReport::SendJsException(JsExcepType::JS_ENGINE_INIT_ERR); - return false; - } - - if (context == nullptr) { - context = JS_NewContext(runtime_); - } - if (context_ != nullptr) { - JS_FreeContext(context_); - } - context_ = context; - if (!InitJsContext(context_, Framework::MAX_STACK_SIZE, instanceId_, this, extraNativeObject)) { - LOGE("Qjs cannot allocate JS context"); - EventReport::SendJsException(JsExcepType::JS_ENGINE_INIT_ERR); - JS_FreeRuntime(runtime_); - return false; - } - - const char* str = "\n" - "var global = globalThis;\n" - "globalThis.pa = {default: {}};\n" - "function $app_define$(page, packageName, parseContent) {\n" - " const module = {exports: {}};\n" - " parseContent({}, module.exports, module);\n" - " globalThis.pa = module.exports;\n" - "}\n" - "function $app_bootstrap$() {}\n"; - - JSValue CppToJSRet = JS_Eval(context_, str, strlen(str), "", JS_EVAL_TYPE_GLOBAL); - if (JS_IsException(CppToJSRet)) { - LOGE("eval framework error"); - } - - JS_FreeValue(context_, CppToJSRet); - js_std_loop(context_); - return true; -} - -QjsPaEngineInstance::~QjsPaEngineInstance() -{ - if (context_) { - JS_FreeContext(context_); - } - if (runtime_) { - JS_FreeRuntime(runtime_); - } -} -// ----------------------- -// Start QjsPaEngine -// ----------------------- - -bool QjsPaEngine::Initialize(const RefPtr& delegate) -{ - ACE_SCOPED_TRACE("QjsPaEngine::Initialize"); - LOGI("Initialize"); - - JSRuntime* runtime = nullptr; - JSContext* context = nullptr; - - // put JS_NewContext as early as possible to make stack_top in context - // closer to the top stack frame pointer of JS thread. - runtime = JS_NewRuntime(); - if (runtime != nullptr) { - context = JS_NewContext(runtime); - } - LOGD("QjsPaEngine initialize"); -#ifdef ENABLE_JS_DEBUG - LOGI("QjsPaEngine debug mode"); - std::string instanceName = GetInstanceName(); - if (instanceName.empty()) { - LOGE("GetInstanceName fail, %s", instanceName.c_str()); - return false; - } - constexpr int32_t COMPONENT_NAME_MAX_LEN = 100; - char componentName[COMPONENT_NAME_MAX_LEN]; - if (!DBG_CopyComponentNameFromAce(instanceName.c_str(), componentName, COMPONENT_NAME_MAX_LEN)) { - LOGE("GetInstanceName strcpy_s fail"); - return false; - } - DBG_SetComponentName(componentName, strlen(componentName)); -#endif - LoadLibrary(); - nativeEngine_ = new QuickJSNativeEngine(runtime, context, static_cast(this)); - ACE_DCHECK(delegate); - delegate->AddTaskObserver([nativeEngine = nativeEngine_, id = instanceId_]() { - ContainerScope scope(id); - nativeEngine->Loop(LOOP_NOWAIT); - }); - - engineInstance_ = AceType::MakeRefPtr(delegate, instanceId_); - bool ret = engineInstance_->InitJsEnv(runtime, context, GetExtraNativeObject()); - JsBackendTimerModule::GetInstance()->InitTimerModule(nativeEngine_, delegate); - SetPostTask(nativeEngine_); -#if !defined(PREVIEW) - nativeEngine_->CheckUVLoop(); -#endif - if (delegate && delegate->GetAssetManager()) { - std::vector packagePath = delegate->GetAssetManager()->GetLibPath(); - if (!packagePath.empty()) { - auto qjsNativeEngine = static_cast(nativeEngine_); - qjsNativeEngine->SetPackagePath(packagePath); - } - } - RegisterWorker(); - return ret; -} - -void QjsPaEngine::SetPostTask(NativeEngine* nativeEngine) -{ - LOGI("SetPostTask"); - auto weakDelegate = AceType::WeakClaim(AceType::RawPtr(engineInstance_->GetDelegate())); - auto&& postTask = [weakDelegate, nativeEngine = nativeEngine_, id = instanceId_](bool needSync) { - auto delegate = weakDelegate.Upgrade(); - if (delegate == nullptr) { - LOGE("delegate is nullptr"); - return; - } - delegate->PostJsTask([nativeEngine, needSync, id]() { - ContainerScope scope(id); - if (nativeEngine == nullptr) { - return; - } - nativeEngine->Loop(LOOP_NOWAIT, needSync); - }); - }; - nativeEngine_->SetPostTask(postTask); -} - -void QjsPaEngine::RegisterInitWorkerFunc() -{ - auto&& initWorkerFunc = [weak = AceType::WeakClaim(this)](NativeEngine* nativeEngine) { - LOGI("WorkerCore RegisterInitWorkerFunc called"); - auto paEngine = weak.Upgrade(); - if (nativeEngine == nullptr) { - LOGE("nativeEngine is nullptr"); - return; - } - auto qjsNativeEngine = static_cast(nativeEngine); - if (qjsNativeEngine == nullptr) { - LOGE("qjsNativeEngine is nullptr"); - return; - } - - JSContext* ctx = qjsNativeEngine->GetContext(); - if (ctx == nullptr) { - LOGE("ctx is nullptr"); - return; - } - - // Create a stack-allocated handle scope. - Framework::QJSHandleScope handleScope(ctx); - - // Note: default 256KB is not enough - JS_SetMaxStackSize(ctx, Framework::MAX_STACK_SIZE); - - JSValue globalObj = JS_GetGlobalObject(ctx); - InitJsConsoleObject(ctx, globalObj); - JS_FreeValue(ctx, globalObj); - - for (const auto& [key, value] : paEngine->GetExtraNativeObject()) { - auto nativeObjectInfo = std::make_unique(); - nativeObjectInfo->nativeObject = value; - JSValue abilityValue = JS_NewExternal( - ctx, nativeObjectInfo.release(), - [](JSContext* ctx, void* data, void* hint) { - std::unique_ptr info(static_cast(data)); - }, - nullptr); - JS_SetPropertyStr(ctx, globalObj, key.c_str(), abilityValue); - } - }; - nativeEngine_->SetInitWorkerFunc(initWorkerFunc); -} - -void QjsPaEngine::RegisterAssetFunc() -{ - auto weakDelegate = AceType::WeakClaim(AceType::RawPtr(engineInstance_->GetDelegate())); - auto&& assetFunc = [weakDelegate](const std::string& uri, std::vector& content, std::string& ami) { - LOGI("WorkerCore RegisterAssetFunc called"); - auto delegate = weakDelegate.Upgrade(); - if (delegate == nullptr) { - LOGE("delegate is nullptr"); - return; - } - delegate->GetResourceData(uri, content, ami); - }; - nativeEngine_->SetGetAssetFunc(assetFunc); -} - -void QjsPaEngine::RegisterWorker() -{ - RegisterInitWorkerFunc(); - RegisterAssetFunc(); -} - -QjsPaEngine::~QjsPaEngine() -{ - UnloadLibrary(); - if (engineInstance_ && engineInstance_->GetDelegate()) { - engineInstance_->GetDelegate()->RemoveTaskObserver(); - } - if (nativeEngine_ != nullptr) { -#if !defined(PREVIEW) - nativeEngine_->CancelCheckUVLoop(); -#endif - nativeEngine_->DeleteEngine(); - delete nativeEngine_; - } - if (engineInstance_ && engineInstance_->GetQjsRuntime()) { - JS_RunGC(engineInstance_->GetQjsRuntime()); - } -} - -inline int32_t GetJsInt32Val(JSContext* ctx, JSValueConst value) -{ - int32_t val = 0; - if (JS_IsNumber(value) && (JS_ToInt32(ctx, &val, value)) < 0) { - val = 0; - } - return val; -} - -inline std::string GetJsStringVal(JSContext* ctx, JSValueConst value) -{ - std::string val; - if (!JS_IsString(value)) { - return val; - } - - auto cstr = JS_ToCString(ctx, value); - if (cstr == nullptr) { - return val; - } - val = cstr; - JS_FreeCString(ctx, cstr); - - return val; -} - -inline std::string ToJSONStringInt(std::string sKey, std::string sValue) -{ - char szDoubleQuotes[] = "\""; - char szColon[] = ":"; - std::string strResult; - strResult.append(szDoubleQuotes); - strResult.append(sKey); - strResult.append(szDoubleQuotes); - - strResult.append(szColon); - strResult.append(sValue); - return strResult; -} - -inline std::string ToJSONString(std::string sKey, std::string sValue) -{ - char szDoubleQuotes[] = "\""; - char szColon[] = ":"; - std::string strResult; - strResult.append(szDoubleQuotes); - strResult.append(sKey); - strResult.append(szDoubleQuotes); - - strResult.append(szColon); - strResult.append(szDoubleQuotes); - strResult.append(sValue); - strResult.append(szDoubleQuotes); - return strResult; -} - -void QjsPaEngine::LoadJs(const std::string& url, const OHOS::AAFwk::Want& want) -{ - LOGI("QjsPaEngine LoadJs: %{private}s", url.c_str()); - ACE_SCOPED_TRACE("QjsPaEngine::LoadJs"); - ACE_DCHECK(engineInstance_); - - JSContext* ctx = engineInstance_->GetQjsContext(); - - // Create a stack-allocated handle scope. - Framework::QJSHandleScope handleScope(ctx); - - // Memorize the context that this JSContext is working with. - JS_SetContextOpaque(ctx, reinterpret_cast(AceType::RawPtr(engineInstance_))); - - JSValue globalObj = JS_GetGlobalObject(ctx); - - std::string jsContent; - if (!engineInstance_->GetDelegate()->GetAssetContent(url, jsContent)) { - LOGE("js file load failed!"); - JS_FreeValue(ctx, globalObj); - return; - } - - JSValue CppToJSRet = JS_Eval(ctx, jsContent.c_str(), jsContent.size(), url.c_str(), JS_EVAL_TYPE_GLOBAL); - - JS_FreeValue(ctx, CppToJSRet); - - // call onStart - JSValue paObj; - paObj = Framework::QJSUtils::GetPropertyStr(ctx, globalObj, "pa"); - if (!JS_IsObject(paObj)) { - LOGE("get paObj error"); - } - - JSPropertyEnum* pTab = nullptr; - uint32_t len = 0; - if (!Framework::CheckAndGetJsProperty(ctx, paObj, &pTab, &len)) { - LOGE("PA: Framework::CheckAndGetJsProperty error"); - } - LOGI("PA: QjsPaEngine pa propey num %{public}u", len); - - BackendType type = engineInstance_->GetDelegate()->GetType(); - JSValue paStartFunc = JS_NULL; - if (type == BackendType::SERVICE) { - paStartFunc = Framework::QJSUtils::GetPropertyStr(ctx, paObj, "onStart"); - } else if (type == BackendType::DATA) { - paStartFunc = Framework::QJSUtils::GetPropertyStr(ctx, paObj, "onInitialized"); - } else if (type == BackendType::FORM) { - LOGI("Form Ability LoadJS finish."); - JS_FreeValue(ctx, globalObj); - return; - } else { - LOGE("backend type not support"); - } - - if (!JS_IsFunction(ctx, paStartFunc)) { - LOGE("paStartFunc is not found"); - JS_FreeValue(ctx, globalObj); - return; - } - - JSValue retVal = JS_UNDEFINED; - if (type == BackendType::SERVICE) { - JSValueConst argv[] = {}; - retVal = Framework::QJSUtils::Call(ctx, paStartFunc, paObj, countof(argv), argv); - } else if (type == BackendType::DATA) { - const auto& nativeObjects = GetExtraNativeObject(); - auto it = nativeObjects.find("ability"); - if (it == nativeObjects.end() || it->second == nullptr) { - LOGE("Can't find ability object"); - return; - } - const std::shared_ptr abilityInfo = - reinterpret_cast(it->second)->GetAbilityInfo(); - const AppExecFwk::AbilityInfo abilityInfoInstance = *(abilityInfo.get()); - napi_value abilityInfoNapi = - AppExecFwk::ConvertAbilityInfo(reinterpret_cast(nativeEngine_), abilityInfoInstance); - - NativeValue* abilityInfoNative = reinterpret_cast(abilityInfoNapi); - JSValue abilityInfoJS = static_cast(*abilityInfoNative); - JSValueConst argv[] = { abilityInfoJS }; - retVal = Framework::QJSUtils::Call(ctx, paStartFunc, paObj, countof(argv), argv); - } else { - LOGE("PA: QjsPaEngine backend type not support"); - } - - if (JS_IsException(retVal)) { - LOGE("PA: QjsPaEngine QJSUtils::Call IsException"); - } else { - LOGI("PA: QjsPaEngine QJSUtils::Call ok"); - } - - js_std_loop(ctx); - JS_FreeValue(ctx, retVal); - JS_FreeValue(ctx, globalObj); -} - -void QjsPaEngine::SetJsMessageDispatcher(const RefPtr& dispatcher) -{ - ACE_DCHECK(engineInstance_); - engineInstance_->SetJsMessageDispatcher(dispatcher); -} - -void QjsPaEngine::FireAsyncEvent(const std::string& eventId, const std::string& param) -{ - std::string callBuf = std::string("[{\"args\": [\"") - .append(eventId) - .append("\",") - .append(param) - .append("], \"method\":\"fireEvent\"}]"); - LOGD("FireAsyncEvent string: %{private}s", callBuf.c_str()); - - ACE_DCHECK(engineInstance_); - JSValue cppToJsRet = engineInstance_->FireJsEvent(eventId, callBuf); - if (JS_IsException(cppToJsRet)) { - LOGE("Qjs FireAsyncEvent FAILED !! jsCall: %{private}s", callBuf.c_str()); - } - JS_FreeValue(engineInstance_->GetQjsContext(), cppToJsRet); -} - -void QjsPaEngine::FireSyncEvent(const std::string& eventId, const std::string& param) -{ - std::string callBuf = std::string("[{\"args\": [\"") - .append(eventId) - .append("\",") - .append(param) - .append("], \"method\":\"fireEventSync\"}]"); - LOGD("FireSyncEvent string: %{private}s", callBuf.c_str()); - - ACE_DCHECK(engineInstance_); - JSValue cppToJsRet = engineInstance_->FireJsEvent(eventId, callBuf.c_str()); - if (JS_IsException(cppToJsRet)) { - LOGE("Qjs FireSyncEvent FAILED !! jsCall: %{private}s", callBuf.c_str()); - } - JS_FreeValue(engineInstance_->GetQjsContext(), cppToJsRet); -} - -void QjsPaEngine::DestroyApplication(const std::string& packageName) -{ - LOGI("DestroyApplication: destroy app instance from jsfwk"); - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Framework::QJSHandleScope handleScope(ctx); - JSValue globalObj = JS_GetGlobalObject(ctx); - JSValue paObj = Framework::QJSUtils::GetPropertyStr(ctx, globalObj, "pa"); - if (!JS_IsObject(paObj)) { - LOGE("get paObj error"); - } - JSValue paDestroyFunc = Framework::QJSUtils::GetPropertyStr(ctx, paObj, "onStop"); - if (!JS_IsFunction(ctx, paDestroyFunc)) { - LOGE("paDestroyFunc is not found, cannot destroy page instance!"); - JS_FreeValue(ctx, globalObj); - return; - } - - JSValue name = Framework::QJSUtils::NewString(ctx, packageName.c_str()); - JSValueConst argv[] = { name }; - JSValue retVal = Framework::QJSUtils::Call(ctx, paDestroyFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("Qjs paDestroyFunc FAILED!"); - } - - JS_FreeValue(ctx, globalObj); -} - -void QjsPaEngine::OnCommandApplication(const std::string& intent, int startId) -{ - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Framework::QJSHandleScope handleScope(ctx); - JSValue globalObj = JS_GetGlobalObject(ctx); - JSValue paObj = Framework::QJSUtils::GetPropertyStr(ctx, globalObj, "pa"); - if (!JS_IsObject(paObj)) { - LOGE("get paObj error"); - } - JSValue paCommandFunc = Framework::QJSUtils::GetPropertyStr(ctx, paObj, "onCommand"); - if (!JS_IsFunction(ctx, paCommandFunc)) { - LOGE("paCommandFunc is not found!"); - JS_FreeValue(ctx, globalObj); - return; - } - - JSValueConst argv[] = { - Framework::QJSUtils::NewString(ctx, intent.c_str()), - JS_NewInt32(ctx, startId), - }; - JSValue retVal = Framework::QJSUtils::Call(ctx, paCommandFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("Qjs paCommandFunc FAILED!"); - } - - JS_FreeValue(ctx, globalObj); -} - -JSValue QjsPaEngine::GetPaFunc(const std::string& funcName) -{ - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Framework::QJSHandleScope handleScope(ctx); - JSValue globalObj = JS_GetGlobalObject(ctx); - JSValue paObj = Framework::QJSUtils::GetPropertyStr(ctx, globalObj, "pa"); - if (!JS_IsObject(paObj)) { - LOGE("PA: get paObj error"); - return JS_UNDEFINED; - } - JSValue paFunc = Framework::QJSUtils::GetPropertyStr(ctx, paObj, funcName.c_str()); - if (!JS_IsFunction(ctx, paFunc)) { - LOGE("PA: paFunc is not found,! %{public}s", funcName.c_str()); - JS_FreeValue(ctx, globalObj); - return JS_UNDEFINED; - } - LOGI("GetPaFunc: funcName success: %{public}s", funcName.c_str()); - JS_FreeValue(ctx, globalObj); - return paFunc; -} - -void QjsPaEngine::LoadLibrary() -{ -#ifdef _ARM_ - const char* rdbPath = "/system/lib/module/data/librdb.z.so"; -#else - const char* rdbPath = "/system/lib64/module/data/librdb.z.so"; -#endif - if (strlen(rdbPath) == 0) { - LOGE("module path is empty"); - return; - } - - libRdb_ = dlopen(rdbPath, RTLD_LAZY); - if (libRdb_ == nullptr) { - LOGE("dlopen failed: %{public}s", dlerror()); - } - - rdbValueBucketNewInstance_ = reinterpret_cast( - dlsym(libRdb_, "NAPI_OHOS_Data_RdbJsKit_ValuesBucketProxy_NewInstance")); - if (rdbValueBucketNewInstance_ == nullptr) { - LOGE("symbol not found: %{public}s", dlerror()); - } - - rdbValueBucketGetNativeObject_ = reinterpret_cast( - dlsym(libRdb_, "NAPI_OHOS_Data_RdbJsKit_ValuesBucketProxy_GetNativeObject")); - if (rdbValueBucketGetNativeObject_ == nullptr) { - LOGE("symbol not found: %{public}s", dlerror()); - } - - rdbResultSetProxyNewInstance_ = reinterpret_cast( - dlsym(libRdb_, "NAPI_OHOS_Data_RdbJsKit_ResultSetProxy_NewInstance")); - if (rdbResultSetProxyNewInstance_ == nullptr) { - LOGE("symbol not found: %{public}s", dlerror()); - } - - rdbResultSetProxyGetNativeObject_ = reinterpret_cast( - dlsym(libRdb_, "NAPI_OHOS_Data_RdbJsKit_ResultSetProxy_GetNativeObject")); - if (rdbResultSetProxyGetNativeObject_ == nullptr) { - LOGE("symbol not found: %{public}s", dlerror()); - } - -#ifdef _ARM_ - const char* dataAbilityPath = "/system/lib/module/data/libdataability.z.so"; -#else - const char* dataAbilityPath = "/system/lib64/module/data/libdataability.z.so"; -#endif - if (strlen(dataAbilityPath) == 0) { - LOGE("module path is empty"); - return; - } - - libDataAbility_ = dlopen(dataAbilityPath, RTLD_LAZY); - if (libDataAbility_ == nullptr) { - LOGE("dlopen failed: %{public}s", dlerror()); - } - - dataAbilityPredicatesNewInstance_ = reinterpret_cast( - dlsym(libDataAbility_, "NAPI_OHOS_Data_DataAbilityJsKit_DataAbilityPredicatesProxy_NewInstance")); - if (dataAbilityPredicatesNewInstance_ == nullptr) { - LOGE("symbol not found: %{public}s", dlerror()); - } - - dataAbilityPredicatesGetNativeObject_ = reinterpret_cast( - dlsym(libDataAbility_, "NAPI_OHOS_Data_DataAbilityJsKit_DataAbilityPredicatesProxy_GetNativeObject")); - if (dataAbilityPredicatesGetNativeObject_ == nullptr) { - LOGE("symbol not found: %{public}s", dlerror()); - } -} - -void QjsPaEngine::UnloadLibrary() -{ - dlclose(libRdb_); - dlclose(libDataAbility_); -} - -int32_t QjsPaEngine::Insert(const Uri& uri, const OHOS::NativeRdb::ValuesBucket& value, const CallingInfo& callingInfo) -{ - LOGI("Insert"); - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Framework::QJSHandleScope handleScope(ctx); - JSValue paFunc = GetPaFunc("insert"); - - JSValue argUriJSValue = JS_NewString(ctx, uri.ToString().c_str()); - - napi_env env = reinterpret_cast(nativeEngine_); - napi_value argNapiValue = rdbValueBucketNewInstance_(env, const_cast(value)); - NativeValue* argNapiNativeValue = reinterpret_cast(argNapiValue); - JSValue argNapiJSValue = (JSValue)*argNapiNativeValue; - JSValueConst argv[] = { argUriJSValue, argNapiJSValue }; - JSValue retVal = Framework::QJSUtils::Call(ctx, paFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("Qjs paFunc FAILED!"); - return 0; - } - return GetJsInt32Val(ctx, retVal); -} - -std::shared_ptr QjsPaEngine::Call( - const std::string& method, const std::string& arg, const AppExecFwk::PacMap& pacMap, const CallingInfo& callingInfo) -{ - LOGD("QjsPaEngine Call"); - std::shared_ptr resultSet = nullptr; - return resultSet; -} - -std::shared_ptr QjsPaEngine::Query(const Uri& uri, - const std::vector& columns, const OHOS::NativeRdb::DataAbilityPredicates& predicates, - const CallingInfo& callingInfo) -{ - LOGI("Query"); - std::shared_ptr resultSet = nullptr; - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Framework::QJSHandleScope handleScope(ctx); - JSValue paFunc = GetPaFunc("query"); - - JSValue argUriJSValue = JS_NewString(ctx, uri.ToString().c_str()); - - napi_env env = reinterpret_cast(nativeEngine_); - napi_value argColumnsNapiValue = nullptr; - napi_create_array(env, &argColumnsNapiValue); - bool isArray = false; - if (napi_is_array(env, argColumnsNapiValue, &isArray) != napi_ok || !isArray) { - LOGE("create array failed"); - return resultSet; - } - - int32_t index = 0; - for (auto column : columns) { - napi_value result = nullptr; - napi_create_string_utf8(env, column.c_str(), column.length(), &result); - napi_set_element(env, argColumnsNapiValue, index++, result); - } - - NativeValue* argColumnsNativeValue = reinterpret_cast(argColumnsNapiValue); - JSValue argColumnsJSValue = (JSValue)*argColumnsNativeValue; - - OHOS::NativeRdb::DataAbilityPredicates* predicatesPtr = new OHOS::NativeRdb::DataAbilityPredicates(); - *predicatesPtr = predicates; - napi_value argPredicatesNapiValue = dataAbilityPredicatesNewInstance_(env, predicatesPtr); - NativeValue* argPredicatesNativeValue = reinterpret_cast(argPredicatesNapiValue); - if (argPredicatesNativeValue == nullptr) { - LOGE("Query argPredicatesNativeValue is nullptr"); - return resultSet; - } - JSValue argPredicatesJSValue = (JSValue)*argPredicatesNativeValue; - - JSValueConst argv[] = { argUriJSValue, argColumnsJSValue, argPredicatesJSValue }; - JSValue retVal = Framework::QJSUtils::Call(ctx, paFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal) || JS_IsUndefined(retVal)) { - LOGE("Qjs paFunc FAILED!"); - return resultSet; - } - - auto nativeObject = rdbResultSetProxyGetNativeObject_( - env, reinterpret_cast(QuickJSNativeEngine::JSValueToNativeValue(nativeEngine_, retVal))); - if (nativeObject == nullptr) { - LOGE("AbsSharedResultSet from JS to Native failed"); - return resultSet; - } - - resultSet.reset(nativeObject); - return resultSet; -} - -int32_t QjsPaEngine::Update(const Uri& uri, const OHOS::NativeRdb::ValuesBucket& value, - const OHOS::NativeRdb::DataAbilityPredicates& predicates, const CallingInfo& callingInfo) -{ - LOGI("Update"); - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Framework::QJSHandleScope handleScope(ctx); - JSValue paFunc = GetPaFunc("update"); - - JSValue argUriJSValue = JS_NewString(ctx, uri.ToString().c_str()); - - napi_env env = reinterpret_cast(nativeEngine_); - napi_value argNapiValue = rdbValueBucketNewInstance_(env, const_cast(value)); - NativeValue* argNapiNativeValue = reinterpret_cast(argNapiValue); - JSValue argNapiJSValue = (JSValue)*argNapiNativeValue; - - OHOS::NativeRdb::DataAbilityPredicates* predicatesPtr = new OHOS::NativeRdb::DataAbilityPredicates(); - *predicatesPtr = predicates; - napi_value argPredicatesNapiValue = dataAbilityPredicatesNewInstance_(env, predicatesPtr); - NativeValue* argPredicatesNativeValue = reinterpret_cast(argPredicatesNapiValue); - if (argPredicatesNativeValue == nullptr) { - LOGE("Update argPredicatesNativeValue is nullptr"); - return 0; - } - JSValue argPredicatesJSValue = (JSValue)*argPredicatesNativeValue; - - JSValueConst argv[] = { argUriJSValue, argNapiJSValue, argPredicatesJSValue }; - JSValue retVal = Framework::QJSUtils::Call(ctx, paFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("Qjs paFunc FAILED!"); - return 0; - } - return GetJsInt32Val(ctx, retVal); -} - -int32_t QjsPaEngine::Delete( - const Uri& uri, const OHOS::NativeRdb::DataAbilityPredicates& predicates, const CallingInfo& callingInfo) -{ - LOGI("Delete"); - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Framework::QJSHandleScope handleScope(ctx); - JSValue paFunc = GetPaFunc("delete"); - - JSValue argUriJSValue = JS_NewString(ctx, uri.ToString().c_str()); - - napi_env env = reinterpret_cast(nativeEngine_); - OHOS::NativeRdb::DataAbilityPredicates* predicatesPtr = new OHOS::NativeRdb::DataAbilityPredicates(); - *predicatesPtr = predicates; - napi_value argPredicatesNapiValue = dataAbilityPredicatesNewInstance_(env, predicatesPtr); - NativeValue* argPredicatesNativeValue = reinterpret_cast(argPredicatesNapiValue); - if (argPredicatesNativeValue == nullptr) { - LOGE("Delete argPredicatesNativeValue is nullptr"); - return 0; - } - JSValue argPredicatesJSValue = (JSValue)*argPredicatesNativeValue; - - JSValueConst argv[] = { argUriJSValue, argPredicatesJSValue }; - JSValue retVal = Framework::QJSUtils::Call(ctx, paFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("Qjs paFunc FAILED!"); - return 0; - } - return GetJsInt32Val(ctx, retVal); -} - -int32_t QjsPaEngine::BatchInsert( - const Uri& uri, const std::vector& values, const CallingInfo& callingInfo) -{ - LOGI("BatchInsert"); - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Framework::QJSHandleScope handleScope(ctx); - JSValue paFunc = GetPaFunc("batchInsert"); - - JSValue argUriJSValue = JS_NewString(ctx, uri.ToString().c_str()); - - napi_env env = reinterpret_cast(nativeEngine_); - napi_value argColumnsNapiValue = nullptr; - napi_create_array(env, &argColumnsNapiValue); - bool isArray = false; - if (napi_is_array(env, argColumnsNapiValue, &isArray) != napi_ok || !isArray) { - LOGE("create array failed"); - return 0; - } - - int32_t index = 0; - for (auto value : values) { - napi_value result = rdbValueBucketNewInstance_(env, const_cast(value)); - napi_set_element(env, argColumnsNapiValue, index++, result); - } - - NativeValue* argColumnsNativeValue = reinterpret_cast(argColumnsNapiValue); - JSValue argColumnsJSValue = (JSValue)*argColumnsNativeValue; - - JSValueConst argv[] = { argUriJSValue, argColumnsJSValue }; - JSValue retVal = Framework::QJSUtils::Call(ctx, paFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("Qjs paFunc FAILED!"); - return 0; - } - return GetJsInt32Val(ctx, retVal); -} - -std::string QjsPaEngine::GetType(const Uri& uri, const CallingInfo& callingInfo) -{ - LOGI("GetType"); - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Framework::QJSHandleScope handleScope(ctx); - JSValue paFunc = GetPaFunc("getType"); - - JSValue argUriJSValue = JS_NewString(ctx, uri.ToString().c_str()); - - JSValueConst argv[] = { argUriJSValue }; - JSValue retVal = Framework::QJSUtils::Call(ctx, paFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("Qjs paFunc FAILED!"); - return std::string(); - } - return GetJsStringVal(ctx, retVal); -} - -std::vector QjsPaEngine::GetFileTypes( - const Uri& uri, const std::string& mimeTypeFilter, const CallingInfo& callingInfo) -{ - LOGI("GetFileTypes"); - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - std::vector ret; - Framework::QJSHandleScope handleScope(ctx); - JSValue paFunc = GetPaFunc("getFileTypes"); - - JSValue argUriJSValue = JS_NewString(ctx, uri.ToString().c_str()); - JSValue argMimeTypeFilterJSValue = JS_NewString(ctx, mimeTypeFilter.c_str()); - - JSValueConst argv[] = { argUriJSValue, argMimeTypeFilterJSValue }; - JSValue retVal = Framework::QJSUtils::Call(ctx, paFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("Qjs paFunc FAILED!"); - return ret; - } - - if (!JS_IsArray(ctx, retVal)) { - LOGE("GetFileTypes return not array"); - return ret; - } - - int32_t length = Framework::QJSUtils::JsGetArrayLength(ctx, retVal); - for (int i = 0; i < length; i++) { - JSValue itemVal = JS_GetPropertyUint32(ctx, retVal, i); - ret.push_back(GetJsStringVal(ctx, itemVal)); - } - - return ret; -} - -int32_t QjsPaEngine::OpenFile(const Uri& uri, const std::string& mode, const CallingInfo& callingInfo) -{ - LOGI("OpenFile"); - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Framework::QJSHandleScope handleScope(ctx); - JSValue paFunc = GetPaFunc("openFile"); - - JSValue argUriJSValue = JS_NewString(ctx, uri.ToString().c_str()); - JSValue argModeJSValue = JS_NewString(ctx, mode.c_str()); - - JSValueConst argv[] = { argUriJSValue, argModeJSValue }; - JSValue retVal = Framework::QJSUtils::Call(ctx, paFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("Qjs paFunc FAILED!"); - return 0; - } - return GetJsInt32Val(ctx, retVal); -} - -int32_t QjsPaEngine::OpenRawFile(const Uri& uri, const std::string& mode, const CallingInfo& callingInfo) -{ - LOGI("OpenRawFile"); - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Framework::QJSHandleScope handleScope(ctx); - JSValue paFunc = GetPaFunc("openRawFile"); - - JSValue argUriJSValue = JS_NewString(ctx, uri.ToString().c_str()); - JSValue argModeJSValue = JS_NewString(ctx, mode.c_str()); - - JSValueConst argv[] = { argUriJSValue, argModeJSValue }; - JSValue retVal = Framework::QJSUtils::Call(ctx, paFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("Qjs paFunc FAILED!"); - return 0; - } - return GetJsInt32Val(ctx, retVal); -} - -Uri QjsPaEngine::NormalizeUri(const Uri& uri, const CallingInfo& callingInfo) -{ - LOGI("NormalizeUri"); - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Uri ret(""); - Framework::QJSHandleScope handleScope(ctx); - JSValue paFunc = GetPaFunc("normalizeUri"); - - JSValue argUriJSValue = JS_NewString(ctx, uri.ToString().c_str()); - - JSValueConst argv[] = { argUriJSValue }; - JSValue retVal = Framework::QJSUtils::Call(ctx, paFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("Qjs paFunc FAILED!"); - return ret; - } - - return Uri(GetJsStringVal(ctx, retVal)); -} - -Uri QjsPaEngine::DenormalizeUri(const Uri& uri, const CallingInfo& callingInfo) -{ - LOGI("DenormalizeUri"); - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Uri ret(""); - Framework::QJSHandleScope handleScope(ctx); - JSValue paFunc = GetPaFunc("denormalizeUri"); - - JSValue argUriJSValue = JS_NewString(ctx, uri.ToString().c_str()); - - JSValueConst argv[] = { argUriJSValue }; - JSValue retVal = Framework::QJSUtils::Call(ctx, paFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("Qjs paFunc FAILED!"); - return ret; - } - - return Uri(GetJsStringVal(ctx, retVal)); -} - -sptr QjsPaEngine::OnConnectService(const OHOS::AAFwk::Want& want) -{ - LOGI("OnConnectService"); - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - Framework::QJSHandleScope handleScope(ctx); - Framework::QJSContext::Scope scope(ctx); - JSValue globalObj = JS_GetGlobalObject(ctx); - JSValue paObj = Framework::QJSUtils::GetPropertyStr(ctx, globalObj, "pa"); - if (!JS_IsObject(paObj)) { - LOGE("get onConnect function error"); - return nullptr; - } - JSValue onConnectFunc = Framework::QJSUtils::GetPropertyStr(ctx, paObj, "onConnect"); - if (!JS_IsFunction(ctx, onConnectFunc)) { - LOGE("onConnect function is not found!"); - JS_FreeValue(ctx, globalObj); - return nullptr; - } - napi_value napiWant = OHOS::AppExecFwk::WrapWant(reinterpret_cast(nativeEngine_), want); - NativeValue* nativeWant = reinterpret_cast(napiWant); - JSValue jsWant = (JSValue)*nativeWant; - JSValueConst argv[] = { jsWant }; - JSValue retVal = Framework::QJSUtils::Call(ctx, onConnectFunc, JS_UNDEFINED, countof(argv), argv); - js_std_loop(ctx); - if (JS_IsException(retVal)) { - LOGE("Qjs onConnectService FAILED!"); - JS_FreeValue(ctx, globalObj); - JS_FreeValue(ctx, retVal); - return nullptr; - } else { - NativeValue* nativeValue = QuickJSNativeEngine::JSValueToNativeValue(nativeEngine_, retVal); - auto remoteObj = NAPI_ohos_rpc_getNativeRemoteObject( - reinterpret_cast(nativeEngine_), reinterpret_cast(nativeValue)); - JS_FreeValue(ctx, globalObj); - return remoteObj; - } -} - -void QjsPaEngine::OnDisconnectService(const OHOS::AAFwk::Want& want) -{ - LOGI("OnDisconnectService"); - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Framework::QJSHandleScope handleScope(ctx); - JSValue globalObj = JS_GetGlobalObject(ctx); - JSValue paObj = Framework::QJSUtils::GetPropertyStr(ctx, globalObj, "pa"); - if (!JS_IsObject(paObj)) { - LOGE("get onDisconnect function error"); - return; - } - JSValue onDisConnectFunc = Framework::QJSUtils::GetPropertyStr(ctx, paObj, "onDisconnect"); - if (!JS_IsFunction(ctx, onDisConnectFunc)) { - LOGE("onDisconnect function is not found!"); - JS_FreeValue(ctx, globalObj); - return; - } - napi_value napiWant = OHOS::AppExecFwk::WrapWant(reinterpret_cast(nativeEngine_), want); - NativeValue* nativeWant = reinterpret_cast(napiWant); - JSValue jsWant = (JSValue)*nativeWant; - JSValueConst argv[] = { jsWant }; - JSValue retVal = Framework::QJSUtils::Call(ctx, onDisConnectFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("Qjs OnDisconnectService FAILED!"); - } - JS_FreeValue(ctx, globalObj); - JS_FreeValue(ctx, retVal); -} - -void QjsPaEngine::OnCreate(const OHOS::AAFwk::Want& want) -{ - LOGI("PA: QjsPaEngine OnCreate"); - // call onCreate - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - Framework::QJSHandleScope handleScope(ctx); - JSValue globalObj = JS_GetGlobalObject(ctx); - JSValue paObj = Framework::QJSUtils::GetPropertyStr(ctx, globalObj, "pa"); - if (!JS_IsObject(paObj)) { - LOGE("OnCreate failed, get pa object error"); - return; - } - - JSPropertyEnum* pTab = nullptr; - uint32_t len = 0; - if (!Framework::CheckAndGetJsProperty(ctx, paObj, &pTab, &len)) { - LOGE("PA: Framework::CheckAndGetJsProperty error"); - } - LOGI("PA: QjsPaEngine pa propey num %{public}u", len); - JSValue paStartFunc = Framework::QJSUtils::GetPropertyStr(ctx, paObj, "onCreate"); - if (!JS_IsFunction(ctx, paStartFunc)) { - LOGE("onCreate func is not found."); - JS_FreeValue(ctx, globalObj); - return; - } - - napi_value napiWant = OHOS::AppExecFwk::WrapWant(reinterpret_cast(nativeEngine_), want); - NativeValue* nativeWant = reinterpret_cast(napiWant); - JSValue jsWant = (JSValue)*nativeWant; - JSValueConst argv[] = { jsWant }; - JSValue retVal = Framework::QJSUtils::Call(ctx, paStartFunc, paObj, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("PA: QjsPaEngine QJSUtils::Call IsException"); - } - - std::string jsonStr; - JSValue formJsonData = Framework::QJSUtils::GetPropertyStr(ctx, retVal, "data"); - if (JS_IsString(formJsonData)) { - Framework::ScopedString strValue(ctx, formJsonData); - jsonStr = strValue.get(); - LOGI("Add FormBindingData json:%{public}s", jsonStr.c_str()); - } - AppExecFwk::FormProviderData formData = AppExecFwk::FormProviderData(jsonStr); - JSValue formImageData = Framework::QJSUtils::GetPropertyStr(ctx, retVal, "image"); - if (JS_IsObject(formImageData)) { - std::map rawImageDataMap; - NativeValue* nativeValue = reinterpret_cast(&formImageData); - UnwrapRawImageDataMap(nativeEngine_, nativeValue, rawImageDataMap); - for (const auto& data : rawImageDataMap) { - formData.AddImageData(data.first, data.second); - } - } - SetFormData(formData); -} - -void QjsPaEngine::OnDelete(const int64_t formId) -{ - LOGI("PA: QjsPaEngine OnDelete"); - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Framework::QJSHandleScope handleScope(ctx); - JSValue paFunc = GetPaFunc("onDestroy"); - - JSValue argFormIdJSValue = JS_NewString(ctx, std::to_string(formId).c_str()); - - JSValueConst argv[] = { argFormIdJSValue }; - JSValue retVal = Framework::QJSUtils::Call(ctx, paFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("PA: OnDelete FAILED!"); - return; - } - return; -} - -void QjsPaEngine::OnTriggerEvent(const int64_t formId, const std::string& message) -{ - LOGI("PA: QjsPaEngine OnTriggerEvent"); - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Framework::QJSHandleScope handleScope(ctx); - JSValue paFunc = GetPaFunc("onEvent"); - - JSValue argFormIdJSValue = JS_NewString(ctx, std::to_string(formId).c_str()); - JSValue argMessageJSValue = JS_NewString(ctx, message.c_str()); - - JSValueConst argv[] = { argFormIdJSValue, argMessageJSValue }; - JSValue retVal = Framework::QJSUtils::Call(ctx, paFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("PA: OnTriggerEvent FAILED!"); - return; - } - return; -} - -void QjsPaEngine::OnUpdate(const int64_t formId) -{ - LOGI("PA: QjsPaEngine OnUpdate"); - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Framework::QJSHandleScope handleScope(ctx); - JSValue paFunc = GetPaFunc("onUpdate"); - - JSValue argFormIdJSValue = JS_NewString(ctx, std::to_string(formId).c_str()); - - JSValueConst argv[] = { argFormIdJSValue }; - JSValue retVal = Framework::QJSUtils::Call(ctx, paFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("PA: OnUpdate FAILED!"); - return; - } - return; -} - -void QjsPaEngine::OnCastTemptoNormal(const int64_t formId) -{ - LOGI("PA: QjsPaEngine OnCastTemptoNormal"); - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Framework::QJSHandleScope handleScope(ctx); - JSValue paFunc = GetPaFunc("onCastToNormal"); - - JSValue argFormIdJSValue = JS_NewString(ctx, std::to_string(formId).c_str()); - - JSValueConst argv[] = { argFormIdJSValue }; - JSValue retVal = Framework::QJSUtils::Call(ctx, paFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("PA: OnCastTemptoNormal FAILED!"); - return; - } - return; -} - -void QjsPaEngine::OnVisibilityChanged(const std::map& formEventsMap) -{ - LOGI("PA: QjsPaEngine OnVisibilityChanged"); - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Framework::QJSHandleScope handleScope(ctx); - JSValue paFunc = GetPaFunc("onVisibilityChange"); - - std::string strJsonResult("{"); - for (auto item = formEventsMap.begin(); item != formEventsMap.end(); item++) { - strJsonResult.append(ToJSONStringInt(std::to_string(item->first), std::to_string(item->second))); - strJsonResult.append(","); - } - strJsonResult = strJsonResult.substr(0, strJsonResult.size() - 1); - strJsonResult.append("}"); - - LOGI("PA: QjsPaEngine strJsonResult = %{public}s", strJsonResult.c_str()); - JSValue argJSValue = Framework::QJSUtils::ParseJSON(ctx, strJsonResult.c_str(), strJsonResult.size(), nullptr); - - JSValueConst argv[] = { argJSValue }; - JSValue retVal = Framework::QJSUtils::Call(ctx, paFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("PA: QjsPaEngine OnVisibilityChanged FAILED!"); - return; - } - return; -} - -int32_t QjsPaEngine::OnAcquireFormState(const OHOS::AAFwk::Want& want) -{ - LOGI("PA: QjsPaEngine OnAcquireFormState"); - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Framework::QJSHandleScope handleScope(ctx); - JSValue paFunc = GetPaFunc("onAcquireFormState"); - if (JS_IsUndefined(paFunc)) { - LOGI("no OnAcquireFormState!"); - return (int32_t)AppExecFwk::FormState::DEFAULT; - } - - napi_value napiWant = OHOS::AppExecFwk::WrapWant(reinterpret_cast(nativeEngine_), want); - NativeValue* nativeWant = reinterpret_cast(napiWant); - JSValue jsWant = (JSValue)*nativeWant; - JSValueConst argv[] = { jsWant }; - JSValue retVal = Framework::QJSUtils::Call(ctx, paFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("PA: OnAcquireFormState FAILED!"); - return (int32_t)AppExecFwk::FormState::DEFAULT; - } - - if (!JS_IsNumber(retVal)) { - LOGE("invalid return value!"); - return (int32_t)AppExecFwk::FormState::DEFAULT; - } - - int32_t formState = GetJsInt32Val(ctx, retVal); - LOGI("JsiPaEngine OnAcquireFormState, formState: %{public}d", formState); - return formState; -} - -void QjsPaEngine::OnCommand(const OHOS::AAFwk::Want& want, int startId) -{ - LOGI("OnCommand"); - JSContext* ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - - Framework::QJSHandleScope handleScope(ctx); - JSValue globalObj = JS_GetGlobalObject(ctx); - JSValue paObj = Framework::QJSUtils::GetPropertyStr(ctx, globalObj, "pa"); - if (!JS_IsObject(paObj)) { - LOGE("get onCommand function error"); - return; - } - JSValue onCommandFunc = Framework::QJSUtils::GetPropertyStr(ctx, paObj, "onCommand"); - if (!JS_IsFunction(ctx, onCommandFunc)) { - LOGE("onCommand function is not found!"); - JS_FreeValue(ctx, globalObj); - return; - } - napi_value napiWant = OHOS::AppExecFwk::WrapWant(reinterpret_cast(nativeEngine_), want); - NativeValue* nativeWant = reinterpret_cast(napiWant); - JSValue jsWant = (JSValue)*nativeWant; - JSValueConst argv[] = { jsWant, JS_NewInt32(ctx, startId) }; - JSValue retVal = Framework::QJSUtils::Call(ctx, onCommandFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("Qjs onCommand FAILED!"); - } - JS_FreeValue(ctx, globalObj); - JS_FreeValue(ctx, retVal); -} - -bool QjsPaEngine::OnShare(int64_t formId, OHOS::AAFwk::WantParams& wantParams) -{ - LOGD("PA: QjsPaEngine OnShare, begin"); - // call onCreate - auto ctx = engineInstance_->GetQjsContext(); - ACE_DCHECK(ctx); - Framework::QJSHandleScope handleScope(ctx); - auto paOnShareFunc = GetPaFunc("onShare"); - auto formIdJs = JS_NewString(ctx, std::to_string(formId).c_str()); - JSValueConst argv[] = { formIdJs }; - - auto retVal = Framework::QJSUtils::Call(ctx, paOnShareFunc, JS_UNDEFINED, countof(argv), argv); - if (JS_IsException(retVal)) { - LOGE("PA: QjsPaEngine QJSUtils::Call IsException"); - } - - auto nativeValue = reinterpret_cast(&retVal); - if (nativeValue->TypeOf() != NativeValueType::NATIVE_OBJECT) { - LOGE("%{public}s OnShare return value`s type is %{public}d", __func__, static_cast(nativeValue->TypeOf())); - return false; - } - - if (!OHOS::AppExecFwk::UnwrapWantParams( - reinterpret_cast(nativeEngine_), reinterpret_cast(nativeValue), wantParams)) { - LOGE("%{public}s OnShare UnwrapWantParams failed, return false", __func__); - return false; - } - - LOGD("PA: QjsPaEngine OnShare, end"); - return true; -} -} // namespace OHOS::Ace diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/qjs_pa_engine.h b/ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/qjs_pa_engine.h deleted file mode 100644 index e0e31b797..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/qjs_pa_engine.h +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_QUICK_JS_QJS_PA_ENGINE_H -#define FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_QUICK_JS_QJS_PA_ENGINE_H - -#include -#include -#include - -#include "abs_shared_result_set.h" -#include "data_ability_predicates.h" -#include "napi/native_api.h" -#include "napi/native_node_api.h" -#include "native_engine/impl/quickjs/quickjs_native_engine.h" -#include "result_set.h" -#include "third_party/quickjs/quickjs.h" -#include "uri.h" -#include "values_bucket.h" -#include "want.h" - -#include "adapter/ohos/entrance/pa_engine/backend_delegate.h" -#include "adapter/ohos/entrance/pa_engine/engine/common/js_backend_engine.h" -#include "base/memory/ace_type.h" -#include "base/utils/noncopyable.h" -#include "core/common/ace_page.h" -#include "core/common/js_message_dispatcher.h" - -namespace OHOS::Ace { - -// Each JsFrontend holds only one QjsPaEngineInstance. -class QjsPaEngineInstance final : public AceType, public JsBackendEngineInstance { -public: - explicit QjsPaEngineInstance(const RefPtr& delegate, int32_t instanceId) - : backendDelegate_(delegate), instanceId_(instanceId) - {} - ~QjsPaEngineInstance() override; - - bool InitJsEnv( - JSRuntime* runtime, JSContext* context, const std::unordered_map& extraNativeObject); - - JSRuntime* GetQjsRuntime() const - { - return runtime_; - } - - JSContext* GetQjsContext() const - { - return context_; - } - - void CallJs(const std::string& callbackId, const std::string& args, bool keepAlive = false, bool isGlobal = false); - - void SetJsMessageDispatcher(const RefPtr& dispatcher) - { - dispatcher_ = dispatcher; - } - - RefPtr GetDelegate() const - { - return backendDelegate_; - } - - bool CallPlatformFunction(const std::string& channel, std::vector&& data, int32_t id) - { - auto dispatcher = dispatcher_.Upgrade(); - if (dispatcher) { - dispatcher->Dispatch(channel, std::move(data), id); - return true; - } else { - LOGW("Dispatcher Upgrade fail when dispatch request message to platform"); - return false; - } - } - - bool PluginErrorCallback(int32_t callbackId, int32_t errorCode, std::string&& errorMessage) - { - auto dispatcher = dispatcher_.Upgrade(); - if (dispatcher) { - dispatcher->DispatchPluginError(callbackId, errorCode, std::move(errorMessage)); - return true; - } else { - LOGW("Dispatcher Upgrade fail when dispatch error message to platform"); - return false; - } - } - - JSValue FireJsEvent(const std::string& eventId, const std::string& param); - -private: - JSRuntime* runtime_ = nullptr; - JSContext* context_ = nullptr; - RefPtr backendDelegate_; - int32_t instanceId_; - - WeakPtr dispatcher_; - mutable std::mutex mutex_; - - ACE_DISALLOW_COPY_AND_MOVE(QjsPaEngineInstance); -}; - -using RdbValueBucketNewInstance = napi_value (*)(napi_env env, OHOS::NativeRdb::ValuesBucket& valueBucket); -using RdbValueBucketGetNativeObject = OHOS::NativeRdb::ValuesBucket* (*)(napi_env env, napi_value& value); -using RdbResultSetProxyNewInstance = napi_value (*)(napi_env env, OHOS::NativeRdb::AbsSharedResultSet* resultSet); -using RdbResultSetProxyGetNativeObject = OHOS::NativeRdb::AbsSharedResultSet* (*)(const napi_env& env, - const napi_value& arg); -using DataAbilityPredicatesNewInstance = napi_value (*)( - napi_env env, OHOS::NativeRdb::DataAbilityPredicates* predicates); -using DataAbilityPredicatesGetNativeObject = OHOS::NativeRdb::DataAbilityPredicates* (*)(const napi_env env, - const napi_value& arg); - -class QjsPaEngine : public JsBackendEngine { -public: - explicit QjsPaEngine(int32_t instanceId) : instanceId_(instanceId) {} - ~QjsPaEngine() override; - - bool Initialize(const RefPtr& delegate) override; - - // Load and initialize a JS bundle into the JS Framework - void LoadJs(const std::string& url, const OHOS::AAFwk::Want& want) override; - - void SetJsMessageDispatcher(const RefPtr& dispatcher) override; - - // destroy application instance according packageName - void DestroyApplication(const std::string& packageName) override; - - void OnCommandApplication(const std::string& intent, int startId) override; - - RefPtr GetGroupJsBridge() override - { - return nullptr; - } - - // Fire AsyncEvent on JS - void FireAsyncEvent(const std::string& eventId, const std::string& param) override; - - // Fire SyncEvent on JS - void FireSyncEvent(const std::string& eventId, const std::string& param) override; - - int32_t Insert(const Uri& uri, const OHOS::NativeRdb::ValuesBucket& value, const CallingInfo& callingInfo) override; - std::shared_ptr Call(const std::string& method, const std::string& arg, - const AppExecFwk::PacMap& pacMap, const CallingInfo& callingInfo) override; - std::shared_ptr Query(const Uri& uri, const std::vector& columns, - const OHOS::NativeRdb::DataAbilityPredicates& predicates, const CallingInfo& callingInfo) override; - int32_t Update(const Uri& uri, const OHOS::NativeRdb::ValuesBucket& value, - const OHOS::NativeRdb::DataAbilityPredicates& predicates, const CallingInfo& callingInfo) override; - int32_t Delete(const Uri& uri, const OHOS::NativeRdb::DataAbilityPredicates& predicates, - const CallingInfo& callingInfo) override; - - int32_t BatchInsert(const Uri& uri, const std::vector& values, - const CallingInfo& callingInfo) override; - std::string GetType(const Uri& uri, const CallingInfo& callingInfo) override; - std::vector GetFileTypes( - const Uri& uri, const std::string& mimeTypeFilter, const CallingInfo& callingInfo) override; - int32_t OpenFile(const Uri& uri, const std::string& mode, const CallingInfo& callingInfo) override; - int32_t OpenRawFile(const Uri& uri, const std::string& mode, const CallingInfo& callingInfo) override; - Uri NormalizeUri(const Uri& uri, const CallingInfo& callingInfo) override; - Uri DenormalizeUri(const Uri& uri, const CallingInfo& callingInfo) override; - sptr OnConnectService(const OHOS::AAFwk::Want& want) override; - void OnDisconnectService(const OHOS::AAFwk::Want& want) override; - void OnCreate(const OHOS::AAFwk::Want& want) override; - void OnDelete(const int64_t formId) override; - void OnTriggerEvent(const int64_t formId, const std::string& message) override; - void OnUpdate(const int64_t formId) override; - void OnCastTemptoNormal(const int64_t formId) override; - void OnVisibilityChanged(const std::map& formEventsMap) override; - int32_t OnAcquireFormState(const OHOS::AAFwk::Want& want) override; - void OnCommand(const OHOS::AAFwk::Want& want, int startId) override; - bool OnShare(int64_t formId, OHOS::AAFwk::WantParams& wantParams) override; - void DumpHeapSnapshot(bool isPrivate) override {} - -private: - void GetLoadOptions(std::string& optionStr); - JSValue GetPaFunc(const std::string& funcName); - - void LoadLibrary(); - void UnloadLibrary(); - - void RegisterWorker(); - void RegisterInitWorkerFunc(); - void RegisterAssetFunc(); - - RefPtr engineInstance_; - int32_t instanceId_ = 0; - QuickJSNativeEngine* nativeEngine_ = nullptr; - - void* libRdb_ = nullptr; - void* libDataAbility_ = nullptr; - RdbValueBucketNewInstance rdbValueBucketNewInstance_ = nullptr; - RdbValueBucketGetNativeObject rdbValueBucketGetNativeObject_ = nullptr; - RdbResultSetProxyNewInstance rdbResultSetProxyNewInstance_ = nullptr; - RdbResultSetProxyGetNativeObject rdbResultSetProxyGetNativeObject_ = nullptr; - DataAbilityPredicatesNewInstance dataAbilityPredicatesNewInstance_ = nullptr; - DataAbilityPredicatesGetNativeObject dataAbilityPredicatesGetNativeObject_ = nullptr; - void SetPostTask(NativeEngine* nativeEngine); - - ACE_DISALLOW_COPY_AND_MOVE(QjsPaEngine); -}; - -class FromBindingData : public AceType { - DECLARE_ACE_TYPE(FromBindingData, AceType); - -public: - FromBindingData(JSContext* ctx, JSValue value); - void Constructor(const std::string& param); - void UpdateData(const std::string& data); - std::string GetDataString() const; - void AddImageData(const std::string& name, void* buffer); - void RemoveImageData(const std::string& name); - -private: - JSContext* ctx_; - JSValue valueFromJs_; - ACE_DISALLOW_COPY_AND_MOVE(FromBindingData); -}; - -} // namespace OHOS::Ace - -#endif // FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_QUICK_JS_QJS_PA_ENGINE_H diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/qjs_pa_engine_loader.cpp b/ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/qjs_pa_engine_loader.cpp deleted file mode 100644 index 13d1ec0c5..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/qjs_pa_engine_loader.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "adapter/ohos/entrance/pa_engine/engine/quickjs/qjs_pa_engine_loader.h" - -#include "adapter/ohos/entrance/pa_engine/engine/quickjs/qjs_pa_engine.h" -#include "base/utils/macros.h" - -namespace OHOS::Ace { - -QjsPaEngineLoader::QjsPaEngineLoader() = default; -QjsPaEngineLoader::~QjsPaEngineLoader() = default; - -RefPtr QjsPaEngineLoader::CreateJsBackendEngine(int32_t instanceId) const -{ - return AceType::MakeRefPtr(instanceId); -} - -#if defined(BUILT_IN_JS_ENGINE) -JsBackendEngineLoader& JsBackendEngineLoader::Get(const char* sharedLibrary) -{ - return QjsPaEngineLoader::GetInstance(); -} -#else -extern "C" ACE_EXPORT void* OHOS_ACE_GetJsBackendEngineLoader() -{ - return &QjsPaEngineLoader::GetInstance(); -} -#endif - -} // namespace OHOS::Ace diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/qjs_pa_engine_loader.h b/ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/qjs_pa_engine_loader.h deleted file mode 100644 index 8bc359fd0..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/quickjs/qjs_pa_engine_loader.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_QUICK_JS_QJS_PA_ENGINE_LOADER_H -#define FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_QUICK_JS_QJS_PA_ENGINE_LOADER_H - -#include "adapter/ohos/entrance/pa_engine/engine/common/js_backend_engine_loader.h" -#include "base/utils/singleton.h" - -namespace OHOS::Ace { - -class QjsPaEngineLoader : public JsBackendEngineLoader, public Singleton { - DECLARE_SINGLETON(QjsPaEngineLoader) -public: - RefPtr CreateJsBackendEngine(int32_t instanceId) const final; -}; - -} // namespace OHOS::Ace - -#endif // FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_ENGINE_QUICK_JS_QJS_PA_ENGINE_LOADER_H diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/pa_backend.cpp b/ace_engine/adapter/fangtian/entrance/pa_engine/pa_backend.cpp deleted file mode 100644 index ac975ede6..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/pa_backend.cpp +++ /dev/null @@ -1,490 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "adapter/ohos/entrance/pa_engine/pa_backend.h" - -#include "napi_remote_object.h" - -#include "adapter/ohos/entrance/pa_engine/engine/common/js_backend_engine_loader.h" -#include "base/log/dump_log.h" -#include "base/log/event_report.h" -#include "base/utils/utils.h" - -namespace OHOS::Ace { - -RefPtr Backend::Create() -{ - return AceType::MakeRefPtr(); -} - -PaBackend::~PaBackend() noexcept -{ - // To guarantee the jsBackendEngine_ and delegate_ released in js thread - auto jsTaskExecutor = delegate_->GetAnimationJsTask(); - RefPtr jsBackendEngine; - jsBackendEngine.Swap(jsBackendEngine_); - RefPtr delegate; - delegate.Swap(delegate_); - jsTaskExecutor.PostTask([jsBackendEngine, delegate] {}); -} - -bool PaBackend::Initialize(BackendType type, const RefPtr& taskExecutor) -{ - LOGI("PaBackend initialize begin."); - type_ = type; - InitializeBackendDelegate(taskExecutor); - - taskExecutor->PostTask( - [weakEngine = WeakPtr(jsBackendEngine_), delegate = delegate_] { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_VOID_NOLOG(jsBackendEngine); - jsBackendEngine->Initialize(delegate); - }, - TaskExecutor::TaskType::JS); - - LOGI("PaBackend initialize end."); - return true; -} - -void PaBackend::LoadEngine(const char* libName, int32_t instanceId) -{ - auto& loader = JsBackendEngineLoader::Get(libName); - SetJsEngine(loader.CreateJsBackendEngine(instanceId)); -} - -void PaBackend::InitializeBackendDelegate(const RefPtr& taskExecutor) -{ - // builder callback - BackendDelegateImplBuilder builder; - builder.loadCallback = [weakEngine = WeakPtr(jsBackendEngine_)]( - const std::string& url, const OHOS::AAFwk::Want& want) { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_VOID_NOLOG(jsBackendEngine); - jsBackendEngine->LoadJs(url, want); - }; - - builder.transferCallback = [weakEngine = WeakPtr(jsBackendEngine_)]( - const RefPtr& dispatcher) { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_VOID_NOLOG(jsBackendEngine); - jsBackendEngine->SetJsMessageDispatcher(dispatcher); - }; - - builder.asyncEventCallback = [weakEngine = WeakPtr(jsBackendEngine_)]( - const std::string& eventId, const std::string& param) { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_VOID_NOLOG(jsBackendEngine); - jsBackendEngine->FireAsyncEvent(eventId, param); - }; - - builder.syncEventCallback = [weakEngine = WeakPtr(jsBackendEngine_)]( - const std::string& eventId, const std::string& param) { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_VOID_NOLOG(jsBackendEngine); - jsBackendEngine->FireSyncEvent(eventId, param); - }; - - builder.insertCallback = [weakEngine = WeakPtr(jsBackendEngine_)](const Uri& uri, - const OHOS::NativeRdb::ValuesBucket& value, - const CallingInfo& callingInfo) -> int32_t { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_RETURN_NOLOG(jsBackendEngine, 0); - return jsBackendEngine->Insert(uri, value, callingInfo); - }; - - builder.callCallback = [weakEngine = WeakPtr(jsBackendEngine_)](const std::string& method, - const std::string& arg, const AppExecFwk::PacMap& pacMap, - const CallingInfo& callingInfo) -> std::shared_ptr { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_RETURN_NOLOG(jsBackendEngine, nullptr); - return jsBackendEngine->Call(method, arg, pacMap, callingInfo); - }; - - builder.queryCallback = - [weakEngine = WeakPtr(jsBackendEngine_)](const Uri& uri, - const std::vector& columns, const OHOS::NativeRdb::DataAbilityPredicates& predicates, - const CallingInfo& callingInfo) -> std::shared_ptr { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_RETURN_NOLOG(jsBackendEngine, nullptr); - return jsBackendEngine->Query(uri, columns, predicates, callingInfo); - }; - - builder.updateCallback = [weakEngine = WeakPtr(jsBackendEngine_)](const Uri& uri, - const OHOS::NativeRdb::ValuesBucket& value, - const OHOS::NativeRdb::DataAbilityPredicates& predicates, - const CallingInfo& callingInfo) -> int32_t { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_RETURN_NOLOG(jsBackendEngine, 0); - return jsBackendEngine->Update(uri, value, predicates, callingInfo); - }; - - builder.deleteCallback = [weakEngine = WeakPtr(jsBackendEngine_)](const Uri& uri, - const OHOS::NativeRdb::DataAbilityPredicates& predicates, - const CallingInfo& callingInfo) -> int32_t { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_RETURN_NOLOG(jsBackendEngine, 0); - return jsBackendEngine->Delete(uri, predicates, callingInfo); - }; - - builder.batchInsertCallback = [weakEngine = WeakPtr(jsBackendEngine_)](const Uri& uri, - const std::vector& values, - const CallingInfo& callingInfo) -> int32_t { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_RETURN_NOLOG(jsBackendEngine, 0); - return jsBackendEngine->BatchInsert(uri, values, callingInfo); - }; - - builder.getTypeCallback = [weakEngine = WeakPtr(jsBackendEngine_)]( - const Uri& uri, const CallingInfo& callingInfo) -> std::string { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_RETURN_NOLOG(jsBackendEngine, std::string()); - return jsBackendEngine->GetType(uri, callingInfo); - }; - - builder.getFileTypesCallback = [weakEngine = WeakPtr(jsBackendEngine_)](const Uri& uri, - const std::string& mimeTypeFilter, - const CallingInfo& callingInfo) -> std::vector { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_RETURN_NOLOG(jsBackendEngine, std::vector()); - return jsBackendEngine->GetFileTypes(uri, mimeTypeFilter, callingInfo); - }; - - builder.openFileCallback = [weakEngine = WeakPtr(jsBackendEngine_)]( - const Uri& uri, const std::string& mode, const CallingInfo& callingInfo) -> int32_t { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_RETURN_NOLOG(jsBackendEngine, 0); - return jsBackendEngine->OpenFile(uri, mode, callingInfo); - }; - - builder.openRawFileCallback = [weakEngine = WeakPtr(jsBackendEngine_)](const Uri& uri, - const std::string& mode, const CallingInfo& callingInfo) -> int32_t { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_RETURN_NOLOG(jsBackendEngine, 0); - return jsBackendEngine->OpenRawFile(uri, mode, callingInfo); - }; - - builder.normalizeUriCallback = [weakEngine = WeakPtr(jsBackendEngine_)]( - const Uri& uri, const CallingInfo& callingInfo) -> Uri { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_RETURN_NOLOG(jsBackendEngine, Uri("")); - return jsBackendEngine->NormalizeUri(uri, callingInfo); - }; - - builder.denormalizeUriCallback = [weakEngine = WeakPtr(jsBackendEngine_)]( - const Uri& uri, const CallingInfo& callingInfo) -> Uri { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_RETURN_NOLOG(jsBackendEngine, Uri("")); - return jsBackendEngine->DenormalizeUri(uri, callingInfo); - }; - - builder.destroyApplicationCallback = [weakEngine = WeakPtr(jsBackendEngine_)]( - const std::string& packageName) { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_VOID_NOLOG(jsBackendEngine); - jsBackendEngine->DestroyApplication(packageName); - }; - - builder.connectCallback = [weakEngine = WeakPtr(jsBackendEngine_)]( - const OHOS::AAFwk::Want& want) -> sptr { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_RETURN_NOLOG(jsBackendEngine, nullptr); - return jsBackendEngine->OnConnectService(want); - }; - - builder.disConnectCallback = [weakEngine = WeakPtr(jsBackendEngine_)]( - const OHOS::AAFwk::Want& want) { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_VOID_NOLOG(jsBackendEngine); - jsBackendEngine->OnDisconnectService(want); - }; - - builder.commandCallback = [weakEngine = WeakPtr(jsBackendEngine_)]( - const OHOS::AAFwk::Want& want, int startId) { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_VOID_NOLOG(jsBackendEngine); - jsBackendEngine->OnCommand(want, startId); - }; - - builder.createFormCallback = [weakEngine = WeakPtr(jsBackendEngine_)]( - const OHOS::AAFwk::Want& want) { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_VOID_NOLOG(jsBackendEngine); - jsBackendEngine->OnCreate(want); - }; - - builder.deleteFormCallback = [weakEngine = WeakPtr(jsBackendEngine_)](const int64_t formId) { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_VOID_NOLOG(jsBackendEngine); - jsBackendEngine->OnDelete(formId); - }; - - builder.triggerEventCallback = [weakEngine = WeakPtr(jsBackendEngine_)]( - const int64_t formId, const std::string& message) { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_VOID_NOLOG(jsBackendEngine); - jsBackendEngine->OnTriggerEvent(formId, message); - }; - - builder.updateFormCallback = [weakEngine = WeakPtr(jsBackendEngine_)](const int64_t formId) { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_VOID_NOLOG(jsBackendEngine); - jsBackendEngine->OnUpdate(formId); - }; - - builder.castTemptoNormalCallback = [weakEngine = WeakPtr(jsBackendEngine_)](const int64_t formId) { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_VOID_NOLOG(jsBackendEngine); - jsBackendEngine->OnCastTemptoNormal(formId); - }; - - builder.visibilityChangedCallback = [weakEngine = WeakPtr(jsBackendEngine_)]( - const std::map& formEventsMap) { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_VOID_NOLOG(jsBackendEngine); - jsBackendEngine->OnVisibilityChanged(formEventsMap); - }; - - builder.acquireStateCallback = [weakEngine = WeakPtr(jsBackendEngine_)]( - const OHOS::AAFwk::Want& want) -> int32_t { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_RETURN_NOLOG(jsBackendEngine, -1); - return jsBackendEngine->OnAcquireFormState(want); - }; - - builder.commandApplicationCallback = [weakEngine = WeakPtr(jsBackendEngine_)]( - const std::string& intent, int startId) { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_VOID_NOLOG(jsBackendEngine); - jsBackendEngine->OnCommandApplication(intent, startId); - }; - - builder.commandCallback = [weakEngine = WeakPtr(jsBackendEngine_)]( - const OHOS::AAFwk::Want& want, int startId) { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_VOID_NOLOG(jsBackendEngine); - jsBackendEngine->OnCommand(want, startId); - }; - - builder.shareFormCallback = [weakEngine = WeakPtr(jsBackendEngine_)]( - int64_t formId, OHOS::AAFwk::WantParams& wantParams) { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_RETURN_NOLOG(jsBackendEngine, false); - return jsBackendEngine->OnShare(formId, wantParams); - }; - - builder.dumpHeapSnapshotCallback = [weakEngine = WeakPtr(jsBackendEngine_)](bool isPrivate) { - auto jsBackendEngine = weakEngine.Upgrade(); - CHECK_NULL_VOID_NOLOG(jsBackendEngine); - jsBackendEngine->DumpHeapSnapshot(isPrivate); - }; - - builder.taskExecutor = taskExecutor; - builder.type = type_; - - delegate_ = AceType::MakeRefPtr(builder); - - CHECK_NULL_VOID(jsBackendEngine_); - delegate_->SetGroupJsBridge(jsBackendEngine_->GetGroupJsBridge()); -} - -void PaBackend::UpdateState(Backend::State state) -{ - LOGI("UpdateState"); - switch (state) { - case Backend::State::ON_CREATE: - break; - case Backend::State::ON_DESTROY: - delegate_->OnApplicationDestroy("pa"); - break; - default: - LOGE("error State: %d", state); - } -} - -void PaBackend::OnCommand(const std::string& intent, int startId) -{ - delegate_->OnApplicationCommand(intent, startId); -} - -void PaBackend::OnCommand(const OHOS::AAFwk::Want& want, int startId) -{ - delegate_->OnCommand(want, startId); -} - -void PaBackend::RunPa(const std::string& url) {} - -void PaBackend::TransferJsResponseData(int callbackId, int32_t code, std::vector&& data) const -{ - delegate_->TransferJsResponseData(callbackId, code, std::move(data)); -} - -void PaBackend::TransferJsPluginGetError(int callbackId, int32_t errorCode, std::string&& errorMessage) const -{ - delegate_->TransferJsPluginGetError(callbackId, errorCode, std::move(errorMessage)); -} - -void PaBackend::TransferJsEventData(int32_t callbackId, int32_t code, std::vector&& data) const -{ - delegate_->TransferJsEventData(callbackId, code, std::move(data)); -} - -void PaBackend::LoadPluginJsCode(std::string&& jsCode) const -{ - delegate_->LoadPluginJsCode(std::move(jsCode)); -} - -void PaBackend::LoadPluginJsByteCode(std::vector&& jsCode, std::vector&& jsCodeLen) const -{ - delegate_->LoadPluginJsByteCode(std::move(jsCode), std::move(jsCodeLen)); -} - -void PaBackend::SetJsMessageDispatcher(const RefPtr& dispatcher) const -{ - delegate_->SetJsMessageDispatcher(dispatcher); -} - -void PaBackend::SetAssetManager(const RefPtr& assetManager) -{ - delegate_->SetAssetManager(assetManager); -} - -void PaBackend::MethodChannel(const std::string& methodName, std::string& jsonStr) -{ - delegate_->MethodChannel(methodName, jsonStr); -} - -int32_t PaBackend::Insert(const Uri& uri, const OHOS::NativeRdb::ValuesBucket& value) -{ - return delegate_->Insert(uri, value); -} - -std::shared_ptr PaBackend::Call( - const Uri& uri, const std::string& method, const std::string& arg, const AppExecFwk::PacMap& pacMap) -{ - return delegate_->Call(uri, method, arg, pacMap); -} - -std::shared_ptr PaBackend::Query( - const Uri& uri, const std::vector& columns, const OHOS::NativeRdb::DataAbilityPredicates& predicates) -{ - return delegate_->Query(uri, columns, predicates); -} - -int32_t PaBackend::Update(const Uri& uri, const OHOS::NativeRdb::ValuesBucket& value, - const OHOS::NativeRdb::DataAbilityPredicates& predicates) -{ - return delegate_->Update(uri, value, predicates); -} - -int32_t PaBackend::Delete(const Uri& uri, const OHOS::NativeRdb::DataAbilityPredicates& predicates) -{ - return delegate_->Delete(uri, predicates); -} - -int32_t PaBackend::BatchInsert(const Uri& uri, const std::vector& values) -{ - return delegate_->BatchInsert(uri, values); -} - -std::string PaBackend::GetType(const Uri& uri) -{ - return delegate_->GetType(uri); -} - -std::vector PaBackend::GetFileTypes(const Uri& uri, const std::string& mimeTypeFilter) -{ - return delegate_->GetFileTypes(uri, mimeTypeFilter); -} - -int32_t PaBackend::OpenFile(const Uri& uri, const std::string& mode) -{ - return delegate_->OpenFile(uri, mode); -} - -int32_t PaBackend::OpenRawFile(const Uri& uri, const std::string& mode) -{ - return delegate_->OpenRawFile(uri, mode); -} - -Uri PaBackend::NormalizeUri(const Uri& uri) -{ - return delegate_->NormalizeUri(uri); -} - -Uri PaBackend::DenormalizeUri(const Uri& uri) -{ - return delegate_->DenormalizeUri(uri); -} - -void PaBackend::RunPa(const std::string& url, const OHOS::AAFwk::Want& want) -{ - delegate_->RunPa(url, want); -} - -void PaBackend::OnCreate(const OHOS::AAFwk::Want& want) -{ - delegate_->OnCreate(want); -} - -void PaBackend::OnDelete(const int64_t formId) -{ - delegate_->OnDelete(formId); -} - -void PaBackend::OnTriggerEvent(const int64_t formId, const std::string& message) -{ - delegate_->OnTriggerEvent(formId, message); -} - -void PaBackend::OnUpdate(const int64_t formId) -{ - delegate_->OnUpdate(formId); -} - -void PaBackend::OnCastTemptoNormal(const int64_t formId) -{ - delegate_->OnCastTemptoNormal(formId); -} - -void PaBackend::OnVisibilityChanged(const std::map& formEventsMap) -{ - delegate_->OnVisibilityChanged(formEventsMap); -} - -int32_t PaBackend::OnAcquireFormState(const OHOS::AAFwk::Want& want) -{ - return delegate_->OnAcquireFormState(want); -} - -sptr PaBackend::OnConnect(const OHOS::AAFwk::Want& want) -{ - return delegate_->OnConnect(want); -} - -void PaBackend::OnDisConnect(const OHOS::AAFwk::Want& want) -{ - delegate_->OnDisConnect(want); -} - -bool PaBackend::OnShare(int64_t formId, OHOS::AAFwk::WantParams& wantParams) -{ - return delegate_->OnShare(formId, wantParams); -} - -void PaBackend::DumpHeapSnapshot(bool isPrivate) -{ - delegate_->DumpHeapSnapshot(isPrivate); -} -} // namespace OHOS::Ace diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/pa_backend.h b/ace_engine/adapter/fangtian/entrance/pa_engine/pa_backend.h deleted file mode 100644 index fd9a5bb44..000000000 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/pa_backend.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_PA_BACKEND_H -#define FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_PA_BACKEND_H - -#include -#include - -#include "abs_shared_result_set.h" -#include "data_ability_predicates.h" -#include "form_provider_info.h" -#include "iremote_object.h" -#include "values_bucket.h" -#include "want.h" - -#include "adapter/ohos/entrance/pa_engine/backend_delegate_impl.h" -#include "adapter/ohos/entrance/pa_engine/engine/common/js_backend_engine.h" -#include "base/memory/ace_type.h" -#include "base/utils/string_utils.h" -#include "core/common/backend.h" - -namespace OHOS::Ace { - -class PaBackend : public Backend { - DECLARE_ACE_TYPE(PaBackend, Backend); - -public: - PaBackend() = default; - ~PaBackend() override; - - bool Initialize(BackendType type, const RefPtr& taskExecutor) override; - - void LoadEngine(const char* libName, int32_t instanceId) override; - - void UpdateState(Backend::State state) override; - - void SetJsMessageDispatcher(const RefPtr& dispatcher) const override; - - BackendType GetType() override - { - return type_; - } - - void MethodChannel(const std::string& methodName, std::string& jsonStr) override; - - void RunPa(const std::string& url) override; - - void OnCommand(const std::string& intent, int startId) override; - - void TransferJsResponseData(int32_t callbackId, int32_t code, std::vector&& data) const override; - - void TransferJsPluginGetError(int32_t callbackId, int32_t errorCode, std::string&& errorMessage) const override; - - void TransferJsEventData(int32_t callbackId, int32_t code, std::vector&& data) const override; - - void LoadPluginJsCode(std::string&& jsCode) const override; - - void LoadPluginJsByteCode(std::vector&& jsCode, std::vector&& jsCodeLen) const override; - - void SetJsEngine(const RefPtr& jsBackEngine) - { - jsBackendEngine_ = jsBackEngine; - } - - void SetAssetManager(const RefPtr& assetManager) override; - - void RunPa(const std::string& url, const OHOS::AAFwk::Want& want); - void OnCreate(const OHOS::AAFwk::Want& want); - void OnDelete(const int64_t formId); - void OnTriggerEvent(const int64_t formId, const std::string& message); - void OnUpdate(const int64_t formId); - void OnCastTemptoNormal(const int64_t formId); - void OnVisibilityChanged(const std::map& formEventsMap); - int32_t OnAcquireFormState(const OHOS::AAFwk::Want& want); - sptr OnConnect(const OHOS::AAFwk::Want& want); - void OnDisConnect(const OHOS::AAFwk::Want& want); - - int32_t Insert(const Uri& uri, const OHOS::NativeRdb::ValuesBucket& value); - std::shared_ptr Query(const Uri& uri, const std::vector& columns, - const OHOS::NativeRdb::DataAbilityPredicates& predicates); - int32_t Update(const Uri& uri, const OHOS::NativeRdb::ValuesBucket& value, - const OHOS::NativeRdb::DataAbilityPredicates& predicates); - int32_t Delete(const Uri& uri, const OHOS::NativeRdb::DataAbilityPredicates& predicates); - - int32_t BatchInsert(const Uri& uri, const std::vector& values); - std::string GetType(const Uri& uri); - std::vector GetFileTypes(const Uri& uri, const std::string& mimeTypeFilter); - int32_t OpenFile(const Uri& uri, const std::string& mode); - int32_t OpenRawFile(const Uri& uri, const std::string& mode); - Uri NormalizeUri(const Uri& uri); - Uri DenormalizeUri(const Uri& uri); - std::shared_ptr Call(const Uri& uri, - const std::string& method, const std::string& arg, const AppExecFwk::PacMap& pacMap); - bool OnShare(int64_t formId, OHOS::AAFwk::WantParams &wantParams); - - AppExecFwk::FormProviderData GetFormData() const - { - if (jsBackendEngine_) { - return jsBackendEngine_->GetFormData(); - } else { - LOGE("PA: PaBackend::jsBackendEngine_ is null"); - return AppExecFwk::FormProviderData(""); - } - } - - void OnCommand(const OHOS::AAFwk::Want &want, int startId); - void DumpHeapSnapshot(bool isPrivate) override; - -private: - void InitializeBackendDelegate(const RefPtr& taskExecutor); - BackendType type_ = BackendType::SERVICE; - - RefPtr delegate_; - RefPtr jsBackendEngine_; -}; - -} // namespace OHOS::Ace - -#endif // FOUNDATION_ACE_ADAPTER_OHOS_ENTRANCE_PA_ENGINE_PA_BACKEND_H diff --git a/ace_engine/adapter/fangtian/ft_build/config.gni b/ace_engine/adapter/fangtian/ft_build/config.gni index 23a9a5ab4..fc5f535f4 100644 --- a/ace_engine/adapter/fangtian/ft_build/config.gni +++ b/ace_engine/adapter/fangtian/ft_build/config.gni @@ -49,7 +49,8 @@ if (ace_engine_feature_enable_web) { } is_experiment_build = false -use_build_in_js_engine = false +#need js engine for fangtian +use_build_in_js_engine = true use_external_icu = "shared" use_curl_download = true ohos_standard_fontmgr = false @@ -60,7 +61,7 @@ form_components_support = false remote_window_support = false plugin_components_support = false xcomponent_components_support = false -pixel_map_support = true +pixel_map_support = false js_pa_support = false connect_server_support = true hdc_register_support = false diff --git a/ace_engine/adapter/preview/ft_build/BUILD.gn b/ace_engine/adapter/preview/ft_build/BUILD.gn deleted file mode 100644 index 47eb3b171..000000000 --- a/ace_engine/adapter/preview/ft_build/BUILD.gn +++ /dev/null @@ -1,38 +0,0 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//ace_engine/build/ace_lib.gni") - -# build for preview shared library -template("libace_engine") { - forward_variables_from(invoker, "*") - - ohos_shared_library(target_name) { - deps = [ "$ace_root/ft_build/build:libace_static_$platform" ] - subsystem_name = ace_engine_subsystem - part_name = ace_engine_part - } -} - -libace_engine("libace_engine_windows") { - platform = "windows" -} - -libace_engine("libace_engine_mac") { - platform = "mac" -} - -libace_engine("libace_engine_linux") { - platform = "linux" -} diff --git a/ace_engine/adapter/preview/ft_build/config.gni b/ace_engine/adapter/preview/ft_build/config.gni deleted file mode 100644 index 8467bc7b9..000000000 --- a/ace_engine/adapter/preview/ft_build/config.gni +++ /dev/null @@ -1,23 +0,0 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# source code for Windows. -use_mingw_win = "${current_os}_${current_cpu}" == "mingw_x86_64" - -# source code for linux. -use_linux = "${current_os}_${current_cpu}" == "linux_x64" - -# source code for mac. - -use_mac = "${current_os}_${current_cpu}" == "mac_x64" || - "${current_os}_${current_cpu}" == "mac_arm64" diff --git a/ace_engine/adapter/preview/ft_build/config_linux.gni b/ace_engine/adapter/preview/ft_build/config_linux.gni deleted file mode 100644 index 6289b92d7..000000000 --- a/ace_engine/adapter/preview/ft_build/config_linux.gni +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("preview_common.gni") - -# linux platform defines and configs -defines += [ - "LINUX_PLATFORM", - "GPU_DISABLED", - "SK_BUILD_FONT_MGR_FOR_PREVIEW_LINUX", -] - -libace_target = - "//ace_engine/adapter/preview/build:libace_engine_linux" diff --git a/ace_engine/adapter/preview/ft_build/config_mac.gni b/ace_engine/adapter/preview/ft_build/config_mac.gni deleted file mode 100644 index 15bdee769..000000000 --- a/ace_engine/adapter/preview/ft_build/config_mac.gni +++ /dev/null @@ -1,23 +0,0 @@ -# Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("preview_common.gni") - -# windows platform defines and configs -defines += [ - "MAC_PLATFORM", - "SK_BUILD_FONT_MGR_FOR_PREVIEW_MAC", -] - -libace_target = - "//ace_engine/adapter/preview/build:libace_engine_mac" diff --git a/ace_engine/adapter/preview/ft_build/config_windows.gni b/ace_engine/adapter/preview/ft_build/config_windows.gni deleted file mode 100644 index 934953a91..000000000 --- a/ace_engine/adapter/preview/ft_build/config_windows.gni +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("preview_common.gni") - -# windows platform defines and configs -defines += [ - "WINDOWS_PLATFORM", - "_USE_MATH_DEFINES", - "NOGDI", - "U_CHARSET_IS_UTF8=1", - "SK_BUILD_FOR_WIN", - "SK_BUILD_FONT_MGR_FOR_PREVIEW_WIN", -] - -cflags_cc += [ - "-DWINVER=0x0601", - "-Wno-inconsistent-dllimport", - "-Wno-macro-redefined", - "-Wno-missing-braces", - "-Wno-used-but-marked-unused", -] - -libace_target = - "//ace_engine/adapter/preview/build:libace_engine_windows" diff --git a/ace_engine/adapter/preview/ft_build/platform.gni b/ace_engine/adapter/preview/ft_build/platform.gni deleted file mode 100644 index 5a7b31314..000000000 --- a/ace_engine/adapter/preview/ft_build/platform.gni +++ /dev/null @@ -1,50 +0,0 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("config.gni") - -platforms = [] - -if (use_mingw_win || true) { - windows_platform = { - name = "windows" - config = { - import("config_windows.gni") - } - } - - platforms += [ windows_platform ] -} - -if (use_mac || true) { - mac_platform = { - name = "mac" - config = { - import("config_mac.gni") - } - } - - platforms += [ mac_platform ] -} - -if (use_linux || true) { - linux_platform = { - name = "linux" - config = { - import("config_linux.gni") - } - } - - platforms += [ linux_platform ] -} diff --git a/ace_engine/adapter/preview/ft_build/preview_common.gni b/ace_engine/adapter/preview/ft_build/preview_common.gni deleted file mode 100644 index 491532123..000000000 --- a/ace_engine/adapter/preview/ft_build/preview_common.gni +++ /dev/null @@ -1,100 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -xcomponent_components_support = false -form_components_support = false -remote_window_support = false -use_curl_download = true -accessibility_support = true -rich_components_support = true -ohos_standard_fontmgr = true -image_components_support = false -plugin_components_support = false -enable_ability_component = false -enable_system_clipboard = false -advance_components_support = false -connect_server_support = false -enable_rosen_backend = true -enable_standard_input = false -video_components_support = false -web_components_support = false -preview_support = true -build_for_preview = true - -# js engine common configs -js_pa_support = false -use_build_in_js_engine = true - -ark_engine = { - engine_name = "ark" - engine_path = "jsi" - engine_defines = [ "USE_ARK_ENGINE" ] -} -js_engines = [ ark_engine ] - -platform_deps = [ - "//ace_engine/adapter/preview/entrance:preview_entrance_source", - "//ace_engine/adapter/preview/external:preview_external_source", - "//ace_engine/adapter/preview/inspector:preview_inspector_source", - "//ace_engine/adapter/preview/osal:preview_osal_source", -] - -cflags_cc = [ - "-std=c++17", - "-Wno-thread-safety-attributes", - "-Wno-thread-safety-analysis", - "-Wno-ignored-attributes", - "-Wno-unknown-pragmas", -] - -defines = [ "UNICODE" ] - -if (defined(web_components_support) && web_components_support) { - defines += [ "WEB_SUPPORTED" ] -} - -if (defined(video_components_support) && video_components_support) { - defines += [ "VIDEO_SUPPORTED" ] -} - -if (defined(xcomponent_components_support) && xcomponent_components_support) { - defines += [ "XCOMPONENT_SUPPORTED" ] -} - -if (defined(form_components_support) && form_components_support) { - defines += [ "FORM_SUPPORTED" ] -} - -if (defined(remote_window_support) && remote_window_support) { - defines += [ "REMOTE_WINDOW_SUPPORTED" ] -} - -if (defined(image_components_support) && image_components_support) { - defines += [ "IMAGE_SUPPORTED" ] -} - -if (defined(plugin_components_support) && plugin_components_support) { - defines += [ "PLUGIN_COMPONENT_SUPPORTED" ] -} - -if (defined(enable_ability_component) && enable_ability_component) { - defines += [ "ABILITY_COMPONENT_SUPPORTED" ] -} - -if (defined(preview_support) && preview_support) { - defines += [ "PREVIEW" ] -} - -if (defined(enable_rosen_backend) && enable_rosen_backend) { - defines += [ "ENABLE_ROSEN_BACKEND" ] -} diff --git a/ace_engine/frameworks/bridge/declarative_frontend/engine/declarative_engine_loader.cpp b/ace_engine/frameworks/bridge/declarative_frontend/engine/declarative_engine_loader.cpp index 426645da2..20a7047dd 100644 --- a/ace_engine/frameworks/bridge/declarative_frontend/engine/declarative_engine_loader.cpp +++ b/ace_engine/frameworks/bridge/declarative_frontend/engine/declarative_engine_loader.cpp @@ -81,4 +81,4 @@ extern "C" ACE_FORCE_EXPORT void* OHOS_ACE_GetJsEngineLoader() } #endif -} // namespace OHOS::Ace::Framework \ No newline at end of file +} // namespace OHOS::Ace::Framework diff --git a/ace_engine/frameworks/bridge/declarative_frontend/engine/jsi/ft_build/BUILD.gn b/ace_engine/frameworks/bridge/declarative_frontend/engine/jsi/ft_build/BUILD.gn new file mode 100644 index 000000000..d3d87497a --- /dev/null +++ b/ace_engine/frameworks/bridge/declarative_frontend/engine/jsi/ft_build/BUILD.gn @@ -0,0 +1,172 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#import("//arkcompiler/ets_frontend/ts2panda/ts2abc_config.gni") +import("//build/gn/fangtian.gni") +import("//ace_engine/ft_build/ace_config.gni") +import("//ace_engine/ft_build/build/ace_gen_obj.gni") +import("//ace_engine/ft_build/build/uicast.gni") + +base_output_path = get_label_info(":gen_abc_proxyclass", "target_out_dir") +abcproxyclass_obj_path = base_output_path + "/abc_proxy_class.o" +abcenumstyle_obj_path = base_output_path + "/abc_enum_style.o" +jsmocksystemplugin_obj_path = base_output_path + "/abc_js_mock_system_plugin.o" + +#ts2abc_gen_abc("gen_stateMgmt_abc") { +# extra_visibility = [ ":*" ] # Only targets in this file can depend on this. +# src_js = rebase_path( +# "//foundation/arkui/ace_engine/frameworks/bridge/declarative_frontend/engine/stateMgmt.js") +# dst_file = rebase_path(base_output_path + "/stateMgmt.abc") +# +# in_puts = [ "//foundation/arkui/ace_engine/frameworks/bridge/declarative_frontend/engine/stateMgmt.js" ] +# out_puts = [ base_output_path + "/stateMgmt.abc" ] +#} +# +#ts2abc_gen_abc("gen_jsEnumStyle_abc") { +# extra_visibility = [ ":*" ] # Only targets in this file can depend on this. +# src_js = rebase_path( +# "//foundation/arkui/ace_engine/frameworks/bridge/declarative_frontend/engine/jsEnumStyle.js") +# dst_file = rebase_path(base_output_path + "/jsEnumStyle.abc") +# +# in_puts = [ "//foundation/arkui/ace_engine/frameworks/bridge/declarative_frontend/engine/jsEnumStyle.js" ] +# out_puts = [ base_output_path + "/jsEnumStyle.abc" ] +#} +# +#ts2abc_gen_abc("gen_js_mock_system_plugin_abc") { +# extra_visibility = [ ":*" ] # Only targets in this file can depend on this. +# src_js = rebase_path( +# "$root_out_dir/obj/third_party/jsframework/dist/jsMockSystemPlugin.js") +# dst_file = rebase_path(base_output_path + "/jsMockSystemPlugin.abc") +# +# in_puts = [ rebase_path( +# "$root_out_dir/obj/third_party/jsframework/dist/jsMockSystemPlugin.js") ] +# out_puts = [ base_output_path + "/jsMockSystemPlugin.abc" ] +# extra_dependencies = [ "//third_party/jsframework:gen_snapshot" ] +#} +# +#gen_obj("abc_proxyclass") { +# input = base_output_path + "/stateMgmt.abc" +# if (use_mac || use_mingw_win || use_ios || use_linux) { +# abcproxyclass_obj_path = base_output_path + "/js_proxy_class.c" +# } +# output = abcproxyclass_obj_path +# snapshot_dep = [ ":gen_stateMgmt_abc" ] +#} +# +#gen_obj("abc_enum_style") { +# input = base_output_path + "/jsEnumStyle.abc" +# if (use_mac || use_mingw_win || use_linux || use_ios) { +# abcenumstyle_obj_path = base_output_path + "/jsEnumStyle.c" +# } +# output = abcenumstyle_obj_path +# snapshot_dep = [ ":gen_jsEnumStyle_abc" ] +#} +# +#gen_obj("abc_mock_system_plugin") { +# input = base_output_path + "/jsMockSystemPlugin.abc" +# if (use_mac || use_mingw_win || use_linux) { +# jsmocksystemplugin_obj_path = base_output_path + "/js_mock_system_plugin.c" +# } +# output = jsmocksystemplugin_obj_path +# snapshot_dep = [ ":gen_js_mock_system_plugin_abc" ] +#} + +template("declarative_js_engine_ark") { + forward_variables_from(invoker, "*") + + ft_source_set(target_name) { + defines += invoker.defines + if (target_cpu == "arm64") { + defines += [ "APP_USE_ARM64" ] + } else if (target_cpu == "arm") { + defines += [ "APP_USE_ARM" ] + } + + configs = [ "$ace_root/ft_build:ace_config" ] + + #configs += [ "${uicast_configs.ace_uicast}:uicast_jsi_config" ] + + public_configs = [ "//arkcompiler/ets_runtime/ft_build:ark_jsruntime_public_config" ] + + sources = [ + "../js_converter.cpp", + "../jsi_declarative_engine.cpp", + "../jsi_declarative_group_js_bridge.cpp", + "../jsi_object_template.cpp", + "../jsi_types.cpp", + "../jsi_view_register.cpp", + "../modules/jsi_app_module.cpp", + "../modules/jsi_context_module.cpp", + "../modules/jsi_curves_module.cpp", + "../modules/jsi_matrix4_module.cpp", + "../modules/jsi_module_manager.cpp", + "../modules/jsi_router_module.cpp", + "../modules/jsi_syscap_module.cpp", + "../modules/jsi_timer_module.cpp", + ] + deps = [] + sources += [ "../jsi_animator_model_ng_impl.cpp" ] + deps += [ "$ace_root/frameworks/core/components/theme/ft_build:build_theme_code" ] + + defines += uicast_configs.uicast_defines + sources += uicast_configs.uicast_jsi_sources + + deps += [ "//arkcompiler/ets_runtime/ft_build:libark_jsruntime" ] + + if (defined(config.build_for_preview) && config.build_for_preview) { + deps += [ ":gen_obj_src_abc_mock_system_plugin" ] + sources += [ "utils/jsi_module_searcher.cpp" ] + } else if (!defined(config.use_build_in_js_engine) || + !config.use_build_in_js_engine) { + sources += [ + "$ace_root/frameworks/bridge/js_frontend/engine/jsi/ark_js_runtime.cpp", + "$ace_root/frameworks/bridge/js_frontend/engine/jsi/ark_js_value.cpp", + "$ace_root/frameworks/bridge/js_frontend/engine/jsi/jsi_base_utils.cpp", + ] + } + + # if napi support + #deps += [ "$ace_napi/ft_build:ace_napi_ark" ] + #deps += [ "$ace_napi/ft_bulld:ace_napi" ] + + #deps += [ + # ":gen_obj_src_abc_enum_style", + # ":gen_obj_src_abc_proxyclass", + #] + } +} + +foreach(item, ace_platforms) { + platform = item.name + engine_config = { + } + engine_config = item.config + support_engines = [] + support_engines = engine_config.js_engines + foreach(engine, support_engines) { + if (engine.engine_name == "ark") { + declarative_js_engine_ark("declarative_js_engine_bridge_ark_$platform") { + defines = engine.engine_defines + config = { + } + + if (defined(item.config)) { + config = item.config + } + if (defined(config.defines)) { + defines += config.defines + } + } + } + } +} diff --git a/ace_engine/frameworks/bridge/declarative_frontend/ft_build/BUILD.gn b/ace_engine/frameworks/bridge/declarative_frontend/ft_build/BUILD.gn index 5dc59d551..fcea4e3ba 100644 --- a/ace_engine/frameworks/bridge/declarative_frontend/ft_build/BUILD.gn +++ b/ace_engine/frameworks/bridge/declarative_frontend/ft_build/BUILD.gn @@ -14,6 +14,7 @@ import("//build/gn/fangtian.gni") import("//ace_engine/ft_build/ace_config.gni") import("//ace_engine/ft_build/build/ace_gen_obj.gni") +import("//ace_engine/ft_build/build/uicast.gni") # declarative frontend source template("declarative_frontend") { @@ -98,7 +99,220 @@ template("declarative_js_engine") { public_deps = [] configs = [ "$ace_root/ft_build:ace_config" ] - sources = [] + sources = [ + "../engine/bindings_implementation.cpp", + "../engine/declarative_engine_loader.cpp", + "../engine/functions/js_animator_function.cpp", + "../engine/functions/js_click_function.cpp", + "../engine/functions/js_clipboard_function.cpp", + "../engine/functions/js_drag_function.cpp", + "../engine/functions/js_focus_function.cpp", + "../engine/functions/js_foreach_function.cpp", + "../engine/functions/js_function.cpp", + "../engine/functions/js_gesture_function.cpp", + "../engine/functions/js_hover_function.cpp", + "../engine/functions/js_key_function.cpp", + "../engine/functions/js_mouse_function.cpp", + "../engine/functions/js_on_area_change_function.cpp", + "../engine/functions/js_page_transition_function.cpp", + "../engine/functions/js_pan_function.cpp", + "../engine/functions/js_touch_function.cpp", + "../engine/functions/js_webview_function.cpp", + "../engine/js_types.cpp", + "../interfaces/profiler/js_profiler.cpp", + "../jsview/action_sheet/js_action_sheet.cpp", + "../jsview/dialog/js_alert_dialog.cpp", + "../jsview/dialog/js_custom_dialog_controller.cpp", + "../jsview/js_animator.cpp", + "../jsview/js_badge.cpp", + "../jsview/js_blank.cpp", + "../jsview/js_button.cpp", + "../jsview/js_calendar.cpp", + "../jsview/js_calendar_controller.cpp", + "../jsview/js_canvas.cpp", + "../jsview/js_canvas_gradient.cpp", + "../jsview/js_canvas_image_data.cpp", + "../jsview/js_canvas_path.cpp", + "../jsview/js_canvas_renderer.cpp", + "../jsview/js_checkbox.cpp", + "../jsview/js_checkboxgroup.cpp", + "../jsview/js_circle.cpp", + "../jsview/js_clipboard.cpp", + "../jsview/js_column.cpp", + "../jsview/js_column_split.cpp", + "../jsview/js_common_view.cpp", + "../jsview/js_container_base.cpp", + "../jsview/js_counter.cpp", + "../jsview/js_data_panel.cpp", + "../jsview/js_datepicker.cpp", + "../jsview/js_distributed.cpp", + "../jsview/js_divider.cpp", + "../jsview/js_ellipse.cpp", + "../jsview/js_environment.cpp", + "../jsview/js_flex.cpp", + "../jsview/js_flex_impl.cpp", + "../jsview/js_foreach.cpp", + "../jsview/js_gauge.cpp", + "../jsview/js_gesture.cpp", + "../jsview/js_grid.cpp", + "../jsview/js_grid_col.cpp", + "../jsview/js_grid_container.cpp", + "../jsview/js_grid_item.cpp", + "../jsview/js_grid_row.cpp", + "../jsview/js_hyperlink.cpp", + "../jsview/js_if_else.cpp", + "../jsview/js_image.cpp", + "../jsview/js_image_animator.cpp", + "../jsview/js_indexer.cpp", + "../jsview/js_interactable_view.cpp", + "../jsview/js_lazy_foreach.cpp", + "../jsview/js_line.cpp", + "../jsview/js_list.cpp", + "../jsview/js_list_item.cpp", + "../jsview/js_list_item_group.cpp", + "../jsview/js_loading_progress.cpp", + "../jsview/js_local_storage.cpp", + "../jsview/js_marquee.cpp", + "../jsview/js_matrix2d.cpp", + "../jsview/js_menu.cpp", + "../jsview/js_menu_item.cpp", + "../jsview/js_menu_item_group.cpp", + "../jsview/js_navdestination.cpp", + "../jsview/js_navigation.cpp", + "../jsview/js_navigator.cpp", + "../jsview/js_navrouter.cpp", + "../jsview/js_offscreen_canvas.cpp", + "../jsview/js_offscreen_rendering_context.cpp", + "../jsview/js_page_transition.cpp", + "../jsview/js_pan_handler.cpp", + "../jsview/js_path.cpp", + "../jsview/js_path2d.cpp", + "../jsview/js_pattern_lock.cpp", + "../jsview/js_persistent.cpp", + "../jsview/js_polygon.cpp", + "../jsview/js_polyline.cpp", + "../jsview/js_progress.cpp", + "../jsview/js_qrcode.cpp", + "../jsview/js_radio.cpp", + "../jsview/js_rect.cpp", + "../jsview/js_refresh.cpp", + "../jsview/js_relative_container.cpp", + "../jsview/js_render_image.cpp", + "../jsview/js_rendering_context.cpp", + "../jsview/js_rendering_context_settings.cpp", + "../jsview/js_row.cpp", + "../jsview/js_row_split.cpp", + "../jsview/js_scroll.cpp", + "../jsview/js_scroller.cpp", + "../jsview/js_search.cpp", + "../jsview/js_select.cpp", + "../jsview/js_shape.cpp", + "../jsview/js_shape_abstract.cpp", + "../jsview/js_sheet.cpp", + "../jsview/js_side_bar.cpp", + "../jsview/js_slider.cpp", + "../jsview/js_sliding_panel.cpp", + "../jsview/js_span.cpp", + "../jsview/js_stack.cpp", + "../jsview/js_stepper.cpp", + "../jsview/js_stepper_item.cpp", + "../jsview/js_swiper.cpp", + "../jsview/js_tab_content.cpp", + "../jsview/js_tabs.cpp", + "../jsview/js_tabs_controller.cpp", + "../jsview/js_text.cpp", + "../jsview/js_text_clock.cpp", + "../jsview/js_textarea.cpp", + "../jsview/js_textfield.cpp", + "../jsview/js_textinput.cpp", + "../jsview/js_textpicker.cpp", + "../jsview/js_texttimer.cpp", + "../jsview/js_toggle.cpp", + "../jsview/js_touch_handler.cpp", + "../jsview/js_utils.cpp", + "../jsview/js_view.cpp", + "../jsview/js_view_abstract.cpp", + "../jsview/js_view_context.cpp", + "../jsview/js_view_functions.cpp", + "../jsview/js_view_measure_layout.cpp", + "../jsview/js_view_stack_processor.cpp", + "../jsview/js_water_flow.cpp", + "../jsview/js_water_flow_item.cpp", + "../jsview/menu/js_context_menu.cpp", + "../jsview/scroll_bar/js_scroll_bar.cpp", + "../sharedata/js_share_data.cpp", + "../view_stack_processor.cpp", + + # Models implemenations for classic fw + "../jsview/models/animator_model_impl.cpp", + "../jsview/models/checkbox_model_impl.cpp", + "../jsview/models/checkboxgroup_model_impl.cpp", + "../jsview/models/circle_model_impl.cpp", + "../jsview/models/column_model_impl.cpp", + "../jsview/models/counter_model_impl.cpp", + "../jsview/models/data_panel_model_impl.cpp", + "../jsview/models/divider_model_impl.cpp", + "../jsview/models/ellipse_model_impl.cpp", + "../jsview/models/flex_model_impl.cpp", + "../jsview/models/for_each_model_impl.cpp", + "../jsview/models/gauge_model_impl.cpp", + "../jsview/models/grid_col_model_impl.cpp", + "../jsview/models/grid_container_model_impl.cpp", + "../jsview/models/grid_item_model_impl.cpp", + "../jsview/models/grid_model_impl.cpp", + "../jsview/models/grid_row_model_impl.cpp", + "../jsview/models/hyperlink_model_impl.cpp", + "../jsview/models/if_else_model_impl.cpp", + "../jsview/models/image_model_impl.cpp", + "../jsview/models/lazy_for_each_model_impl.cpp", + "../jsview/models/line_model_impl.cpp", + "../jsview/models/linear_split_model_impl.cpp", + "../jsview/models/list_item_group_model_impl.cpp", + "../jsview/models/list_item_model_impl.cpp", + "../jsview/models/list_model_impl.cpp", + "../jsview/models/loading_progress_model_impl.cpp", + "../jsview/models/marquee_model_impl.cpp", + "../jsview/models/navigator_model_impl.cpp", + "../jsview/models/page_transition_model_impl.cpp", + "../jsview/models/path_model_impl.cpp", + "../jsview/models/patternlock_model_impl.cpp", + "../jsview/models/picker_model_impl.cpp", + "../jsview/models/polygon_model_impl.cpp", + "../jsview/models/progress_model_impl.cpp", + "../jsview/models/qrcode_model_impl.cpp", + "../jsview/models/radio_model_impl.cpp", + "../jsview/models/rect_model_impl.cpp", + "../jsview/models/refresh_model_impl.cpp", + "../jsview/models/row_model_impl.cpp", + "../jsview/models/scroll_model_impl.cpp", + "../jsview/models/search_model_impl.cpp", + "../jsview/models/shape_abstract_model_impl.cpp", + "../jsview/models/shape_model_impl.cpp", + "../jsview/models/slider_model_impl.cpp", + "../jsview/models/sliding_panel_model_impl.cpp", + "../jsview/models/span_model_impl.cpp", + "../jsview/models/stack_model_impl.cpp", + "../jsview/models/stepper_item_model_impl.cpp", + "../jsview/models/stepper_model_impl.cpp", + "../jsview/models/swiper_model_impl.cpp", + "../jsview/models/tab_content_model_impl.cpp", + "../jsview/models/tabs_model_impl.cpp", + "../jsview/models/text_clock_model_impl.cpp", + "../jsview/models/text_field_model_impl.cpp", + "../jsview/models/text_model_impl.cpp", + "../jsview/models/text_timer_model_impl.cpp", + "../jsview/models/textpicker_model_impl.cpp", + "../jsview/models/timepicker_model_impl.cpp", + "../jsview/models/toggle_model_impl.cpp", + "../jsview/models/view_abstract_model_impl.cpp", + "../jsview/models/view_full_update_model_impl.cpp", + "../jsview/models/view_partial_update_model_impl.cpp", + "../jsview/models/water_flow_item_model_impl.cpp", + "../jsview/models/water_flow_model_impl.cpp", + ] + + sources += uicast_configs.uicast_frontend_sources + deps += [ "$ace_root/frameworks/core/components/qrcode/ft_build:ace_core_components_qrcode_$platform", ] if (defined(config.xcomponent_components_support) && config.xcomponent_components_support) { @@ -148,7 +362,7 @@ template("declarative_js_engine") { if (defined(config.use_build_in_js_engine) && config.use_build_in_js_engine) { - deps += [ "$ace_root/frameworks/bridge:framework_bridge_$platform" ] + deps += [ "$ace_root/frameworks/bridge/ft_build:framework_bridge_$platform" ] defines += [ "BUILT_IN_JS_ENGINE" ] } else { sources += [ @@ -161,7 +375,7 @@ template("declarative_js_engine") { } } -#deps += [ "engine/$engine_path:declarative_js_engine_bridge_${engine_name}_$platform" ] + deps += [ "../engine/$engine_path/ft_build:declarative_js_engine_bridge_${engine_name}_$platform" ] deps += [ ":gen_obj_src_js_enum_style", @@ -213,7 +427,7 @@ template("declarative_js_engine_ng") { if (current_os == "ohos" && current_cpu == "x86_64") { defines += [ "SIMULATOR_64" ] } - + print(defines) deps = [] configs = [ "$ace_root/ft_build:ace_config" ] @@ -272,8 +486,9 @@ template("declarative_js_engine_ng") { if (defined(config.use_build_in_js_engine) && config.use_build_in_js_engine) { - deps += [ "$ace_root/frameworks/bridge:framework_bridge_ng_$platform" ] + deps += [ "$ace_root/frameworks/bridge/ft_build:framework_bridge_ng_$platform" ] defines += [ "BUILT_IN_JS_ENGINE" ] + print("use build in js engine") } else { deps += [ "$ace_root/ft_build/build:libace_static_${platform}" ] if (defined(config.build_container_scope_lib) && @@ -302,6 +517,8 @@ foreach(item, ace_platforms) { "declarative_js_engine_${engine.engine_name}_$platform") { platform = item.name defines = engine.engine_defines + engine_name = engine.engine_name + engine_path = engine.engine_path config = {} if (defined(item.config)) { @@ -311,5 +528,21 @@ foreach(item, ace_platforms) { defines += config.defines } } + #declarative_js_engine_ng( + # "declarative_js_engine_ng_${engine.engine_name}_$platform") { + # platform = item.name + # #engine_name = engine.engine_name + # #engine_path = engine.engine_path + # defines = engine.engine_defines + + # config = { + # } + # if (defined(item.config)) { + # config = item.config + # } + # if (defined(config.defines)) { + # defines += config.defines + # } + #} } } diff --git a/ace_engine/frameworks/bridge/declarative_frontend/jsview/js_canvas_renderer.h b/ace_engine/frameworks/bridge/declarative_frontend/jsview/js_canvas_renderer.h index b9e0f92f2..d600ea1b5 100644 --- a/ace_engine/frameworks/bridge/declarative_frontend/jsview/js_canvas_renderer.h +++ b/ace_engine/frameworks/bridge/declarative_frontend/jsview/js_canvas_renderer.h @@ -27,7 +27,7 @@ #include "frameworks/bridge/declarative_frontend/jsview/js_path2d.h" #include "frameworks/bridge/declarative_frontend/jsview/js_render_image.h" #include "frameworks/bridge/declarative_frontend/jsview/js_view_abstract.h" -#include "frameworks/bridge/js_frontend/engine/quickjs/qjs_utils.h" +//#include "frameworks/bridge/js_frontend/engine/quickjs/qjs_utils.h" #include "frameworks/core/components/custom_paint/offscreen_canvas.h" #include "frameworks/core/components_ng/pattern/custom_paint/custom_paint_pattern.h" #include "frameworks/core/components_ng/pattern/custom_paint/offscreen_canvas_pattern.h" diff --git a/ace_engine/frameworks/bridge/js_frontend/engine/common/js_engine.cpp b/ace_engine/frameworks/bridge/js_frontend/engine/common/js_engine.cpp index 0c588bb96..2526c069f 100644 --- a/ace_engine/frameworks/bridge/js_frontend/engine/common/js_engine.cpp +++ b/ace_engine/frameworks/bridge/js_frontend/engine/common/js_engine.cpp @@ -18,19 +18,17 @@ #include "frameworks/bridge/js_frontend/engine/common/js_engine.h" -#include "frameworks/bridge/js_frontend/engine/common/runtime_constants.h" -// Fangtian TODO -// #include "native_engine/native_engine.h" +#include "frameworks/bridge/js_frontend/engine/common/runtime_constants.h" +#include "native_engine/native_engine.h" namespace OHOS::Ace::Framework { void JsEngine::RunNativeEngineLoop() { - // Fangtian TODO LOGW("RunNativeEngineLoop not implemented."); - // if (nativeEngine_ != nullptr) { - // nativeEngine_->Loop(LOOP_NOWAIT, false); - // } + if (nativeEngine_ != nullptr) { + nativeEngine_->Loop(LOOP_NOWAIT, false); + } } #if !defined(PREVIEW) diff --git a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/BUILD.gn b/ace_engine/frameworks/bridge/js_frontend/engine/ft_build/BUILD.gn similarity index 55% rename from ace_engine/adapter/fangtian/entrance/pa_engine/engine/BUILD.gn rename to ace_engine/frameworks/bridge/js_frontend/engine/ft_build/BUILD.gn index 357b8ffa3..6866667a9 100644 --- a/ace_engine/adapter/fangtian/entrance/pa_engine/engine/BUILD.gn +++ b/ace_engine/frameworks/bridge/js_frontend/engine/ft_build/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. +# Copyright (c) 2021 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -11,34 +11,47 @@ # See the License for the specific language governing permissions and # limitations under the License. -#import("//build/ohos.gni") import("//build/gn/fangtian.gni") -import("//foundation/arkui/ace_engine/ace_config.gni") +import("//ace_engine/ft_build/ace_config.gni") -# build service backend javascript engine library -template("js_pa_engine") { +# build javascript engine library +template("js_engine") { forward_variables_from(invoker, "*") ft_source_set(target_name) { - subsystem_name = ace_engine_subsystem - part_name = ace_engine_part defines += invoker.defines - configs = [ "$ace_root:ace_config" ] - + if (target_cpu == "arm64") { + if (!is_mingw) { + defines += [ "_ARM64_" ] + } + } + if (current_os == "ohos" && current_cpu == "x86_64") { + defines += [ "SIMULATOR_64" ] + } deps = [] + configs = [ "$ace_root/ft_build:ace_config" ] + if (use_js_debug) { - deps += [ - "${engine_path}:js_pa_engine_bridge_${engine_name}_debug_$platform", - ] + deps += + [ "../${engine_path}/ft_build:js_engine_bridge_${engine_name}_debug_$platform" ] } else { -#deps += [ "${engine_path}:js_pa_engine_bridge_${engine_name}_$platform" ] + deps += [ "../${engine_path}/ft_build:js_engine_bridge_${engine_name}_$platform" ] } - deps += [ "$ace_root/build:libace" ] - if (defined(config.build_container_scope_lib) && - config.build_container_scope_lib) { -# TODO -# deps += [ "napi:ace_container_scope" ] + # if support napi + sources = [ "../common/js_engine.cpp" ] + + #deps += [ "$napi/ft_build:ace_napi" ] + + if (defined(config.use_build_in_js_engine) && + config.use_build_in_js_engine) { + deps += [ "$ace_root/frameworks/bridge/ft_build:framework_bridge_$platform" ] + } else { + deps += [ "$ace_root/build:libace" ] + if (defined(config.build_container_scope_lib) && + config.build_container_scope_lib) { + deps += [ "$napi/ft_build:ace_container_scope" ] + } } } } @@ -52,10 +65,10 @@ foreach(item, ace_platforms) { support_engines = [] support_engines = engine_config.js_engines foreach(engine, support_engines) { - js_pa_engine("js_pa_engine_${engine.engine_name}_$platform") { -#platform = item.name -#engine_name = engine.engine_name -#engine_path = engine.engine_path + js_engine("js_engine_${engine.engine_name}_$platform") { + platform = item.name + engine_name = engine.engine_name + engine_path = engine.engine_path defines = engine.engine_defines use_js_debug = false config = { @@ -68,7 +81,7 @@ foreach(item, ace_platforms) { } } if (defined(engine.have_debug) && engine.have_debug) { - js_pa_engine("js_pa_engine_${engine.engine_name}_debug_$platform") { + js_engine("js_engine_${engine.engine_name}_debug_$platform") { platform = item.name engine_name = engine.engine_name engine_path = engine.engine_path diff --git a/ace_engine/frameworks/bridge/js_frontend/engine/jsi/ft_build/BUILD.gn b/ace_engine/frameworks/bridge/js_frontend/engine/jsi/ft_build/BUILD.gn new file mode 100644 index 000000000..375db1a90 --- /dev/null +++ b/ace_engine/frameworks/bridge/js_frontend/engine/jsi/ft_build/BUILD.gn @@ -0,0 +1,136 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#import("//arkcompiler/ets_frontend/ts2panda/ts2abc_config.gni") +import("//build/gn/fangtian.gni") +import("//ace_engine/ft_build/ace_config.gni") +import("//ace_engine/ft_build/build/ace_gen_obj.gni") + +base_output_path = get_label_info(":gen_abc_proxyclass", "target_out_dir") +abcstrip_native_min_obj_path = base_output_path + "strip.native.min.abc" + +#ts2abc_gen_abc("gen_strip_native_min_abc") { +# extra_visibility = [ ":*" ] # Only targets in this file can depend on this. +# src_js = rebase_path( +# "$root_out_dir/obj/third_party/jsframework/dist/strip.native.min.js") +# dst_file = rebase_path(base_output_path + "/strip.native.min.abc") + +# in_puts = +# [ "$root_out_dir/obj/third_party/jsframework/dist/strip.native.min.js" ] +# out_puts = [ base_output_path + "/strip.native.min.abc" ] +# extra_dependencies = [ "//third_party/jsframework:gen_snapshot" ] +#} + +#gen_obj("abc_strip_native_min") { +# input = base_output_path + "/strip.native.min.abc" +# if (use_mac || use_mingw_win || use_ios || use_linux) { +# abcstripnativemin_obj_path = base_output_path + "/strip_native_min.c" +# } else { +# abcstripnativemin_obj_path = base_output_path + "/strip_native_min.o" +# } +# output = abcstripnativemin_obj_path +# snapshot_dep = [ ":gen_strip_native_min_abc" ] +#} + +template("js_engine_ark") { + forward_variables_from(invoker, "*") + + ft_source_set(target_name) { + defines += invoker.defines + + print("js engine ark") + configs = [ + "$ace_root/ft_build:ace_config", + #"//arkcompiler/ets_runtime:ark_jsruntime_public_config", + ] + + sources = [ + "../ark_js_runtime.cpp", + "../ark_js_value.cpp", + "../jsi_animation_bridge.cpp", + "../jsi_animator_bridge.cpp", + "../jsi_badge_bridge.cpp", + "../jsi_base_utils.cpp", + "../jsi_canvas_bridge.cpp", + "../jsi_chart_bridge.cpp", + "../jsi_clock_bridge.cpp", + "../jsi_component_api_bridge.cpp", + "../jsi_engine.cpp", + "../jsi_engine_loader.cpp", + "../jsi_group_js_bridge.cpp", + "../jsi_image_animator_bridge.cpp", + "../jsi_input_bridge.cpp", + "../jsi_list_bridge.cpp", + "../jsi_offscreen_canvas_bridge.cpp", + "../jsi_stepper_bridge.cpp", + ] + + # xcomponent components supports phone, TV and wearable except PC Preview + if (defined(config.xcomponent_components_support) && + config.xcomponent_components_support) { + sources += [ "../jsi_xcomponent_bridge.cpp" ] + } + + if (defined(config.use_build_in_js_engine) && + config.use_build_in_js_engine) { + defines += [ "BUILT_IN_JS_ENGINE" ] + } + + deps = [] + #if (defined(config.build_for_preview) && config.build_for_preview) { + deps += [ + #":gen_obj_src_abc_strip_native_min", + #"$napi/native_engine/impl/ark:ace_napi_impl_ark", + ] + #} else { + #deps += [ "//third_party/jsframework:ark_build" ] + # deps += [ + # "multimedia_image_framework:image", + # "multimedia_image_framework:image_native", + # "napi:ace_napi", + # ] + #} + if (target_cpu == "arm64") { + defines += [ "APP_USE_ARM64" ] + } else if (target_cpu == "arm") { + defines += [ "APP_USE_ARM" ] + } + #deps += [ "napi/ft_build:ace_napi_ark" ] + deps += [ "//arkcompiler/ets_runtime/ft_build:libark_jsruntime" ] + } +} + +foreach(item, ace_platforms) { + platform = item.name + engine_config = { + } + engine_config = item.config + support_engines = [] + support_engines = engine_config.js_engines + foreach(engine, support_engines) { + if (engine.engine_name == "ark") { + js_engine_ark("js_engine_bridge_ark_$platform") { + defines = engine.engine_defines + config = { + } + + if (defined(item.config)) { + config = item.config + } + if (defined(config.defines)) { + defines += config.defines + } + } + } + } +} diff --git a/ace_engine/frameworks/core/components/qrcode/ft_build/BUILD.gn b/ace_engine/frameworks/core/components/qrcode/ft_build/BUILD.gn new file mode 100644 index 000000000..3fd695ef5 --- /dev/null +++ b/ace_engine/frameworks/core/components/qrcode/ft_build/BUILD.gn @@ -0,0 +1,56 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//ace_engine/frameworks/core/components/ft_build/components.gni") + +qrcodegen_src_dir = "//third_party/qrcodegen/cpp" +qrcodegen_dst_dir = root_out_dir + "/qrcode" +action("apply_patch") { + visibility = [ ":*" ] + script = "../applypatch.sh" + inputs = [ qrcodegen_src_dir ] + outputs = [ "$qrcodegen_dst_dir/qrcodegen.cpp" ] + args = [ + rebase_path(qrcodegen_src_dir, root_build_dir), + rebase_path(qrcodegen_dst_dir, root_build_dir), + rebase_path("../qrcode_patch2.patch", root_build_dir), + ] +} + +config("qrcodegen_config") { + include_dirs = [ "$qrcodegen_dst_dir" ] +} + +source_set("qrcodegen") { + deps = [ ":apply_patch" ] + sources = [ "$qrcodegen_dst_dir/qrcodegen.cpp" ] + cflags = [ + "-Wall", + "-Wno-reorder", + ] + cflags_cc = cflags + + public_configs = [ ":qrcodegen_config" ] +} + +build_component("qrcode") { + sources = [ + "../flutter_render_qrcode.cpp", + "../qrcode_component.cpp", + "../render_qrcode.cpp", + "../render_qrcode_creator.cpp", + ] + rosen_sources = [ "../rosen_render_qrcode.cpp" ] + + deps = [ ":qrcodegen" ] +} diff --git a/ace_engine/frameworks/core/components_ng/pattern/ft_build/BUILD.gn b/ace_engine/frameworks/core/components_ng/pattern/ft_build/BUILD.gn index 7009a1749..d6b1953c3 100644 --- a/ace_engine/frameworks/core/components_ng/pattern/ft_build/BUILD.gn +++ b/ace_engine/frameworks/core/components_ng/pattern/ft_build/BUILD.gn @@ -349,6 +349,13 @@ build_component_ng("pattern_ng") { "../video/video_layout_algorithm.cpp", "../video/video_model_ng.cpp", "../video/video_pattern.cpp", + "../waterflow/water_flow_item_model_ng.cpp", + "../waterflow/water_flow_layout_algorithm.cpp", + "../waterflow/water_flow_layout_info.cpp", + "../waterflow/water_flow_layout_property.cpp", + "../waterflow/water_flow_model_ng.cpp", + "../waterflow/water_flow_pattern.cpp", + "../waterflow/water_flow_position_controller.cpp", "../xcomponent/xcomponent_ext_surface_callback_client.cpp", "../xcomponent/xcomponent_layout_algorithm.cpp", "../xcomponent/xcomponent_model_ng.cpp", diff --git a/ace_engine/adapter/fangtian/build/platform.gni b/ace_engine/frameworks/core/components_ng/pattern/qrcode/ft_build/BUILD.gn similarity index 57% rename from ace_engine/adapter/fangtian/build/platform.gni rename to ace_engine/frameworks/core/components_ng/pattern/qrcode/ft_build/BUILD.gn index 85e6a8c41..a00ba1021 100644 --- a/ace_engine/adapter/fangtian/build/platform.gni +++ b/ace_engine/frameworks/core/components_ng/pattern/qrcode/ft_build/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2023 Huawei Technologies Co., Ltd. All rights reserved. +# Copyright (c) 2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -11,17 +11,16 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//build/gn/fangtian.gni") +import("//ace_engine/frameworks/core/components_ng/ft_build/components.gni") -platforms = [] - -if (is_standard_system) { - platform = { - name = "fangtian" - config = { - import("config.gni") - } - } - - platforms += [ platform ] +build_component_ng("qrcode_pattern_ng") { + sources = [ + "../qrcode_layout_algorithm.cpp", + "../qrcode_model_ng.cpp", + "../qrcode_paint_method.cpp", + "../qrcode_pattern.cpp", + ] + deps = [ + "//ace_engine/frameworks/core/components/qrcode/ft_build:qrcodegen", + ] } diff --git a/ace_engine/frameworks/core/components_ng/property/ft_build/BUILD.gn b/ace_engine/frameworks/core/components_ng/property/ft_build/BUILD.gn index a319cfd60..434ee18b2 100644 --- a/ace_engine/frameworks/core/components_ng/property/ft_build/BUILD.gn +++ b/ace_engine/frameworks/core/components_ng/property/ft_build/BUILD.gn @@ -20,5 +20,6 @@ build_component_ng("property_ng") { "../grid_property.cpp", "../measure_utils.cpp", "../property.cpp", + "../templates_parser.cpp", ] } diff --git a/ace_engine/frameworks/core/ft_build/BUILD.gn b/ace_engine/frameworks/core/ft_build/BUILD.gn index 9d76f9a57..a9d8a5b42 100644 --- a/ace_engine/frameworks/core/ft_build/BUILD.gn +++ b/ace_engine/frameworks/core/ft_build/BUILD.gn @@ -296,6 +296,7 @@ template("ace_core_source_set") { "$ace_root/frameworks/core/components/positioned/ft_build:ace_core_components_positioned_$platform", "$ace_root/frameworks/core/components/progress/ft_build:ace_core_components_progress_$platform", "$ace_root/frameworks/core/components/proxy/ft_build:ace_core_components_proxy_$platform", + "$ace_root/frameworks/core/components/qrcode/ft_build:ace_core_components_qrcode_$platform", "$ace_root/frameworks/core/components/refresh/ft_build:ace_core_components_refresh_$platform", "$ace_root/frameworks/core/components/relative_container/ft_build:ace_core_components_relative_container_$platform", "$ace_root/frameworks/core/components/root/ft_build:ace_core_components_root_$platform", @@ -337,7 +338,9 @@ template("ace_core_source_set") { "$ace_root/frameworks/core/components/watch_slider/ft_build:ace_core_components_watch_slider_$platform", "$ace_root/frameworks/core/components/wrap/ft_build:ace_core_components_wrap_$platform", ] - + deps += [ + "$ace_root/frameworks/core/components_ng/pattern/qrcode/ft_build:ace_core_components_qrcode_pattern_ng_$platform", + ] deps += [ "$ace_root/frameworks/core/components_v2/common/ft_build:ace_core_components_common_v2_$platform", "$ace_root/frameworks/core/components_v2/foreach/ft_build:ace_core_components_foreach_v2_$platform", diff --git a/ace_engine/ft_build/BUILD.gn b/ace_engine/ft_build/BUILD.gn index 373637e12..cbe4aa901 100644 --- a/ace_engine/ft_build/BUILD.gn +++ b/ace_engine/ft_build/BUILD.gn @@ -20,6 +20,10 @@ config("ace_config") { "$ace_root", "$ace_root/frameworks", "$root_out_dir/arkui/framework", + "//arkcompiler/ets_runtime", + "//arkcompiler/runtime_core", + "$ace_napi", + "$ace_root/frameworks/bridge", ] defines = ace_common_defines diff --git a/ace_engine/ft_build/ace_config.gni b/ace_engine/ft_build/ace_config.gni index e2899176d..6c8b673ed 100644 --- a/ace_engine/ft_build/ace_config.gni +++ b/ace_engine/ft_build/ace_config.gni @@ -28,7 +28,7 @@ declare_args() { enable_ace_instance_log = false # Disable glfw window to build for PC preview scenario. - enable_glfw_window = false + enable_glfw_window = true # Enable when build for cross platform is_cross_platform_build = false diff --git a/ace_engine/ft_build/build/ace_lib.gni b/ace_engine/ft_build/build/ace_lib.gni index 457099102..dfdcbe3db 100644 --- a/ace_engine/ft_build/build/ace_lib.gni +++ b/ace_engine/ft_build/build/ace_lib.gni @@ -22,12 +22,11 @@ template("libace_static") { deps = [ "$ace_root/frameworks/base/ft_build:ace_base_$platform" ] if (enable_ng_build) { - # Fangtian TODO assert(false, "not support ng build") - # deps += [ - # "$ace_root/frameworks/bridge/ft_build:framework_bridge_ng_$platform", - # "$ace_root/frameworks/core/ft_build:ace_core_ng_$platform", - # ] + deps += [ + "$ace_root/frameworks/bridge/ft_build:framework_bridge_ng_$platform", + "$ace_root/frameworks/core/ft_build:ace_core_ng_$platform", + ] } else { deps += [ "$ace_root/frameworks/bridge/ft_build:framework_bridge_$platform", @@ -42,9 +41,10 @@ template("libace_static") { # build-in ark js engine for preview if (defined(config.use_build_in_js_engine) && config.use_build_in_js_engine && defined(config.ark_engine)) { + print("use build in ark engine ") deps += [ - # "$ace_root/frameworks/bridge/declarative_frontend:declarative_js_engine_ark_$platform", - # "$ace_root/frameworks/bridge/js_frontend/engine:js_engine_ark_$platform", + "$ace_root/frameworks/bridge/declarative_frontend/ft_build:declarative_js_engine_ark_$platform", + "$ace_root/frameworks/bridge/js_frontend/engine/ft_build:js_engine_ark_$platform", ] } } diff --git a/arkcompiler/ets_frontend/ft_build/ets_frontend_config.gni b/arkcompiler/ets_frontend/ft_build/ets_frontend_config.gni new file mode 100644 index 000000000..3dc269e12 --- /dev/null +++ b/arkcompiler/ets_frontend/ft_build/ets_frontend_config.gni @@ -0,0 +1,35 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +if (!defined(ark_standalone_build)) { + ark_standalone_build = false +} + +if (!ark_standalone_build) { + build_root = "//build" + ark_third_party_root = "//third_party" + import("//build/gn/fangtian.gni") +} else { + ark_third_party_root = "//arkcompiler/toolchain/build/third_party_gn" + import("$build_root/ark.gni") +} + +ets_frontend_root = "//arkcompiler/ets_frontend" + +toolchain_linux = "$build_root/toolchain/linux:clang_x64" +if (host_cpu == "arm64") { + toolchain_mac = "$build_root/toolchain/mac:clang_arm64" +} else { + toolchain_mac = "$build_root/toolchain/mac:clang_x64" +} +toolchain_win = "$build_root/toolchain/mingw:mingw_x86_64" diff --git a/arkcompiler/ets_frontend/ts2panda/ft_build/ts2abc_config.gni b/arkcompiler/ets_frontend/ts2panda/ft_build/ts2abc_config.gni new file mode 100755 index 000000000..8b633cd96 --- /dev/null +++ b/arkcompiler/ets_frontend/ts2panda/ft_build/ts2abc_config.gni @@ -0,0 +1,236 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//arkcompiler/ets_frontend/ft_build/ets_frontend_config.gni") +if (!ark_standalone_build) { + import("//build/gn/fangtian.gni") + #import("//build/test.gni") + build_root = "//build" + ts2abc_root = "//arkcompiler/ets_frontend/ts2panda" +} else { + import("$build_root/ark.gni") + ts2abc_root = "//arkcompiler/ets_frontend/ts2panda" +} + +declare_args() { + nodejs_dir = "" + node_path = "" + node_modules = "" + + ts2abc_build_deps = "" + ts2abc_build_path = "" +} + +node_modules = "//prebuilts/build-tools/common/ts2abc/node_modules" +build_public_version = true +if (build_public_version) { + nodejs_dir = "//prebuilts/build-tools/common/nodejs" +} else { + nodejs_dir = "//prebuilts/ace-toolkit/nodejs" +} + +if (host_toolchain == toolchain_mac) { + ts2abc_build_deps = [ "$ts2abc_root:ts2abc_build_mac($toolchain_mac)" ] + ts2abc_build_path = + get_label_info("$ts2abc_root:ts2abc_build_mac($toolchain_mac)", + "root_out_dir") + + "/obj/arkcompiler/ets_frontend/ts2panda/build-mac" + node_path = "${nodejs_dir}/node-v12.18.4-darwin-x64/bin/" +} else if (host_toolchain == toolchain_win) { + ts2abc_build_deps = [ "$ts2abc_root:ts2abc_build_win($toolchain_win)" ] + ts2abc_build_path = + get_label_info("$ts2abc_root:ts2abc_build_win($toolchain_win)", + "root_out_dir") + + "/obj/arkcompiler/ets_frontend/ts2panda/build_win" +} else { + ts2abc_build_deps = [ "$ts2abc_root:ts2abc_build($toolchain_linux)" ] + ts2abc_build_path = + get_label_info("$ts2abc_root:ts2abc_build($toolchain_linux)", + "root_out_dir") + + "/obj/arkcompiler/ets_frontend/ts2panda/build" + node_path = "${nodejs_dir}/node-v12.18.4-linux-x64/bin/" +} + +# Generate js plugin. +# +# Mandatory arguments: +# plugin_path -- plugin js file path +# plugin_name -- name of js file, ex: BatteryPlugin.js +# generat_file -- name of generated file +# package_name -- name of generated file's package +# extra_dependencies -- a list of files that should be considered as dependencies, must be label +# out_puts +template("ts2abc_gen_file") { + assert(defined(invoker.plugin_path), "plugin_path is required!") + assert(defined(invoker.plugin_name), "plugin_name is required!") + assert(defined(invoker.generat_file), "generat_file is required!") + assert(defined(invoker.package_name), "package_name is required!") + assert(defined(invoker.out_puts), "out_puts is required!") + + extra_dependencies = [] + if (defined(invoker.extra_dependencies)) { + extra_dependencies += invoker.extra_dependencies + } + + action("$target_name") { + script = "${ts2abc_root}/scripts/generate_plugin.py" + + deps = extra_dependencies + deps += [ ts2abc_build_deps ] + args = [ + "--node", + rebase_path("${node_path}"), + "--frontend-tool-path", + rebase_path("${ts2abc_build_path}"), + "--node-modules", + rebase_path("${node_modules}"), + "--plugin-path", + invoker.plugin_path, + "--plugin-name", + invoker.plugin_name, + "--generated-file", + invoker.generat_file, + "--package-name", + invoker.package_name, + ] + + outputs = invoker.out_puts + } +} + +# Generate abc +# +# Mandatory arguments: +# src_js -- name of js file, ex: BatteryPlugin.js +# dst_file -- ex: BatteryPlugin.abc +# out_puts +template("ts2abc_gen_abc") { + assert(defined(invoker.src_js), "src_js is required!") + assert(defined(invoker.dst_file), "dst_file is required!") + assert(defined(invoker.out_puts), "out_puts is required!") + + extra_dependencies = [] + if (defined(invoker.extra_dependencies)) { + extra_dependencies += invoker.extra_dependencies + } + + action("$target_name") { + if (defined(invoker.extra_visibility)) { + visibility = invoker.extra_visibility + } + + script = "${ts2abc_root}/scripts/generate_js_bytecode.py" + + deps = extra_dependencies + deps += ts2abc_build_deps + + args = [ + "--src-js", + invoker.src_js, + "--dst-file", + invoker.dst_file, + "--node", + rebase_path("${node_path}"), + "--frontend-tool-path", + rebase_path("${ts2abc_build_path}"), + "--node-modules", + rebase_path("${node_modules}"), + ] + + if (defined(invoker.extra_args)) { + args += invoker.extra_args + } + + if (defined(invoker.in_puts)) { + inputs = invoker.in_puts + } + + outputs = invoker.out_puts + } +} + +template("ts2abc_unittest_action") { + _target_name_ = "${target_name}" + invoker.module_out_path = "ark/ts2abc" + + # unittest for phone running + ohos_unittest(_target_name_) { + configs = [ "${ts2abc_root}/ts2abc:ts2abc_config" ] + deps = [ "${ts2abc_root}/ts2abc:ts2abc_static" ] + forward_variables_from(invoker, "*") + } + + _module_out_path_ = invoker.module_out_path + + # unittest for host running + action("${_target_name_}Action") { + testonly = true + _host_test_target_ = ":${_target_name_}(${host_toolchain})" + _root_out_dir_ = get_label_info(_host_test_target_, "root_out_dir") + + deps = [ _host_test_target_ ] + + script = "${ts2abc_root}/scripts/run_tests_executable.sh" + + args = [ rebase_path(_root_out_dir_) + + "/tests/unittest/${_module_out_path_}/${_target_name_}" ] + + inputs = [ + "$_root_out_dir_/tests/unittest/${_module_out_path_}/${_target_name_}", + ] + outputs = [ "$target_out_dir/${_target_name_}/" ] + } +} + +# ts2abc performs the ut test +# +# Mandatory arguments: +# js_file: The name of the test use case file to execute , ex expression/TemplateExpression.test.js +template("ts2abc_unittest") { + assert(defined(invoker.js_file), "js_file is required!") + + action("$target_name") { + script = "${ts2abc_root}/scripts/run_tests.py" + deps = [ "${ts2abc_root}:ts2abc_tests" ] + + args = [ + "--src-dir", + rebase_path("${ts2abc_root}"), + "--dist-dir", + rebase_path(target_out_dir + "/.."), + "--node-modules", + rebase_path("${node_modules}"), + "--js-file", + invoker.js_file, + "--gn-build", + ] + + if (host_toolchain == toolchain_linux) { + args += [ + "--platform", + "linux", + ] + } else if (host_toolchain == toolchain_mac) { + args += [ + "--platform", + "mac", + ] + } else { + args += [ + "--platform", + "win", + ] + } + outputs = [ "$target_out_dir/${target_name}/" ] + } +} diff --git a/build/configs/system_deps.toml b/build/configs/system_deps.toml index 95f82ae83..2a3864247 100755 --- a/build/configs/system_deps.toml +++ b/build/configs/system_deps.toml @@ -33,4 +33,5 @@ package_deps = [ "ruby", "libuv-devel", "nodejs-devel", + "patch", ] -- Gitee From 9191517f279761b5b2535c3696da93b87a64f066 Mon Sep 17 00:00:00 2001 From: xieyijun3 Date: Tue, 1 Aug 2023 17:43:49 +0800 Subject: [PATCH 2/2] add qrcodegen Signed-off-by: x30034819 Signed-off-by: xieyijun3 --- third_party/qrcodegen | 1 + 1 file changed, 1 insertion(+) create mode 160000 third_party/qrcodegen diff --git a/third_party/qrcodegen b/third_party/qrcodegen new file mode 160000 index 000000000..8f73aff2f --- /dev/null +++ b/third_party/qrcodegen @@ -0,0 +1 @@ +Subproject commit 8f73aff2fa0f3cf77ae85bfb3bd2a6e10e461c1f -- Gitee