!26 迁移高阶组件代码

Merge pull request !26 from humeng/master
This commit is contained in:
openharmony_ci 2024-10-21 07:06:01 +00:00 committed by Gitee
commit c8a96e6419
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
28 changed files with 5472 additions and 3 deletions

View File

@ -12,5 +12,12 @@
# limitations under the License.
group("as_advanced_ui_component") {
deps = [ "atomicservicetabs/interfaces:atomicservicetabs" ]
deps = [
"atomicservicenavigation/interfaces:atomicservicenavigation",
"atomicservicetabs/interfaces:atomicservicetabs",
"atomicserviceweb/interfaces:atomicserviceweb",
"innerfullscreenlaunchcomponent/interfaces:innerfullscreenlaunchcomponent",
"interstitialdialogaction/interfaces:interstitialdialogaction",
"navpushpathhelper:navpushpathhelper",
]
}

View File

@ -0,0 +1,59 @@
# Copyright (c) 2024 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/config/components/ets_frontend/es2abc_config.gni")
import("//build/ohos.gni")
import("//foundation/arkui/ace_engine/ace_config.gni")
import("//foundation/arkui/ace_engine/adapter/preview/build/config.gni")
import("//foundation/arkui/ace_engine/build/ace_gen_obj.gni")
es2abc_gen_abc("gen_atomicservicenavigation_abc") {
src_js = rebase_path("atomicservicenavigation.js")
dst_file = rebase_path(target_out_dir + "/atomicservicenavigation.abc")
in_puts = [ "atomicservicenavigation.js" ]
out_puts = [ target_out_dir + "/atomicservicenavigation.abc" ]
extra_args = [ "--module" ]
}
gen_js_obj("atomicservicenavigation_abc") {
input = get_label_info(":gen_atomicservicenavigation_abc", "target_out_dir") +
"/atomicservicenavigation.abc"
output = target_out_dir + "/atomicservicenavigation_abc.o"
dep = ":gen_atomicservicenavigation_abc"
}
gen_obj("atomicservicenavigation_abc_preview") {
input = get_label_info(":gen_atomicservicenavigation_abc", "target_out_dir") +
"/atomicservicenavigation.abc"
output = target_out_dir + "/atomicservicenavigation_abc.c"
snapshot_dep = [ ":gen_atomicservicenavigation_abc" ]
}
ohos_shared_library("atomicservicenavigation") {
sources = [ "atomicservicenavigation.cpp" ]
if (use_mingw_win || use_mac || use_linux) {
deps = [ ":gen_obj_src_atomicservicenavigation_abc_preview" ]
} else {
deps = [ ":atomicservicenavigation_abc" ]
}
external_deps = [
"hilog:libhilog",
"napi:ace_napi",
]
relative_install_dir = "module/atomicservice"
subsystem_name = "arkui"
part_name = "as_advanced_ui_component"
}

View File

@ -0,0 +1,51 @@
/*
* Copyright (c) 2024 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.
*/
#include "napi/native_node_api.h"
extern const char _binary_atomicservicenavigation_abc_start[];
extern const char _binary_atomicservicenavigation_abc_end[];
// Napi get abc code function
extern "C" __attribute__((visibility("default")))
void NAPI_atomicservice_AtomicServiceNavigation_GetABCCode(const char **buf, int *buflen)
{
if (buf != nullptr) {
*buf = _binary_atomicservicenavigation_abc_start;
}
if (buflen != nullptr) {
*buflen = _binary_atomicservicenavigation_abc_end - _binary_atomicservicenavigation_abc_start;
}
}
/*
* Module define
*/
static napi_module AtomicServiceNavigationModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_modname = "atomicservice.AtomicServiceNavigation",
.nm_priv = ((void*)0),
.reserved = { 0 },
};
/*
* Module registerfunction
*/
extern "C" __attribute__((constructor)) void AtomicServiceNavigationRegisterModule(void)
{
napi_module_register(&AtomicServiceNavigationModule);
}

View File

@ -0,0 +1,181 @@
/*
* Copyright (c) 2024 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 (!("finalizeConstruction" in ViewPU.prototype)) {
Reflect.set(ViewPU.prototype, "finalizeConstruction", () => { });
}
export class AtomicServiceNavigation extends ViewPU {
constructor(w, x, y, z = -1, a1 = undefined, b1) {
super(w, y, z, b1);
if (typeof a1 === "function") {
this.paramsGenerator_ = a1;
}
this.__navPathStack = new ObservedPropertyObjectPU(new NavPathStack(), this, "navPathStack");
this.navigationContent = undefined;
this.__title = new SynchedPropertyObjectOneWayPU(x.title, this, "title");
this.__titleOptions = new SynchedPropertyObjectOneWayPU(x.titleOptions, this, "titleOptions");
this.__hideTitleBar = new SynchedPropertySimpleOneWayPU(x.hideTitleBar, this, "hideTitleBar");
this.__navBarWidth = new SynchedPropertyObjectOneWayPU(x.navBarWidth, this, "navBarWidth");
this.__mode = new SynchedPropertySimpleOneWayPU(x.mode, this, "mode");
this.navDestinationBuilder = this.defaultNavDestinationBuilder;
this.__navBarWidthRange = new SynchedPropertyObjectOneWayPU(x.navBarWidthRange, this, "navBarWidthRange");
this.__minContentWidth = new SynchedPropertyObjectOneWayPU(x.minContentWidth, this, "minContentWidth");
this.stateChangeCallback = undefined;
this.modeChangeCallback = undefined;
this.setInitiallyProvidedValue(x);
this.finalizeConstruction();
}
setInitiallyProvidedValue(v) {
if (v.navPathStack !== undefined) {
this.navPathStack = v.navPathStack;
}
if (v.navigationContent !== undefined) {
this.navigationContent = v.navigationContent;
}
if (v.titleOptions === undefined) {
this.__titleOptions.set({ isBlurEnabled: true });
}
if (v.navDestinationBuilder !== undefined) {
this.navDestinationBuilder = v.navDestinationBuilder;
}
if (v.stateChangeCallback !== undefined) {
this.stateChangeCallback = v.stateChangeCallback;
}
if (v.modeChangeCallback !== undefined) {
this.modeChangeCallback = v.modeChangeCallback;
}
}
updateStateVars(u) {
this.__title.reset(u.title);
this.__titleOptions.reset(u.titleOptions);
this.__hideTitleBar.reset(u.hideTitleBar);
this.__navBarWidth.reset(u.navBarWidth);
this.__mode.reset(u.mode);
this.__navBarWidthRange.reset(u.navBarWidthRange);
this.__minContentWidth.reset(u.minContentWidth);
}
purgeVariableDependenciesOnElmtId(t) {
this.__navPathStack.purgeDependencyOnElmtId(t);
this.__title.purgeDependencyOnElmtId(t);
this.__titleOptions.purgeDependencyOnElmtId(t);
this.__hideTitleBar.purgeDependencyOnElmtId(t);
this.__navBarWidth.purgeDependencyOnElmtId(t);
this.__mode.purgeDependencyOnElmtId(t);
this.__navBarWidthRange.purgeDependencyOnElmtId(t);
this.__minContentWidth.purgeDependencyOnElmtId(t);
}
aboutToBeDeleted() {
this.__navPathStack.aboutToBeDeleted();
this.__title.aboutToBeDeleted();
this.__titleOptions.aboutToBeDeleted();
this.__hideTitleBar.aboutToBeDeleted();
this.__navBarWidth.aboutToBeDeleted();
this.__mode.aboutToBeDeleted();
this.__navBarWidthRange.aboutToBeDeleted();
this.__minContentWidth.aboutToBeDeleted();
SubscriberManager.Get().delete(this.id__());
this.aboutToBeDeletedInternal();
}
get navPathStack() {
return this.__navPathStack.get();
}
set navPathStack(s) {
this.__navPathStack.set(s);
}
get title() {
return this.__title.get();
}
set title(r) {
this.__title.set(r);
}
get titleOptions() {
return this.__titleOptions.get();
}
set titleOptions(q) {
this.__titleOptions.set(q);
}
get hideTitleBar() {
return this.__hideTitleBar.get();
}
set hideTitleBar(p) {
this.__hideTitleBar.set(p);
}
get navBarWidth() {
return this.__navBarWidth.get();
}
set navBarWidth(o) {
this.__navBarWidth.set(o);
}
get mode() {
return this.__mode.get();
}
set mode(n) {
this.__mode.set(n);
}
get navBarWidthRange() {
return this.__navBarWidthRange.get();
}
set navBarWidthRange(m) {
this.__navBarWidthRange.set(m);
}
get minContentWidth() {
return this.__minContentWidth.get();
}
set minContentWidth(l) {
this.__minContentWidth.set(l);
}
defaultNavDestinationBuilder(i, j, k = null) {
}
initialRender() {
this.observeComponentCreation2((g, h) => {
Navigation.create(this.navPathStack);
Navigation.title(ObservedObject.GetRawObject(this.title), {
backgroundColor: this.titleOptions?.backgroundColor,
backgroundBlurStyle: this.titleOptions?.isBlurEnabled ? BlurStyle.COMPONENT_THICK : BlurStyle.NONE,
barStyle: this.titleOptions?.barStyle
});
Navigation.titleMode(NavigationTitleMode.Mini);
Navigation.hideBackButton(true);
Navigation.hideTitleBar(this.hideTitleBar);
Navigation.navBarWidth(ObservedObject.GetRawObject(this.navBarWidth));
Navigation.navBarPosition(NavBarPosition.Start);
Navigation.mode(this.mode);
Navigation.navDestination({ builder: this.navDestinationBuilder.bind(this) });
Navigation.navBarWidthRange(ObservedObject.GetRawObject(this.navBarWidthRange));
Navigation.minContentWidth(ObservedObject.GetRawObject(this.minContentWidth));
Navigation.onNavBarStateChange(this.stateChangeCallback);
Navigation.onNavigationModeChange(this.modeChangeCallback);
}, Navigation);
this.observeComponentCreation2((c, d) => {
If.create();
if (this.navigationContent) {
this.ifElseBranchUpdateFunction(0, () => {
this.navigationContent.bind(this)(this);
});
}
else {
this.ifElseBranchUpdateFunction(1, () => {
});
}
}, If);
If.pop();
Navigation.pop();
}
rerender() {
this.updateDirtyElements();
}
}
export default { AtomicServiceNavigation };

View File

@ -0,0 +1,68 @@
/*
* Copyright (c) 2024 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 { Callback } from '@ohos.base';
@Component
export struct AtomicServiceNavigation {
@State navPathStack?: NavPathStack = new NavPathStack();
@BuilderParam navigationContent?: Callback<void>;
@Prop title?: ResourceStr;
@Prop titleOptions?: TitleOptions = { isBlurEnabled: true };
@Prop hideTitleBar?: boolean;
@Prop navBarWidth?: Length;
@Prop mode?: NavigationMode;
@BuilderParam navDestinationBuilder?: NavDestinationBuilder = this.defaultNavDestinationBuilder;
@Prop navBarWidthRange?: [Dimension, Dimension];
@Prop minContentWidth?: Dimension;
stateChangeCallback?: Callback<boolean>;
modeChangeCallback?: Callback<NavigationMode>;
@Builder
defaultNavDestinationBuilder(name: string, param?: Object) {
}
build() {
Navigation(this.navPathStack) {
if (this.navigationContent) {
this.navigationContent()
}
}
.title(this.title, {
backgroundColor: this.titleOptions?.backgroundColor,
backgroundBlurStyle: this.titleOptions?.isBlurEnabled ? BlurStyle.COMPONENT_THICK : BlurStyle.NONE,
barStyle: this.titleOptions?.barStyle
})
.titleMode(NavigationTitleMode.Mini)
.hideBackButton(true)
.hideTitleBar(this.hideTitleBar)
.navBarWidth(this.navBarWidth)
.navBarPosition(NavBarPosition.Start)
.mode(this.mode)
.navDestination(this.navDestinationBuilder)
.navBarWidthRange(this.navBarWidthRange)
.minContentWidth(this.minContentWidth)
.onNavBarStateChange(this.stateChangeCallback)
.onNavigationModeChange(this.modeChangeCallback)
}
}
export interface TitleOptions {
backgroundColor?: ResourceColor,
isBlurEnabled?: boolean,
barStyle?: BarStyle
}
export type NavDestinationBuilder = (name: string, param?: Object) => void;

View File

@ -0,0 +1,64 @@
# Copyright (c) 2024 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/config/components/ets_frontend/es2abc_config.gni")
import("//build/ohos.gni")
import("//foundation/arkui/ace_engine/ace_config.gni")
import("//foundation/arkui/ace_engine/adapter/preview/build/config.gni")
import("//foundation/arkui/ace_engine/build/ace_gen_obj.gni")
es2abc_gen_abc("gen_atomicserviceweb_abc") {
src_js = rebase_path("atomicserviceweb.js")
dst_file = rebase_path(target_out_dir + "/atomicserviceweb.abc")
in_puts = [ "atomicserviceweb.js" ]
out_puts = [ target_out_dir + "/atomicserviceweb.abc" ]
extra_args = [ "--module" ]
}
gen_js_obj("atomicserviceweb_abc") {
input = get_label_info(":gen_atomicserviceweb_abc", "target_out_dir") +
"/atomicserviceweb.abc"
output = target_out_dir + "/atomicserviceweb_abc.o"
dep = ":gen_atomicserviceweb_abc"
}
gen_obj("atomicserviceweb_abc_preview") {
input = get_label_info(":gen_atomicserviceweb_abc", "target_out_dir") +
"/atomicserviceweb.abc"
output = target_out_dir + "/atomicserviceweb_abc.c"
snapshot_dep = [ ":gen_atomicserviceweb_abc" ]
}
ohos_shared_library("atomicserviceweb") {
include_dirs = [ "include" ]
sources = [
"api_policy_adapter.cpp",
"atomicserviceweb.cpp",
]
if (use_mingw_win || use_mac || use_linux) {
deps = [ ":gen_obj_src_atomicserviceweb_abc_preview" ]
} else {
deps = [ ":atomicserviceweb_abc" ]
}
external_deps = [
"hilog:libhilog",
"napi:ace_napi",
]
relative_install_dir = "module/atomicservice"
subsystem_name = "arkui"
part_name = "as_advanced_ui_component"
}

View File

@ -0,0 +1,47 @@
/*
* Copyright (c) 2024 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.
*/
#include "api_policy_adapter.h"
ApiPolicyAdapter::ApiPolicyAdapter()
{
#ifndef __WIN32
handle = dlopen("/system/lib64/platformsdk/libapipolicy_client.z.so", RTLD_NOW);
if (!handle) {
return;
}
func = reinterpret_cast<CheckUrlFunc>(dlsym(handle, "CheckUrl"));
#endif
}
ApiPolicyAdapter::~ApiPolicyAdapter()
{
#ifndef __WIN32
if (handle) {
dlclose(handle);
handle = nullptr;
}
#endif
}
int32_t ApiPolicyAdapter::CheckUrl(const std::string& bundleName, const std::string& domainType, const std::string& url)
{
int32_t res = 0;
if (func == nullptr) {
return res;
}
res = func(bundleName, domainType, url);
return res;
}

View File

@ -0,0 +1,39 @@
/*
* Copyright (c) 2024 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.
*/
#ifndef API_POLICY_ADAPTER_H
#define API_POLICY_ADAPTER_H
#include "string"
#ifndef __WIN32
#include <dlfcn.h>
#endif
class ApiPolicyAdapter {
public:
ApiPolicyAdapter();
~ApiPolicyAdapter();
int32_t CheckUrl(const std::string& bundleName, const std::string& domainType, const std::string& url);
using CheckUrlFunc = int32_t (*)(const std::string&, const std::string&, const std::string&);
void SetCheckUrlFunc(CheckUrlFunc& func);
private:
void *handle = nullptr;
CheckUrlFunc func = nullptr;
};
#endif

View File

@ -0,0 +1,114 @@
/*
* Copyright (c) 2024 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.
*/
#include <memory>
#include "napi/native_node_api.h"
#include "api_policy_adapter.h"
using namespace std;
extern const char _binary_atomicserviceweb_abc_start[];
extern const char _binary_atomicserviceweb_abc_end[];
namespace HMS::AtomicServiceWeb {
static napi_value CheckUrl(napi_env env, napi_callback_info info)
{
const int indexTwo = 2;
size_t requireArgc = 3;
size_t argc = 3;
napi_value args[3] = { nullptr };
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
NAPI_ASSERT(env, argc >= requireArgc, "Wrong number of arguments");
napi_valuetype bundleNameType;
NAPI_CALL(env, napi_typeof(env, args[0], &bundleNameType));
napi_valuetype domainTypeType;
NAPI_CALL(env, napi_typeof(env, args[1], &domainTypeType));
napi_valuetype urlType;
NAPI_CALL(env, napi_typeof(env, args[indexTwo], &urlType));
NAPI_ASSERT(env, bundleNameType == napi_string && domainTypeType == napi_string && urlType == napi_string,
"Wrong argument type. String expected.");
size_t maxValueLen = 1024;
char bundleNameValue[maxValueLen];
size_t bundleNameLength = 0;
napi_get_value_string_utf8(env, args[0], bundleNameValue, maxValueLen, &bundleNameLength);
std::string bundleName = bundleNameValue;
char domainTypeValue[maxValueLen];
size_t domainTypeLength = 0;
napi_get_value_string_utf8(env, args[1], domainTypeValue, maxValueLen, &domainTypeLength);
std::string domainType = domainTypeValue;
char urlValue[maxValueLen];
size_t urlLength = 0;
napi_get_value_string_utf8(env, args[indexTwo], urlValue, maxValueLen, &urlLength);
std::string url = urlValue;
std::shared_ptr<ApiPolicyAdapter> apiPolicyAdapter = std::make_shared<ApiPolicyAdapter>();
int32_t res = apiPolicyAdapter->CheckUrl(bundleName, domainType, url);
napi_value result;
NAPI_CALL(env, napi_create_double(env, res, &result));
return result;
}
static napi_value Init(napi_env env, napi_value exports)
{
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("checkUrl", CheckUrl),
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
return exports;
}
// Napi get abc code function
extern "C" __attribute__((visibility("default")))
void NAPI_atomicservice_AtomicServiceWeb_GetABCCode(const char **buf, int *buflen)
{
if (buf != nullptr) {
*buf = _binary_atomicserviceweb_abc_start;
}
if (buflen != nullptr) {
*buflen = _binary_atomicserviceweb_abc_end - _binary_atomicserviceweb_abc_start;
}
}
/*
* Module define
*/
static napi_module AtomicServiceWebModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "atomicservice.AtomicServiceWeb",
.nm_priv = ((void*)0),
.reserved = { 0 },
};
/*
* Module registerfunction
*/
extern "C" __attribute__((constructor)) void AtomicServiceWebRegisterModule(void)
{
napi_module_register(&AtomicServiceWebModule);
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,5 @@
{
"name": "@ohos/advanced_ui_component",
"name": "@ohos/as_advanced_ui_component",
"version": "1.0.0",
"description": "as_advanced_ui_component",
"publishAs": "code-segment",
@ -25,7 +25,12 @@
},
"build": {
"sub_component": [
"//foundation/arkui/arkui_advanced_ui_component/atomicservicetabs/interfaces:atomicservicetabs"
"//foundation/arkui/arkui_advanced_ui_component/atomicservicenavigation/interfaces:atomicservicenavigation",
"//foundation/arkui/arkui_advanced_ui_component/atomicservicetabs/interfaces:atomicservicetabs",
"//foundation/arkui/arkui_advanced_ui_component/atomicserviceweb/interfaces:atomicserviceweb",
"//foundation/arkui/arkui_advanced_ui_component/innerfullscreenlaunchcomponent/interfaces:innerfullscreenlaunchcomponent",
"//foundation/arkui/arkui_advanced_ui_component/interstitialdialogaction/interfaces:interstitialdialogaction",
"//foundation/arkui/arkui_advanced_ui_component/navpushpathhelper/interfaces:navpushpathhelper"
],
"inner_kits": [],
"test": []

View File

@ -0,0 +1,61 @@
# Copyright (c) 2024 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/config/components/ets_frontend/es2abc_config.gni")
import("//build/ohos.gni")
import("//foundation/arkui/ace_engine/ace_config.gni")
import("//foundation/arkui/ace_engine/adapter/preview/build/config.gni")
import("//foundation/arkui/ace_engine/build/ace_gen_obj.gni")
es2abc_gen_abc("gen_innerfullscreenlaunchcomponent_abc") {
src_js = rebase_path("innerfullscreenlaunchcomponent.js")
dst_file = rebase_path(target_out_dir + "/innerfullscreenlaunchcomponent.abc")
in_puts = [ "innerfullscreenlaunchcomponent.js" ]
out_puts = [ target_out_dir + "/innerfullscreenlaunchcomponent.abc" ]
extra_args = [ "--module" ]
}
gen_js_obj("innerfullscreenlaunchcomponent_abc") {
input =
get_label_info(":gen_innerfullscreenlaunchcomponent_abc",
"target_out_dir") + "/innerfullscreenlaunchcomponent.abc"
output = target_out_dir + "/innerfullscreenlaunchcomponent_abc.o"
dep = ":gen_innerfullscreenlaunchcomponent_abc"
}
gen_obj("innerfullscreenlaunchcomponent_abc_preview") {
input =
get_label_info(":gen_innerfullscreenlaunchcomponent_abc",
"target_out_dir") + "/innerfullscreenlaunchcomponent.abc"
output = target_out_dir + "/innerfullscreenlaunchcomponent_abc.c"
snapshot_dep = [ ":gen_innerfullscreenlaunchcomponent_abc" ]
}
ohos_shared_library("innerfullscreenlaunchcomponent") {
sources = [ "innerfullscreenlaunchcomponent.cpp" ]
if (use_mingw_win || use_mac || use_linux) {
deps = [ ":gen_obj_src_innerfullscreenlaunchcomponent_abc_preview" ]
} else {
deps = [ ":innerfullscreenlaunchcomponent_abc" ]
}
external_deps = [
"hilog:libhilog",
"napi:ace_napi",
]
relative_install_dir = "module/arkui/advanced"
subsystem_name = "arkui"
part_name = "as_advanced_ui_component"
}

View File

@ -0,0 +1,52 @@
/*
* Copyright (c) 2024 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.
*/
#include "napi/native_node_api.h"
extern const char _binary_innerfullscreenlaunchcomponent_abc_start[];
extern const char _binary_innerfullscreenlaunchcomponent_abc_end[];
// Napi get abc code function
extern "C" __attribute__((visibility("default"))) void NAPI_arkui_advanced_InnerFullScreenLaunchComponent_GetABCCode(
const char** buf, int* buflen)
{
if (buf != nullptr) {
*buf = _binary_innerfullscreenlaunchcomponent_abc_start;
}
if (buflen != nullptr) {
*buflen = _binary_innerfullscreenlaunchcomponent_abc_end -
_binary_innerfullscreenlaunchcomponent_abc_start;
}
}
/*
* Module define
*/
static napi_module InnerFullScreenLaunchComponentModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_modname = "arkui.advanced.InnerFullScreenLaunchComponent",
.nm_priv = ((void*)0),
.reserved = { 0 },
};
/*
* Module registerfunction
*/
extern "C" __attribute__((constructor)) void InnerFullScreenLaunchComponentRegisterModule(void)
{
napi_module_register(&InnerFullScreenLaunchComponentModule);
}

View File

@ -0,0 +1,214 @@
/*
* Copyright (c) 2024 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 (!("finalizeConstruction" in ViewPU.prototype)) {
Reflect.set(ViewPU.prototype, "finalizeConstruction", () => { });
}
const hilog = requireNapi('hilog');
const abilityManager = requireNapi('app.ability.abilityManager');
const commonEventManager = requireNapi('commonEventManager');
export class LaunchController {
constructor() {
this.launchAtomicService = (n1, o1) => { };
}
}
const EMBEDDED_FULL_MODE = 1;
export class InnerFullScreenLaunchComponent extends ViewPU {
constructor(d1, e1, f1, g1 = -1, h1 = undefined, i1) {
super(d1, f1, g1, i1);
if (typeof h1 === "function") {
this.paramsGenerator_ = h1;
}
this.content = this.doNothingBuilder;
this.context = getContext(this);
this.controller = new LaunchController();
this.appId = '';
this.options = undefined;
this.__isShow = new ObservedPropertySimplePU(false, this, "isShow");
this.subscriber = null;
this.launchAtomicService = (k1, l1) => {
hilog.info(0x3900, 'InnerFullScreenLaunchComponent', 'launchAtomicService, appId: %{public}s.', k1);
this.appId = k1;
this.options = l1;
this.checkAbility();
};
this.setInitiallyProvidedValue(e1);
this.finalizeConstruction();
}
setInitiallyProvidedValue(c1) {
if (c1.content !== undefined) {
this.content = c1.content;
}
if (c1.context !== undefined) {
this.context = c1.context;
}
if (c1.controller !== undefined) {
this.controller = c1.controller;
}
if (c1.appId !== undefined) {
this.appId = c1.appId;
}
if (c1.options !== undefined) {
this.options = c1.options;
}
if (c1.isShow !== undefined) {
this.isShow = c1.isShow;
}
if (c1.subscriber !== undefined) {
this.subscriber = c1.subscriber;
}
if (c1.launchAtomicService !== undefined) {
this.launchAtomicService = c1.launchAtomicService;
}
}
updateStateVars(b1) {
}
purgeVariableDependenciesOnElmtId(a1) {
this.__isShow.purgeDependencyOnElmtId(a1);
}
aboutToBeDeleted() {
this.__isShow.aboutToBeDeleted();
SubscriberManager.Get().delete(this.id__());
this.aboutToBeDeletedInternal();
}
get isShow() {
return this.__isShow.get();
}
set isShow(z) {
this.__isShow.set(z);
}
aboutToAppear() {
let s = {
events: [commonEventManager.Support.COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOUT],
};
commonEventManager.createSubscriber(s, (u, v) => {
if (u) {
hilog.error(0x3900, 'InnerFullScreenLaunchComponent', 'Failed to create subscriber, err: %{public}s.', u.message);
return;
}
if (v == null || v == undefined) {
hilog.error(0x3900, 'InnerFullScreenLaunchComponent', 'Failed to create subscriber, data is null.');
return;
}
this.subscriber = v;
commonEventManager.subscribe(this.subscriber, (x, y) => {
if (x) {
hilog.error(0x3900, 'InnerFullScreenLaunchComponent', 'Failed to subscribe common event, err: %{public}s.', x.message);
return;
}
hilog.info(0x3900, 'InnerFullScreenLaunchComponent', 'Received account logout event.');
this.isShow = false;
});
});
this.controller.launchAtomicService = this.launchAtomicService;
}
aboutToDisappear() {
if (this.subscriber !== null) {
commonEventManager.unsubscribe(this.subscriber, (r) => {
if (r) {
hilog.error(0x3900, 'InnerFullScreenLaunchComponent', 'UnsubscribeCallBack, err: %{public}s.', r.message);
}
else {
hilog.info(0x3900, 'InnerFullScreenLaunchComponent', 'Unsubscribe.');
this.subscriber = null;
}
});
}
}
doNothingBuilder(p = null) {
}
resetOptions() {
if (this.options?.parameters) {
this.options.parameters['ohos.extra.param.key.showMode'] = EMBEDDED_FULL_MODE;
this.options.parameters['ability.want.params.IsNotifyOccupiedAreaChange'] = true;
hilog.info(0x3900, 'InnerFullScreenLaunchComponent', 'replaced options is %{public}s !', JSON.stringify(this.options));
}
else {
this.options = {
parameters: {
'ohos.extra.param.key.showMode': EMBEDDED_FULL_MODE,
'ability.want.params.IsNotifyOccupiedAreaChange': true,
}
};
}
}
async checkAbility() {
this.resetOptions();
try {
const o = await abilityManager.isEmbeddedOpenAllowed(this.context, this.appId);
if (o) {
this.isShow = true;
hilog.info(0x3900, 'InnerFullScreenLaunchComponent', ' EmbeddedOpen is Allowed!');
}
else {
hilog.info(0x3900, 'InnerFullScreenLaunchComponent', ' EmbeddedOpen is not Allowed!');
this.popUp();
}
}
catch (n) {
hilog.error(0x3900, 'InnerFullScreenLaunchComponent', 'isEmbeddedOpenAllowed called error!%{public}s', n.message);
}
}
async popUp() {
this.isShow = false;
try {
const m = await this.context.openAtomicService(this.appId, this.options);
hilog.info(0x3900, 'InnerFullScreenLaunchComponent', '%{public}s open service success!', m.want);
}
catch (l) {
hilog.error(0x3900, 'InnerFullScreenLaunchComponent', '%{public}s open service error!', l.message);
}
}
initialRender() {
this.observeComponentCreation2((i, j) => {
Row.create();
Row.justifyContent(FlexAlign.Center);
Row.bindContentCover({ value: this.isShow, changeEvent: k => { this.isShow = k; } }, { builder: () => {
this.uiExtensionBuilder.call(this);
} }, { modalTransition: ModalTransition.DEFAULT });
}, Row);
this.content.bind(this)(this);
Row.pop();
}
uiExtensionBuilder(a = null) {
this.observeComponentCreation2((c, d) => {
UIExtensionComponent.create({
bundleName: `com.atomicservice.${this.appId}`,
flags: this.options?.flags,
parameters: this.options?.parameters
});
UIExtensionComponent.height('100%');
UIExtensionComponent.width('100%');
UIExtensionComponent.onRelease(() => {
hilog.error(0x3900, 'InnerFullScreenLaunchComponent', 'onRelease');
this.isShow = false;
});
UIExtensionComponent.onError(g => {
this.isShow = false;
hilog.error(0x3900, 'InnerFullScreenLaunchComponent', 'call up UIExtension error!%{public}s', g.message);
this.getUIContext().showAlertDialog({
message: g.message
});
});
}, UIExtensionComponent);
}
rerender() {
this.updateDirtyElements();
}
}
export default { InnerFullScreenLaunchComponent, LaunchController};

View File

@ -0,0 +1,171 @@
/*
* Copyright (c) 2024 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 hilog from '@ohos.hilog';
import abilityManager from '@ohos.app.ability.abilityManager';
import common from '@ohos.app.ability.common';
import { Callback } from '@ohos.base';
import AtomicServiceOptions from '@ohos.app.ability.AtomicServiceOptions';
import commonEventManager from '@ohos.commonEventManager';
import Base from '@ohos.base';
export class LaunchController {
public launchAtomicService = (appId: string, options?: AtomicServiceOptions) => {};
}
const EMBEDDED_FULL_MODE: number = 1;
@Component
export struct InnerFullScreenLaunchComponent {
@BuilderParam content: Callback<void> = this.doNothingBuilder;
private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
controller: LaunchController = new LaunchController();
private appId: string = '';
private options?: AtomicServiceOptions;
@State private isShow: boolean = false;
private subscriber: commonEventManager.CommonEventSubscriber | null = null;
private launchAtomicService = (appId: string, options?: AtomicServiceOptions) => {
hilog.info(0x3900, 'InnerFullScreenLaunchComponent',
'launchAtomicService, appId: %{public}s.', appId);
this.appId = appId;
this.options = options;
this.checkAbility();
}
aboutToAppear() {
let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
events: [commonEventManager.Support.COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOUT],
};
commonEventManager.createSubscriber(subscribeInfo,
(err:Base.BusinessError, data: commonEventManager.CommonEventSubscriber) => {
if (err) {
hilog.error(0x3900, 'InnerFullScreenLaunchComponent',
'Failed to create subscriber, err: %{public}s.', err.message);
return;
}
if (data == null || data == undefined) {
hilog.error(0x3900, 'InnerFullScreenLaunchComponent', 'Failed to create subscriber, data is null.');
return;
}
this.subscriber = data;
commonEventManager.subscribe(this.subscriber,
(err: Base.BusinessError, data: commonEventManager.CommonEventData) => {
if (err) {
hilog.error(0x3900, 'InnerFullScreenLaunchComponent',
'Failed to subscribe common event, err: %{public}s.', err.message);
return;
}
hilog.info(0x3900, 'InnerFullScreenLaunchComponent', 'Received account logout event.');
this.isShow = false;
})
})
this.controller.launchAtomicService = this.launchAtomicService;
}
aboutToDisappear() {
if (this.subscriber !== null) {
commonEventManager.unsubscribe(this.subscriber, (err) => {
if (err) {
hilog.error(0x3900, 'InnerFullScreenLaunchComponent',
'UnsubscribeCallBack, err: %{public}s.', err.message);
} else {
hilog.info(0x3900, 'InnerFullScreenLaunchComponent', 'Unsubscribe.');
this.subscriber = null;
}
})
}
}
@Builder
doNothingBuilder() {
};
resetOptions() {
if (this.options?.parameters) {
this.options.parameters['ohos.extra.param.key.showMode'] = EMBEDDED_FULL_MODE;
this.options.parameters['ability.want.params.IsNotifyOccupiedAreaChange'] = true;
hilog.info(0x3900, 'InnerFullScreenLaunchComponent', 'replaced options is %{public}s !', JSON.stringify(this.options));
} else {
this.options = {
parameters: {
'ohos.extra.param.key.showMode': EMBEDDED_FULL_MODE,
'ability.want.params.IsNotifyOccupiedAreaChange': true,
}
};
}
}
async checkAbility() {
this.resetOptions();
try {
const res: boolean = await abilityManager.isEmbeddedOpenAllowed(this.context, this.appId);
if (res) {
this.isShow = true;
hilog.info(0x3900, 'InnerFullScreenLaunchComponent', ' EmbeddedOpen is Allowed!');
} else {
hilog.info(0x3900, 'InnerFullScreenLaunchComponent', ' EmbeddedOpen is not Allowed!');
this.popUp();
}
} catch (e) {
hilog.error(0x3900, 'InnerFullScreenLaunchComponent', 'isEmbeddedOpenAllowed called error!%{public}s', e.message);
}
}
async popUp() {
this.isShow = false;
try {
const ability = await this.context.openAtomicService(this.appId, this.options);
hilog.info(0x3900, 'InnerFullScreenLaunchComponent', '%{public}s open service success!', ability.want);
} catch (e) {
hilog.error(0x3900, 'InnerFullScreenLaunchComponent', '%{public}s open service error!', e.message);
}
}
build() {
Row() {
this.content();
}
.justifyContent(FlexAlign.Center)
.bindContentCover($$this.isShow, this.uiExtensionBuilder())
}
@Builder
uiExtensionBuilder() {
UIExtensionComponent({
bundleName: `com.atomicservice.${this.appId}`,
flags: this.options?.flags,
parameters: this.options?.parameters
})
.height('100%')
.width('100%')
.onRelease(
() => {
hilog.error(0x3900, 'InnerFullScreenLaunchComponent', 'onRelease');
this.isShow = false;
}
).onError(
err => {
this.isShow = false;
hilog.error(0x3900, 'InnerFullScreenLaunchComponent', 'call up UIExtension error! %{public}s', err.message);
this.getUIContext().showAlertDialog({
message: err.message
});
}
)
}
}

View File

@ -0,0 +1,59 @@
# Copyright (c) 2024 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/config/components/ets_frontend/es2abc_config.gni")
import("//build/ohos.gni")
import("//foundation/arkui/ace_engine/ace_config.gni")
import("//foundation/arkui/ace_engine/adapter/preview/build/config.gni")
import("//foundation/arkui/ace_engine/build/ace_gen_obj.gni")
es2abc_gen_abc("gen_interstitialdialogaction_abc") {
src_js = rebase_path("interstitialdialogaction.js")
dst_file = rebase_path(target_out_dir + "/interstitialdialogaction.abc")
in_puts = [ "interstitialdialogaction.js" ]
out_puts = [ target_out_dir + "/interstitialdialogaction.abc" ]
extra_args = [ "--module" ]
}
gen_js_obj("interstitialdialogaction_abc") {
input = get_label_info(":gen_interstitialdialogaction_abc",
"target_out_dir") + "/interstitialdialogaction.abc"
output = target_out_dir + "/interstitialdialogaction_abc.o"
dep = ":gen_interstitialdialogaction_abc"
}
gen_obj("interstitialdialogaction_abc_preview") {
input = get_label_info(":gen_interstitialdialogaction_abc",
"target_out_dir") + "/interstitialdialogaction.abc"
output = target_out_dir + "/interstitialdialogaction_abc.c"
snapshot_dep = [ ":gen_interstitialdialogaction_abc" ]
}
ohos_shared_library("interstitialdialogaction") {
sources = [ "interstitialdialogaction.cpp" ]
if (use_mingw_win || use_mac || use_linux) {
deps = [ ":gen_obj_src_interstitialdialogaction_abc_preview" ]
} else {
deps = [ ":interstitialdialogaction_abc" ]
}
external_deps = [
"hilog:libhilog",
"napi:ace_napi",
]
relative_install_dir = "module/atomicservice"
subsystem_name = "arkui"
part_name = "as_advanced_ui_component"
}

View File

@ -0,0 +1,51 @@
/*
* Copyright (c) 2024 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.
*/
#include "napi/native_node_api.h"
extern const char _binary_interstitialdialogaction_abc_start[];
extern const char _binary_interstitialdialogaction_abc_end[];
// Napi get abc code function
extern "C" __attribute__((visibility("default")))
void NAPI_atomicservice_InterstitialDialogAction_GetABCCode(const char **buf, int *buflen)
{
if (buf != nullptr) {
*buf = _binary_interstitialdialogaction_abc_start;
}
if (buflen != nullptr) {
*buflen = _binary_interstitialdialogaction_abc_end - _binary_interstitialdialogaction_abc_start;
}
}
/*
* Module define
*/
static napi_module InterstitialDialogActionModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_modname = "atomicservice.InterstitialDialogAction",
.nm_priv = ((void*)0),
.reserved = { 0 },
};
/*
* Module registerfunction
*/
extern "C" __attribute__((constructor)) void InterstitialDialogActionRegisterModule(void)
{
napi_module_register(&InterstitialDialogActionModule);
}

View File

@ -0,0 +1,267 @@
/*
* Copyright (c) 2024 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.
*/
const ComponentContent = requireNapi("arkui.node").ComponentContent;
const curves = requireNativeModule('ohos.curves');
const DIALOG_BORDER_RADIUS = { "id": -1, "type": 10002, params: ['sys.float.ohos_id_corner_radius_default_m'], "bundleName": "__harDefaultBundleName__", "moduleName": "__harDefaultModuleName__" };
const DIALOG_INNER_PADDING_SIZE = 16;
const DIALOG_MAX_WIDTH = 480;
const DIALOG_OFFSET_X = 0;
const DIALOG_OFFSET_Y_FOR_BAR = -88;
const DIALOG_OFFSET_Y_FOR_NONE = -44;
const STANDARD_MIN_COMPONENT_HEIGHT = 82;
const STANDARD_MAX_COMPONENT_HEIGHT = 94;
const DIALOG_SHADOW_RADIUS = 16;
const DIALOG_SHADOW_OFFSET_Y = 10;
const DIALOG_SHADOW_COLOR = '#19000000';
const TITLE_LINE_DISTANCE = 2;
const TITLE_MAX_LINE = 2;
const SUBTITLE_MAX_LINE = 1;
const TEXT_LEFT_MARGIN_SIZE = 16;
const SUBTITLE_DEFAULT_COLOR = { "id": -1, "type": 10001, params: ['sys.color.ohos_id_color_text_secondary_contrary'], "bundleName": "__harDefaultBundleName__", "moduleName": "__harDefaultModuleName__" };
const TITLE_DEFAULT_COLOR = { "id": -1, "type": 10001, params: ['sys.color.ohos_id_color_text_primary_contrary'], "bundleName": "__harDefaultBundleName__", "moduleName": "__harDefaultModuleName__" };
const OPERATE_AREA_AVOID_WIDTH = 28;
const CLOSE_ICON_DARK_RESOURCE = { "id": -1, "type": 10001, params: ['sys.color.ohos_id_color_tertiary'], "bundleName": "__harDefaultBundleName__", "moduleName": "__harDefaultModuleName__" };
const CLOSE_ICON_LIGHT_RESOURCE = { "id": -1, "type": 10001, params: ['sys.color.ohos_id_color_primary_contrary'], "bundleName": "__harDefaultBundleName__", "moduleName": "__harDefaultModuleName__" };
const CLOSE_BUTTON_BORDER_RADIUS = 8;
const CLOSE_BUTTON_ICON_SIZE = 16;
const CLOSE_BUTTON_HOT_SPOT_SIZE = 32;
const CLOSE_BUTTON_MARGIN = 8;
const CLOSE_BUTTON_ICON_OPACITY = 0.6;
const CLOSE_BUTTON_RESPONSE_REGION_OFFSET_X = -8;
const CLOSE_BUTTON_RESPONSE_REGION_OFFSET_Y = -8;
const CLOSE_BUTTON_OFFSET_X = 0;
const CLOSE_BUTTON_OFFSET_Y = -50;
const FOREGROUND_IMAGE_OFFSET_X = 4;
const FOREGROUND_IMAGE_OFFSET_Y = 0;
export var IconStyle;
(function (e2) {
e2[e2["DARK"] = 0] = "DARK";
e2[e2["LIGHT"] = 1] = "LIGHT";
})(IconStyle || (IconStyle = {}));
export var TitlePosition;
(function (d2) {
d2[d2["TOP"] = 0] = "TOP";
d2[d2["BOTTOM"] = 1] = "BOTTOM";
})(TitlePosition || (TitlePosition = {}));
export var BottomOffset;
(function (c2) {
c2[c2["OFFSET_FOR_BAR"] = 0] = "OFFSET_FOR_BAR";
c2[c2["OFFSET_FOR_NONE"] = 1] = "OFFSET_FOR_NONE";
})(BottomOffset || (BottomOffset = {}));
class DialogParams {
constructor(a2, b2) {
this.options = a2;
this.defaultCloseAction = b2;
}
}
function dialogBuilder(k, l = null) {
const m = k;
(l ? l : this).observeComponentCreation2((x1, y1, z1 = m) => {
Row.create();
Row.backgroundColor('rgba(0,0,0,0)');
Row.width('100%');
Row.height(STANDARD_MAX_COMPONENT_HEIGHT);
Row.padding({
left: DIALOG_INNER_PADDING_SIZE,
right: DIALOG_INNER_PADDING_SIZE
});
Row.constraintSize({
minHeight: STANDARD_MIN_COMPONENT_HEIGHT,
maxHeight: STANDARD_MAX_COMPONENT_HEIGHT,
maxWidth: DIALOG_MAX_WIDTH
});
}, Row);
(l ? l : this).observeComponentCreation2((t1, u1, v1 = m) => {
Flex.create();
Flex.backgroundColor(v1.options.backgroundImage === undefined ? '#EBEEF5' : 'rgba(0,0,0,0)');
Flex.shadow({
radius: DIALOG_SHADOW_RADIUS,
offsetX: 0,
offsetY: DIALOG_SHADOW_OFFSET_Y,
color: DIALOG_SHADOW_COLOR
});
Flex.height(STANDARD_MIN_COMPONENT_HEIGHT);
Flex.width('100%');
Flex.alignSelf(ItemAlign.End);
Flex.direction(Direction.Rtl);
Flex.zIndex(1);
Flex.borderRadius({
topLeft: DIALOG_BORDER_RADIUS,
topRight: DIALOG_BORDER_RADIUS,
bottomLeft: DIALOG_BORDER_RADIUS,
bottomRight: DIALOG_BORDER_RADIUS
});
Flex.onClick(() => {
if (v1.options.onDialogClick !== undefined) {
v1.options.onDialogClick();
}
v1.defaultCloseAction();
});
}, Flex);
(l ? l : this).observeComponentCreation2((q1, r1, s1 = m) => {
Row.create();
Row.padding({ left: OPERATE_AREA_AVOID_WIDTH });
Row.direction(Direction.Rtl);
Row.defaultFocus(true);
Row.align(Alignment.End);
Row.alignSelf(ItemAlign.End);
Row.constraintSize({
maxWidth: '50%',
minWidth: '40%'
});
}, Row);
(l ? l : this).observeComponentCreation2((m1, n1, o1 = m) => {
SymbolGlyph.create({ "id": -1, "type": 40000, params: ['sys.symbol.xmark_circle_fill'], "bundleName": "__harDefaultBundleName__", "moduleName": "__harDefaultModuleName__" });
SymbolGlyph.fontColor([o1.options.iconStyle === IconStyle.DARK ?
CLOSE_ICON_DARK_RESOURCE : CLOSE_ICON_LIGHT_RESOURCE]);
SymbolGlyph.borderRadius(CLOSE_BUTTON_BORDER_RADIUS);
SymbolGlyph.width(CLOSE_BUTTON_ICON_SIZE);
SymbolGlyph.height(CLOSE_BUTTON_ICON_SIZE);
SymbolGlyph.opacity(CLOSE_BUTTON_ICON_OPACITY);
SymbolGlyph.draggable(false);
SymbolGlyph.focusable(true);
SymbolGlyph.responseRegion({
x: CLOSE_BUTTON_RESPONSE_REGION_OFFSET_X,
y: CLOSE_BUTTON_RESPONSE_REGION_OFFSET_Y,
width: CLOSE_BUTTON_HOT_SPOT_SIZE,
height: CLOSE_BUTTON_HOT_SPOT_SIZE
});
SymbolGlyph.margin(CLOSE_BUTTON_MARGIN);
SymbolGlyph.alignSelf(ItemAlign.End);
SymbolGlyph.offset({
x: CLOSE_BUTTON_OFFSET_X,
y: CLOSE_BUTTON_OFFSET_Y
});
SymbolGlyph.onClick(() => {
if (o1.options.onDialogClose !== undefined) {
o1.options.onDialogClose();
}
o1.defaultCloseAction();
});
}, SymbolGlyph);
(l ? l : this).observeComponentCreation2((j1, k1, l1 = m) => {
Image.create(l1.options.foregroundImage);
Image.height(STANDARD_MAX_COMPONENT_HEIGHT);
Image.objectFit(ImageFit.Contain);
Image.fitOriginalSize(true);
Image.offset({
x: FOREGROUND_IMAGE_OFFSET_X,
y: FOREGROUND_IMAGE_OFFSET_Y
});
Image.alignSelf(ItemAlign.End);
}, Image);
Row.pop();
(l ? l : this).observeComponentCreation2((g1, h1, i1 = m) => {
Flex.create({
direction: i1.options.titlePosition === TitlePosition.BOTTOM ?
FlexDirection.ColumnReverse : FlexDirection.Column,
justifyContent: FlexAlign.Center
});
Flex.constraintSize({
maxWidth: '60%',
minWidth: '50%'
});
Flex.flexGrow(1);
Flex.margin({ left: TEXT_LEFT_MARGIN_SIZE });
}, Flex);
(l ? l : this).observeComponentCreation2((d1, e1, f1 = m) => {
Text.create(f1.options.title);
Text.alignSelf(ItemAlign.Start);
Text.maxFontSize({ "id": -1, "type": 10002, params: ['sys.float.ohos_id_text_size_sub_title1'], "bundleName": "__harDefaultBundleName__", "moduleName": "__harDefaultModuleName__" });
Text.minFontSize(16);
Text.fontColor(f1.options.titleColor !== undefined ? f1.options.titleColor : TITLE_DEFAULT_COLOR);
Text.fontWeight(FontWeight.Bold);
Text.margin(f1.options.titlePosition ? { top: TITLE_LINE_DISTANCE } : { bottom: TITLE_LINE_DISTANCE });
Text.maxLines(TITLE_MAX_LINE);
Text.wordBreak(WordBreak.BREAK_WORD);
Text.textOverflow({ overflow: TextOverflow.Ellipsis });
}, Text);
Text.pop();
(l ? l : this).observeComponentCreation2((a1, b1, c1 = m) => {
Text.create(c1.options.subtitle);
Text.alignSelf(ItemAlign.Start);
Text.maxFontSize({ "id": -1, "type": 10002, params: ['sys.float.ohos_id_text_size_caption'], "bundleName": "__harDefaultBundleName__", "moduleName": "__harDefaultModuleName__" });
Text.minFontSize(9);
Text.fontColor(c1.options.subtitleColor !== undefined ? c1.options.subtitleColor : SUBTITLE_DEFAULT_COLOR);
Text.maxLines(SUBTITLE_MAX_LINE);
Text.wordBreak(WordBreak.BREAK_WORD);
Text.textOverflow({ overflow: TextOverflow.Ellipsis });
}, Text);
Text.pop();
Flex.pop();
Flex.pop();
(l ? l : this).observeComponentCreation2((w, x, y = m) => {
Image.create(y.options.backgroundImage);
Image.width('100%');
Image.height(STANDARD_MIN_COMPONENT_HEIGHT);
Image.offset({ x: '-100%', y: 0 });
Image.borderRadius(DIALOG_BORDER_RADIUS);
Image.zIndex(0);
Image.alignSelf(ItemAlign.End);
Image.onClick(() => {
if (y.options.onDialogClose !== undefined) {
y.options.onDialogClose();
}
y.defaultCloseAction();
});
}, Image);
Row.pop();
}
export class InterstitialDialogAction {
constructor(i) {
this.uiContext = i.uiContext;
this.bottomOffsetType = i.bottomOffsetType;
this.dialogParam = new DialogParams(i, () => {
this.closeDialog();
});
this.contentNode = new ComponentContent(this.uiContext, wrapBuilder(dialogBuilder), this.dialogParam);
}
openDialog() {
if (this.contentNode !== null) {
this.uiContext.getPromptAction().openCustomDialog(this.contentNode, {
isModal: false,
autoCancel: false,
offset: {
dx: DIALOG_OFFSET_X,
dy: this.bottomOffsetType === BottomOffset.OFFSET_FOR_BAR ?
DIALOG_OFFSET_Y_FOR_BAR : DIALOG_OFFSET_Y_FOR_NONE
},
alignment: DialogAlignment.Bottom,
transition: TransitionEffect.asymmetric(TransitionEffect.OPACITY.animation({ duration: 150, curve: Curve.Sharp })
.combine(TransitionEffect.scale({ x: 0.85, y: 0.85, centerX: '50%', centerY: '85%' })
.animation({ curve: curves.interpolatingSpring(0, 1, 228, 24) })), TransitionEffect.OPACITY.animation({ duration: 250, curve: Curve.Sharp })
.combine(TransitionEffect.scale({ x: 0.85, y: 0.85, centerX: '50%', centerY: '85%' })
.animation({ duration: 250, curve: Curve.Friction })))
})
.catch((f) => {
let g = f.message;
let h = f.code;
console.error(`${h}: ${g}`);
});
}
}
closeDialog() {
if (this.contentNode !== null) {
this.uiContext.getPromptAction().closeCustomDialog(this.contentNode)
.catch((b) => {
let c = b.message;
let d = b.code;
console.error(`${d}: ${c}`);
});
}
}
}
export default { InterstitialDialogAction, IconStyle, TitlePosition, BottomOffset };

View File

@ -0,0 +1,296 @@
/*
* Copyright (c) 2024 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 { UIContext } from '@ohos.arkui.UIContext';
import { ComponentContent } from '@ohos.arkui.node';
import { BusinessError } from '@ohos.base';
import { curves } from '@kit.ArkUI';
const DIALOG_BORDER_RADIUS: Resource = $r('sys.float.ohos_id_corner_radius_default_m');
const DIALOG_INNER_PADDING_SIZE: number = 16;
const DIALOG_MAX_WIDTH: number = 480;
const DIALOG_OFFSET_X: number = 0;
const DIALOG_OFFSET_Y_FOR_BAR: number = -88;
const DIALOG_OFFSET_Y_FOR_NONE: number = -44;
const STANDARD_MIN_COMPONENT_HEIGHT: number = 82;
const STANDARD_MAX_COMPONENT_HEIGHT: number = 94;
const DIALOG_SHADOW_RADIUS: number = 16;
const DIALOG_SHADOW_OFFSET_Y: number = 10;
const DIALOG_SHADOW_COLOR: ResourceStr = '#19000000';
const TITLE_LINE_DISTANCE: number = 2;
const TITLE_MAX_LINE: number = 2;
const SUBTITLE_MAX_LINE: number = 1;
const TEXT_LEFT_MARGIN_SIZE: number = 16;
const SUBTITLE_DEFAULT_COLOR: Resource = $r('sys.color.ohos_id_color_text_secondary_contrary');
const TITLE_DEFAULT_COLOR: Resource = $r('sys.color.ohos_id_color_text_primary_contrary');
const OPERATE_AREA_AVOID_WIDTH: number = 28;
const CLOSE_ICON_DARK_RESOURCE: Resource = $r('sys.color.ohos_id_color_tertiary');
const CLOSE_ICON_LIGHT_RESOURCE: Resource = $r('sys.color.ohos_id_color_primary_contrary');
const CLOSE_BUTTON_BORDER_RADIUS: number = 8;
const CLOSE_BUTTON_ICON_SIZE: number = 16;
const CLOSE_BUTTON_HOT_SPOT_SIZE: number = 32;
const CLOSE_BUTTON_MARGIN: number = 8;
const CLOSE_BUTTON_ICON_OPACITY = 0.6;
const CLOSE_BUTTON_RESPONSE_REGION_OFFSET_X: number = -8;
const CLOSE_BUTTON_RESPONSE_REGION_OFFSET_Y: number = -8;
const CLOSE_BUTTON_OFFSET_X: number = 0;
const CLOSE_BUTTON_OFFSET_Y: number = -50;
const FOREGROUND_IMAGE_OFFSET_X: number = 4;
const FOREGROUND_IMAGE_OFFSET_Y: number = 0;
export enum IconStyle {
DARK = 0,
LIGHT = 1
}
export enum TitlePosition {
TOP = 0,
BOTTOM = 1
}
export enum BottomOffset {
OFFSET_FOR_BAR = 0,
OFFSET_FOR_NONE = 1
}
class DialogParams {
public options: DialogOptions;
public defaultCloseAction: Callback<void>;
constructor(
options: DialogOptions,
defaultCloseAction: Callback<void>,
) {
this.options = options;
this.defaultCloseAction = defaultCloseAction;
}
}
@Builder
function dialogBuilder(params: DialogParams) {
Row() {
Flex() {
Row() {
SymbolGlyph($r('sys.symbol.xmark_circle_fill'))
.fontColor([params.options.iconStyle === IconStyle.DARK ?
CLOSE_ICON_DARK_RESOURCE : CLOSE_ICON_LIGHT_RESOURCE])
.borderRadius(CLOSE_BUTTON_BORDER_RADIUS)
.width(CLOSE_BUTTON_ICON_SIZE)
.height(CLOSE_BUTTON_ICON_SIZE)
.opacity(CLOSE_BUTTON_ICON_OPACITY)
.draggable(false)
.focusable(true)
.responseRegion({
x: CLOSE_BUTTON_RESPONSE_REGION_OFFSET_X,
y: CLOSE_BUTTON_RESPONSE_REGION_OFFSET_Y,
width: CLOSE_BUTTON_HOT_SPOT_SIZE,
height: CLOSE_BUTTON_HOT_SPOT_SIZE
})
.margin(CLOSE_BUTTON_MARGIN)
.alignSelf(ItemAlign.End)
.offset({
x: CLOSE_BUTTON_OFFSET_X,
y: CLOSE_BUTTON_OFFSET_Y
})
.onClick(() => {
if (params.options.onDialogClose !== undefined) {
params.options.onDialogClose()
}
params.defaultCloseAction()
})
Image(params.options.foregroundImage)
.height(STANDARD_MAX_COMPONENT_HEIGHT)
.objectFit(ImageFit.Contain)
.fitOriginalSize(true)
.offset({
x: FOREGROUND_IMAGE_OFFSET_X,
y: FOREGROUND_IMAGE_OFFSET_Y
})
.alignSelf(ItemAlign.End)
}
.padding({ left: OPERATE_AREA_AVOID_WIDTH })
.direction(Direction.Rtl)
.defaultFocus(true)
.align(Alignment.End)
.alignSelf(ItemAlign.End)
.constraintSize({
maxWidth: '50%',
minWidth: '40%'
})
Flex({
direction: params.options.titlePosition === TitlePosition.BOTTOM ?
FlexDirection.ColumnReverse : FlexDirection.Column,
justifyContent: FlexAlign.Center
}) {
Text(params.options.title)
.alignSelf(ItemAlign.Start)
.maxFontSize($r('sys.float.ohos_id_text_size_sub_title1'))
.minFontSize(16)
.fontColor(params.options.titleColor !== undefined ? params.options.titleColor : TITLE_DEFAULT_COLOR)
.fontWeight(FontWeight.Bold)
.margin(params.options.titlePosition ? { top: TITLE_LINE_DISTANCE } : { bottom: TITLE_LINE_DISTANCE })
.maxLines(TITLE_MAX_LINE)
.wordBreak(WordBreak.BREAK_WORD)
.textOverflow({ overflow: TextOverflow.Ellipsis })
Text(params.options.subtitle)
.alignSelf(ItemAlign.Start)
.maxFontSize($r('sys.float.ohos_id_text_size_caption'))
.minFontSize(9)
.fontColor(params.options.subtitleColor !== undefined ? params.options.subtitleColor : SUBTITLE_DEFAULT_COLOR)
.maxLines(SUBTITLE_MAX_LINE)
.wordBreak(WordBreak.BREAK_WORD)
.textOverflow({ overflow: TextOverflow.Ellipsis })
}
.constraintSize({
maxWidth: '60%',
minWidth: '50%'
})
.flexGrow(1)
.margin({ left: TEXT_LEFT_MARGIN_SIZE })
}
.backgroundColor(params.options.backgroundImage === undefined ? '#EBEEF5' : 'rgba(0,0,0,0)')
.shadow({
radius: DIALOG_SHADOW_RADIUS,
offsetX: 0,
offsetY: DIALOG_SHADOW_OFFSET_Y,
color: DIALOG_SHADOW_COLOR
})
.height(STANDARD_MIN_COMPONENT_HEIGHT)
.width('100%')
.alignSelf(ItemAlign.End)
.direction(Direction.Rtl)
.zIndex(1)
.borderRadius({
topLeft: DIALOG_BORDER_RADIUS,
topRight: DIALOG_BORDER_RADIUS,
bottomLeft: DIALOG_BORDER_RADIUS,
bottomRight: DIALOG_BORDER_RADIUS
})
.onClick(() => {
if (params.options.onDialogClick !== undefined) {
params.options.onDialogClick()
}
params.defaultCloseAction()
})
Image(params.options.backgroundImage)
.width('100%')
.height(STANDARD_MIN_COMPONENT_HEIGHT)
.offset({ x: '-100%', y: 0 })
.borderRadius(DIALOG_BORDER_RADIUS)
.zIndex(0)
.alignSelf(ItemAlign.End)
.onClick(() => {
if (params.options.onDialogClose !== undefined) {
params.options.onDialogClose()
}
params.defaultCloseAction()
})
}
.backgroundColor('rgba(0,0,0,0)')
.width('100%')
.height(STANDARD_MAX_COMPONENT_HEIGHT)
.padding({
left: DIALOG_INNER_PADDING_SIZE,
right: DIALOG_INNER_PADDING_SIZE
})
.constraintSize({
minHeight: STANDARD_MIN_COMPONENT_HEIGHT,
maxHeight: STANDARD_MAX_COMPONENT_HEIGHT,
maxWidth: DIALOG_MAX_WIDTH
})
}
declare interface DialogOptions {
uiContext: UIContext,
bottomOffsetType?: BottomOffset,
title?: ResourceStr,
subtitle?: ResourceStr,
titleColor?: ResourceStr | Color,
subtitleColor?: ResourceStr | Color,
backgroundImage?: Resource,
foregroundImage?: Resource,
iconStyle?: IconStyle,
titlePosition?: TitlePosition,
onDialogClick?: Callback<void>,
onDialogClose?: Callback<void>
}
export class InterstitialDialogAction {
private uiContext: UIContext;
private contentNode: ComponentContent<Object>;
private dialogParam: DialogParams;
private bottomOffsetType?: BottomOffset;
constructor(dialogOptions: DialogOptions) {
this.uiContext = dialogOptions.uiContext;
this.bottomOffsetType = dialogOptions.bottomOffsetType;
this.dialogParam = new DialogParams(
dialogOptions,
() => {
this.closeDialog()
}
);
this.contentNode = new ComponentContent(this.uiContext, wrapBuilder(dialogBuilder), this.dialogParam)
}
openDialog() {
if (this.contentNode !== null) {
this.uiContext.getPromptAction().openCustomDialog(this.contentNode, {
isModal: false,
autoCancel: false,
offset: {
dx: DIALOG_OFFSET_X,
dy: this.bottomOffsetType === BottomOffset.OFFSET_FOR_BAR ?
DIALOG_OFFSET_Y_FOR_BAR : DIALOG_OFFSET_Y_FOR_NONE
},
alignment: DialogAlignment.Bottom,
transition: TransitionEffect.asymmetric(
TransitionEffect.OPACITY.animation({ duration: 150, curve: Curve.Sharp })
.combine(TransitionEffect.scale({ x: 0.85, y: 0.85, centerX: '50%', centerY: '85%' })
.animation({ curve: curves.interpolatingSpring(0, 1, 228, 24)}))
,
TransitionEffect.OPACITY.animation({ duration: 250, curve: Curve.Sharp })
.combine(TransitionEffect.scale({ x: 0.85, y: 0.85, centerX: '50%', centerY: '85%' })
.animation({ duration: 250, curve: Curve.Friction }))
)
})
.catch((error: BusinessError) => {
let message = (error as BusinessError).message
let code = (error as BusinessError).code
console.error(`${code}: ${message}`);
})
}
}
closeDialog() {
if (this.contentNode !== null) {
this.uiContext.getPromptAction().closeCustomDialog(this.contentNode)
.catch((error: BusinessError) => {
let message = (error as BusinessError).message
let code = (error as BusinessError).code
console.error(`${code}: ${message}`);
})
}
}
}

View File

@ -0,0 +1,76 @@
# Copyright (c) 2024 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/es2panda/es2abc_config.gni")
import("//build/ohos.gni")
import("//foundation/arkui/ace_engine/ace_config.gni")
import("//foundation/arkui/ace_engine/adapter/preview/build/config.gni")
import("//foundation/arkui/ace_engine/build/ace_gen_obj.gni")
es2abc_gen_abc("gen_navpushpathhelper_abc") {
src_js = rebase_path("navpushpathhelper.js")
dst_file = rebase_path(target_out_dir + "/navpushpathhelper.abc")
in_puts = [ "navpushpathhelper.js" ]
out_puts = [ target_out_dir + "/navpushpathhelper.abc" ]
extra_args = [ "--module" ]
}
gen_js_obj("navpushpathhelper_abc") {
input = get_label_info(":gen_navpushpathhelper_abc", "target_out_dir") +
"/navpushpathhelper.abc"
output = target_out_dir + "/navpushpathhelper_abc.o"
dep = ":gen_navpushpathhelper_abc"
}
gen_obj("navpushpathhelper_abc_preview") {
input = get_label_info(":gen_navpushpathhelper_abc", "target_out_dir") +
"/navpushpathhelper.abc"
output = target_out_dir + "/navpushpathhelper_abc.c"
snapshot_dep = [ ":gen_navpushpathhelper_abc" ]
}
additional_include_dirs = [ "${ace_root}" ]
ohos_shared_library("navpushpathhelper") {
sources = [
"src/hsp_silentinstall.cpp",
"src/hsp_silentinstall_napi.cpp",
"src/navpushpathhelper.cpp",
]
if (use_mingw_win || use_mac || use_linux) {
deps = [ ":gen_obj_src_navpushpathhelper_abc_preview" ]
} else {
deps = [ ":navpushpathhelper_abc" ]
}
include_dirs = additional_include_dirs
include_dirs += [ "${ace_root}/frameworks" ]
deps += [ "$ace_root/build:libace_compatible" ]
external_deps = [
"ability_base:want",
"ability_runtime:abilitykit_native",
"bundle_framework:appexecfwk_base",
"bundle_framework:appexecfwk_core",
"c_utils:utils",
"hilog:libhilog",
"ipc:ipc_core",
"napi:ace_napi",
"samgr:samgr_proxy",
]
relative_install_dir = "module/atomicservice"
subsystem_name = "arkui"
part_name = "as_advanced_ui_component"
}

View File

@ -0,0 +1,37 @@
/*
* Copyright (c) 2024 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.
*/
#ifndef ADVANCED_UI_COMPONENT_NAVPUSHPATHHELPER_INCLUDE_HSP_SILENTINSTALL_H
#define ADVANCED_UI_COMPONENT_NAVPUSHPATHHELPER_INCLUDE_HSP_SILENTINSTALL_H
#include "bundlemgr/bundle_mgr_interface.h"
#include "interfaces/inner_api/ace/ui_content.h"
namespace OHOS::NavPushPathHelper {
class HspSilentInstall {
public:
HspSilentInstall() = default;
~HspSilentInstall() = default;
static int32_t SilentInstall(const std::string& moduleName, const std::function<void()>& callback,
const std::function<void(int32_t, const std::string&)>& silentInstallErrorCallBack);
static bool IsHspExist(const std::string& moduleName, const std::string& pathName);
static void InitRouteMap();
private:
static OHOS::sptr<OHOS::AppExecFwk::IBundleMgr> GetBundleManager();
};
} // namespace OHOS::NavPushPathHelper
#endif

View File

@ -0,0 +1,59 @@
/*
* Copyright (c) 2024 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.
*/
#ifndef ADVANCED_UI_COMPONENT_NAVPUSHPATHHELPER_INCLUDE_HSP_SILENT_INSTALL_NAPI_H
#define ADVANCED_UI_COMPONENT_NAVPUSHPATHHELPER_INCLUDE_HSP_SILENT_INSTALL_NAPI_H
#include "native_engine/native_engine.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
namespace OHOS::NavPushPathHelper {
class HspSilentInstallNapi {
public:
static napi_value SilentInstall(napi_env env, napi_callback_info info);
static napi_value IsHspExist(napi_env env, napi_callback_info info);
static napi_value InitRouteMap(napi_env env, napi_callback_info info);
private:
struct CallbackData {
napi_env env = nullptr;
int32_t errCode = 0;
std::string errorMessage;
napi_ref successCallback = nullptr;
napi_ref failCallback = nullptr;
~CallbackData()
{
if (this->successCallback != nullptr) {
napi_delete_reference(this->env, this->successCallback);
this->successCallback = nullptr;
}
if (this->failCallback != nullptr) {
napi_delete_reference(this->env, this->failCallback);
this->failCallback = nullptr;
}
}
};
static void SendSuccessBackWork(uv_work_t *work, int statusIn);
static void SendFailBackWork(uv_work_t *work, int statusIn);
static napi_value CreateResultMessage(CallbackData *callbackData);
static napi_value getModuleName(napi_env env, napi_value args, std::string& moduleName);
};
}
#endif

View File

@ -0,0 +1,170 @@
/*
* Copyright (c) 2024 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.
*/
#ifndef ADVANCED_UI_COMPONENT_NAVPUSHPATHHELPER_INCLUDE_SILENT_INSTALL_CALLBACK_H
#define ADVANCED_UI_COMPONENT_NAVPUSHPATHHELPER_INCLUDE_SILENT_INSTALL_CALLBACK_H
#include "atomic_service_status_callback.h"
#include "errors.h"
#include "iremote_broker.h"
#include "iremote_object.h"
#include "iremote_stub.h"
#include "base/log/log.h"
#include "want_params_wrapper.h"
#include "want.h"
namespace OHOS::NavPushPathHelper {
constexpr int32_t SILENT_INSTALL_SUCCESS = 0;
constexpr int32_t SILENT_INSTALL_FAIL_CODE = 300001;
constexpr char SILENT_INSTALL_FAIL_MESSAGE[] = "hsp silent install fail";
/**
* @class IAtomicServiceStatusCallback
* IAtomicServiceStatusCallback is used to notify caller ability that free install is complete.
*/
class IAtomicServiceStatusCallback : public OHOS::IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.IAtomicServiceStatusCallback");
/**
* @brief OnActionEvent.
*/
virtual int32_t OnActionEvent() = 0;
/**
* @brief OnError.
* @param code The code.
* @param msg The msg.
*/
virtual int32_t OnError(int32_t code, const std::string& msg) = 0;
};
/**
* @class AtomicServiceStatusCallbackStub
* AtomicServiceStatusCallbackStub.
*/
class AtomicServiceStatusCallbackStub : public OHOS::IRemoteStub<IAtomicServiceStatusCallback> {
public:
AtomicServiceStatusCallbackStub()
{
handleOnActionEventFunc_ = &AtomicServiceStatusCallbackStub::HandleOnActionEvent;
handleOnErrorFunc_ = &AtomicServiceStatusCallbackStub::HandleOnError;
}
~AtomicServiceStatusCallbackStub() override
{
handleOnActionEventFunc_ = nullptr;
handleOnErrorFunc_ = nullptr;
}
int32_t OnRemoteRequest(uint32_t code, OHOS::MessageParcel &data, OHOS::MessageParcel &reply,
OHOS::MessageOption &option) override
{
TAG_LOGD(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN,
"AtomicServiceStatusCallbackStub::OnReceived, code = %{public}u, flags= %{public}d.",
code, option.GetFlags());
std::u16string descriptor = AtomicServiceStatusCallbackStub::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
if (descriptor != remoteDescriptor) {
TAG_LOGE(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN,
"%{public}s failed, local descriptor is not equal to remote", __func__);
return OHOS::ERR_INVALID_VALUE;
}
auto resultCode = data.ReadInt32();
if (resultCode == SILENT_INSTALL_SUCCESS) {
if (handleOnActionEventFunc_ != nullptr) {
return (this->*handleOnActionEventFunc_)();
}
}
if (resultCode < SILENT_INSTALL_SUCCESS) {
if (handleOnErrorFunc_ != nullptr) {
return (this->*handleOnErrorFunc_)();
}
}
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
private:
int32_t HandleOnActionEvent()
{
return OnActionEvent();
}
int32_t HandleOnError()
{
return OnError(SILENT_INSTALL_FAIL_CODE, SILENT_INSTALL_FAIL_MESSAGE);
}
using HandleOnActionEventFunc = int32_t (AtomicServiceStatusCallbackStub::*)();
HandleOnActionEventFunc handleOnActionEventFunc_;
using HandleOnErrorFunc = int32_t (AtomicServiceStatusCallbackStub::*)();
HandleOnErrorFunc handleOnErrorFunc_;
DISALLOW_COPY_AND_MOVE(AtomicServiceStatusCallbackStub);
};
/**
* @class AtomicServiceStatusCallback
* AtomicServiceStatusCallback.
*/
class AtomicServiceStatusCallback : public AtomicServiceStatusCallbackStub {
public:
AtomicServiceStatusCallback() = default;
~AtomicServiceStatusCallback() override = default;
/**
* @brief OnActionEvent.
*/
int32_t OnActionEvent() override
{
if (!actionEventHandler_) {
TAG_LOGE(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "actionEventHandler_ is null.");
return OHOS::ERR_INVALID_VALUE;
}
actionEventHandler_();
return OHOS::ERR_OK;
}
/**
* @brief OnError.
* @param code The code.
* @param msg The msg.
*/
int32_t OnError(int32_t code, const std::string& msg) override
{
TAG_LOGI(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "OnError code: %{public}d, msg: %{public}s",
code, msg.c_str());
if (!errorEventHandler_) {
TAG_LOGE(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "errorEventHandler_ is null");
return OHOS::ERR_INVALID_VALUE;
}
errorEventHandler_(code, msg);
return OHOS::ERR_OK;
}
void SetActionEventHandler(const std::function<void()>& listener)
{
actionEventHandler_ = listener;
}
void SetErrorEventHandler(const std::function<void(int32_t, const std::string&)>& listener)
{
errorEventHandler_ = listener;
}
private:
std::function<void()> actionEventHandler_;
std::function<void(int32_t, const std::string&)> errorEventHandler_;
};
}
#endif

View File

@ -0,0 +1,146 @@
/*
* Copyright (c) 2024 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.
*/
const navPushPathHelperApi = requireInternal('atomicservice.NavPushPathHelper');
const hilog = requireNapi('hilog');
const tag = 'NavPushPathHelper::JS::';
export class NavPushPathHelper {
static currentID = 0;
constructor(navPathStack) {
this.navPathStack_ = navPathStack;
this.currentHelperId_ = NavPushPathHelper.currentID;
NavPushPathHelper.currentID++;
}
async pushPath(moduleName, info, optionParam) {
hilog.info(0x3900, tag, `pushPath -> currentID: ${this.currentHelperId_}`);
if (navPushPathHelperApi.isHspExist(moduleName, info.name)) {
this.navPathStack_?.pushPath(info, optionParam);
return;
}
return new Promise((resolve, reject) => {
navPushPathHelperApi.silentInstall(moduleName, () => {
navPushPathHelperApi.initRouteMap();
this.navPathStack_?.pushPath(info, optionParam);
resolve();
},
(error) => {
const err = new Error(error.message);
err.code = error.code;
reject(err);
});
});
}
async pushDestination(moduleName, info, optionParam) {
hilog.info(0x3900, tag, `pushDestination -> currentID: ${this.currentHelperId_}`);
if (navPushPathHelperApi.isHspExist(moduleName, info.name)) {
await this.navPathStack_?.pushDestination(info, optionParam);
return;
}
return new Promise((resolve, reject) => {
navPushPathHelperApi.silentInstall(moduleName, () => {
navPushPathHelperApi.initRouteMap();
this.navPathStack_?.pushDestination(info, optionParam)
.then(resolve).catch(reject);
}, (error) => {
const err = new Error(error.message);
err.code = error.code;
reject(err);
});
});
}
async pushPathByName(moduleName, name, param, onPop, optionParam) {
hilog.info(0x3900, tag, `pushPathByName -> currentID: ${this.currentHelperId_}`);
if (navPushPathHelperApi.isHspExist(moduleName, name)) {
this.navPathStack_?.pushPathByName(name, param, onPop, optionParam);
return;
}
return new Promise((resolve, reject) => {
navPushPathHelperApi.silentInstall(moduleName, () => {
navPushPathHelperApi.initRouteMap();
this.navPathStack_?.pushPathByName(name, param, onPop, optionParam);
resolve();
}, (error) => {
const err = new Error(error.message);
err.code = error.code;
reject(err);
});
});
}
async pushDestinationByName(moduleName, name, param, onPop, optionParam) {
hilog.info(0x3900, tag, `pushDestinationByName -> currentID: ${this.currentHelperId_}`);
if (navPushPathHelperApi.isHspExist(moduleName, name)) {
await this.navPathStack_?.pushDestinationByName(name, param, onPop, optionParam);
return;
}
return new Promise((resolve, reject) => {
navPushPathHelperApi.silentInstall(moduleName, () => {
navPushPathHelperApi.initRouteMap();
this.navPathStack_?.pushDestinationByName(name, param, onPop, optionParam)
.then(resolve).catch(reject);
}, (error) => {
const err = new Error(error.message);
err.code = error.code;
reject(err);
});
});
}
async replacePath(moduleName, info, optionParam) {
hilog.info(0x3900, tag, `replacePath -> currentID: ${this.currentHelperId_}`);
if (navPushPathHelperApi.isHspExist(moduleName, info.name)) {
this.navPathStack_?.replacePath(info, optionParam);
return;
}
return new Promise((resolve, reject) => {
navPushPathHelperApi.silentInstall(moduleName, () => {
navPushPathHelperApi.initRouteMap();
this.navPathStack_?.replacePath(info, optionParam);
resolve();
}, (error) => {
const err = new Error(error.message);
err.code = error.code;
reject(err);
});
});
}
async replacePathByName(moduleName, name, param, optionParam) {
hilog.info(0x3900, tag, `replacePathByName -> currentID: ${this.currentHelperId_}`);
if (navPushPathHelperApi.isHspExist(moduleName, name)) {
this.navPathStack_?.replacePathByName(name, param, optionParam);
return;
}
return new Promise((resolve, reject) => {
navPushPathHelperApi.silentInstall(moduleName, () => {
hilog.info(0x3900, tag, `silentInstall success`);
navPushPathHelperApi.initRouteMap();
this.navPathStack_?.replacePathByName(name, param, optionParam);
resolve();
}, (error) => {
const err = new Error(error.message);
err.code = error.code;
reject(err);
});
});
}
}
export default { NavPushPathHelper };

View File

@ -0,0 +1,117 @@
/*
* Copyright (c) 2024 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.
*/
#include "advanced_ui_component/navpushpathhelper/include/hsp_silentinstall.h"
#include "advanced_ui_component/navpushpathhelper/include/silent_install_callback.h"
#include "iservice_registry.h"
#include "system_ability_definition.h"
#include "ability_runtime/context/context.h"
#include "want.h"
#include "adapter/ohos/entrance/ace_container.h"
#include "core/pipeline_ng/pipeline_context.h"
#include "base/log/log.h"
#include "base/utils/utils.h"
#include "core/components_ng/manager/navigation/navigation_manager.h"
#include "core/components_ng/pattern/image/image_pattern.h"
namespace OHOS::NavPushPathHelper {
OHOS::sptr<OHOS::AppExecFwk::IBundleMgr> HspSilentInstall::GetBundleManager()
{
auto systemAbilityMgr = OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (!systemAbilityMgr) {
TAG_LOGE(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "get system ability failed");
return nullptr;
}
auto bundleObj = systemAbilityMgr->GetSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
if (!bundleObj) {
TAG_LOGE(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "get bundle service failed");
return nullptr;
}
return OHOS::iface_cast<OHOS::AppExecFwk::IBundleMgr>(bundleObj);
}
int32_t HspSilentInstall::SilentInstall(const std::string& moduleName, const std::function<void()>& callback,
const std::function<void(int32_t, const std::string&)>& silentInstallErrorCallBack)
{
auto pipeline = OHOS::Ace::NG::PipelineContext::GetCurrentContextSafely();
CHECK_NULL_RETURN(pipeline, -1);
auto runtimeContext = OHOS::Ace::Platform::AceContainer::GetRuntimeContext(pipeline->GetInstanceId());
CHECK_NULL_RETURN(runtimeContext, -1);
auto bundleName = runtimeContext->GetBundleName();
if (bundleName.empty()) {
return -1;
}
auto appInfo = runtimeContext->GetApplicationInfo();
if (!appInfo) {
return -1;
}
auto bms = GetBundleManager();
CHECK_NULL_RETURN(bms, -1);
OHOS::AAFwk::Want want;
want.SetBundle(bundleName);
want.SetModuleName(moduleName);
OHOS::sptr<AtomicServiceStatusCallback> routerCallback = new AtomicServiceStatusCallback();
routerCallback->SetActionEventHandler(callback);
routerCallback->SetErrorEventHandler(silentInstallErrorCallBack);
if (bms->SilentInstall(want, appInfo->uid / OHOS::AppExecFwk::Constants::BASE_USER_RANGE, routerCallback)) {
TAG_LOGI(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "Begin to silent install");
return 0;
}
return -1;
}
bool HspSilentInstall::IsHspExist(const std::string &moduleName, const std::string &pathName)
{
auto pipeline = OHOS::Ace::NG::PipelineContext::GetCurrentContextSafely();
CHECK_NULL_RETURN(pipeline, false);
auto container = OHOS::Ace::Container::CurrentSafely();
CHECK_NULL_RETURN(container, false);
auto navigationRoute = container->GetNavigationRoute();
CHECK_NULL_RETURN(navigationRoute, false);
if (navigationRoute->IsNavigationItemExits(pathName)) {
return true;
}
auto runtimeContext = OHOS::Ace::Platform::AceContainer::GetRuntimeContext(pipeline->GetInstanceId());
CHECK_NULL_RETURN(runtimeContext, false);
auto appInfo = runtimeContext->GetApplicationInfo();
if (!appInfo) {
return false;
}
std::vector<OHOS::AppExecFwk::ModuleInfo> moduleList = appInfo->moduleInfos;
auto res = std::any_of(moduleList.begin(), moduleList.end(), [moduleName](const auto &module) {
return module.moduleName == moduleName;
});
if (res) {
return true;
}
return false;
}
void HspSilentInstall::InitRouteMap()
{
auto container = OHOS::Ace::Container::CurrentSafely();
CHECK_NULL_VOID(container);
auto navigationRoute = container->GetNavigationRoute();
CHECK_NULL_VOID(navigationRoute);
navigationRoute->InitRouteMap();
}
} // namespace OHOS::NavPushPathHelper

View File

@ -0,0 +1,273 @@
/*
* Copyright (c) 2024 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.
*/
#include "advanced_ui_component/navpushpathhelper/include/hsp_silentinstall_napi.h"
#include "advanced_ui_component/navpushpathhelper/include/hsp_silentinstall.h"
#include "base/log/log.h"
using namespace std;
namespace OHOS::NavPushPathHelper {
napi_value HspSilentInstallNapi::IsHspExist(napi_env env, napi_callback_info info)
{
size_t argc = 2;
size_t requireArgc = 2;
napi_value args[2] = { nullptr };
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
NAPI_ASSERT(env, argc >= requireArgc, "Wrong number of arguments");
// get first parametermoduleName
napi_valuetype moduleNameType;
NAPI_CALL(env, napi_typeof(env, args[0], &moduleNameType));
NAPI_ASSERT(env, moduleNameType == napi_string, "Wrong argument type. String expected.");
size_t maxValueLen = 1024;
char moduleNameValue[maxValueLen];
size_t moduleNameLength = 0;
napi_get_value_string_utf8(env, args[0], moduleNameValue, maxValueLen, &moduleNameLength);
std::string moduleName = moduleNameValue;
// get second parameterpathName
napi_valuetype pathNameType;
NAPI_CALL(env, napi_typeof(env, args[1], &pathNameType));
NAPI_ASSERT(env, pathNameType == napi_string, "Wrong argument type. String expected.");
char pathNameValue[maxValueLen];
size_t pathNameLength = 0;
napi_get_value_string_utf8(env, args[1], pathNameValue, maxValueLen, &pathNameLength);
std::string pathName = pathNameValue;
bool isHspExits = HspSilentInstall::IsHspExist(moduleName, pathName);
napi_value jsResult;
NAPI_CALL(env, napi_get_boolean(env, isHspExits, &jsResult));
return jsResult;
}
napi_value HspSilentInstallNapi::InitRouteMap(napi_env env, napi_callback_info info)
{
HspSilentInstall::InitRouteMap();
return nullptr;
}
napi_value HspSilentInstallNapi::SilentInstall(napi_env env, napi_callback_info info)
{
napi_value result = nullptr;
size_t argc = 3;
size_t requireArgc = 3;
napi_value args[3] = { nullptr };
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
NAPI_ASSERT(env, argc >= requireArgc, "Wrong number of arguments");
// get first parametermoduleName
std::string moduleName;
getModuleName(env, args[0], moduleName);
auto callbackData = new (std::nothrow) CallbackData();
if (callbackData == nullptr) {
return result;
}
uv_work_t *work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
delete callbackData;
callbackData = nullptr;
return result;
}
int parameterNum = 1;
const int indexTwo = 2;
napi_create_reference(env, args[1], parameterNum, &(callbackData->successCallback));
napi_create_reference(env, args[indexTwo], parameterNum, &(callbackData->failCallback));
callbackData->env = env;
auto successCallback = [callbackData, work]() {
uv_loop_s *loop = nullptr;
napi_get_uv_event_loop(callbackData->env, &loop);
work->data = reinterpret_cast<void *>(callbackData);
uv_queue_work(loop, work, [](uv_work_t *work) { (void)work; }, SendSuccessBackWork);
};
auto failCallback = [callbackData, work](int32_t errorCode, const std::string& errorMessage) {
callbackData->errCode = errorCode;
callbackData->errorMessage = errorMessage;
uv_loop_s *loop = nullptr;
napi_get_uv_event_loop(callbackData->env, &loop);
work->data = reinterpret_cast<void *>(callbackData);
uv_queue_work(loop, work, [](uv_work_t *work) { (void)work; }, SendFailBackWork);
};
HspSilentInstall::SilentInstall(moduleName, successCallback, failCallback);
return result;
}
napi_value HspSilentInstallNapi::getModuleName(napi_env env, napi_value args, std::string& moduleName)
{
napi_valuetype moduleNameType;
NAPI_CALL(env, napi_typeof(env, args, &moduleNameType));
NAPI_ASSERT(env, moduleNameType == napi_string, "Wrong argument type. String expected.");
napi_status status;
size_t maxValueLen = 1024;
char moduleNameValue[maxValueLen];
size_t moduleNameLength = 0;
status = napi_get_value_string_utf8(env, args, moduleNameValue, maxValueLen, &moduleNameLength);
NAPI_ASSERT(env, status == napi_ok, "Failed to napi_get_value_string_utf8");
moduleName = moduleNameValue;
return nullptr;
}
void HspSilentInstallNapi::SendSuccessBackWork(uv_work_t *work, int statusIn)
{
if (work == nullptr) {
TAG_LOGE(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "SendSuccessBackWork -> work is null");
return;
}
(void)statusIn;
napi_status status;
napi_handle_scope scope = nullptr;
CallbackData *callbackData = reinterpret_cast<CallbackData *>(work->data);
if (callbackData == nullptr) {
TAG_LOGE(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "SendSuccessBackWork -> callbackData is null");
return;
}
napi_open_handle_scope(callbackData->env, &scope);
if (scope == nullptr) {
TAG_LOGE(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "SendSuccessBackWork -> scope is null");
return;
}
napi_value callback = nullptr;
status = napi_get_reference_value(callbackData->env, callbackData->successCallback, &callback);
if (status != napi_ok) {
TAG_LOGE(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "SendSuccessBackWork -> napi_get_reference_value error");
napi_close_handle_scope(callbackData->env, scope);
return;
}
napi_value result;
status = napi_call_function(callbackData->env, nullptr, callback, 0, nullptr, &result);
if (status != napi_ok) {
TAG_LOGE(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "SendSuccessBackWork -> napi_call_function error");
napi_close_handle_scope(callbackData->env, scope);
return;
}
napi_close_handle_scope(callbackData->env, scope);
if (callbackData != nullptr) {
delete callbackData;
callbackData = nullptr;
}
if (work != nullptr) {
delete work;
work = nullptr;
}
}
void HspSilentInstallNapi::SendFailBackWork(uv_work_t *work, int statusIn)
{
if (work == nullptr) {
TAG_LOGE(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "SendSuccessBackWork -> work is null");
return;
}
(void)statusIn;
napi_status status;
napi_handle_scope scope = nullptr;
CallbackData *callbackData = reinterpret_cast<CallbackData *>(work->data);
if (callbackData == nullptr) {
TAG_LOGE(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "SendFailBackWork -> callbackData is null");
return;
}
napi_open_handle_scope(callbackData->env, &scope);
if (scope == nullptr) {
TAG_LOGE(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "SendFailBackWork -> scope is null");
return;
}
napi_value callback = nullptr;
status = napi_get_reference_value(callbackData->env, callbackData->failCallback, &callback);
if (status != napi_ok) {
TAG_LOGE(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "SendFailBackWork -> napi_get_reference_value error");
napi_close_handle_scope(callbackData->env, scope);
return;
}
size_t resultLength = 1;
napi_value resultMessage = CreateResultMessage(callbackData);
napi_value result[] = { resultMessage };
status = napi_call_function(callbackData->env, nullptr, callback, resultLength, result, nullptr);
if (status != napi_ok) {
TAG_LOGE(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "SendFailBackWork -> napi_call_function error");
napi_close_handle_scope(callbackData->env, scope);
return;
}
napi_close_handle_scope(callbackData->env, scope);
if (callbackData != nullptr) {
delete callbackData;
callbackData = nullptr;
}
if (work != nullptr) {
delete work;
work = nullptr;
}
}
napi_value HspSilentInstallNapi::CreateResultMessage(CallbackData *callbackData)
{
napi_status status;
napi_value result = nullptr;
napi_value code = nullptr;
status = napi_create_int32(callbackData->env, callbackData->errCode, &code);
if (status != napi_ok) {
TAG_LOGE(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "CreateResultMessage -> napi_create_int32 error");
return result;
}
napi_value message = nullptr;
status = napi_create_string_utf8(callbackData->env, callbackData->errorMessage.c_str(),
NAPI_AUTO_LENGTH, &message);
if (status != napi_ok) {
TAG_LOGE(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "CreateResultMessage -> napi_create_string_utf8 error");
return result;
}
napi_value businessError = nullptr;
status = napi_create_object(callbackData->env, &businessError);
if (status != napi_ok) {
TAG_LOGE(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "CreateResultMessage -> napi_create_object error");
return result;
}
status = napi_set_named_property(callbackData->env, businessError, "code", code);
if (status != napi_ok) {
TAG_LOGE(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "CreateResultMessage -> napi_set_named_property error");
return result;
}
status = napi_set_named_property(callbackData->env, businessError, "message", message);
if (status != napi_ok) {
TAG_LOGE(OHOS::Ace::AceLogTag::ACE_DEFAULT_DOMAIN, "CreateResultMessage -> napi_set_named_property error");
return result;
}
return businessError;
}
}

View File

@ -0,0 +1,75 @@
/*
* Copyright (c) 2024 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.
*/
#include "native_engine/native_engine.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "advanced_ui_component/navpushpathhelper/include/hsp_silentinstall_napi.h"
extern const char _binary_navpushpathhelper_abc_start[];
extern const char _binary_navpushpathhelper_abc_end[];
namespace OHOS::NavPushPathHelper {
/*
* function for module exports
*/
static napi_value Init(napi_env env, napi_value exports)
{
/*
* Properties define
*/
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("silentInstall", HspSilentInstallNapi::SilentInstall),
DECLARE_NAPI_FUNCTION("isHspExist", HspSilentInstallNapi::IsHspExist),
DECLARE_NAPI_FUNCTION("initRouteMap", HspSilentInstallNapi::InitRouteMap),
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
return exports;
}
// Napi get abc code function
extern "C" __attribute__((visibility("default")))
void NAPI_atomicservice_NavPushPathHelper_GetABCCode(const char **buf, int *buflen)
{
if (buf != nullptr) {
*buf = _binary_navpushpathhelper_abc_start;
}
if (buflen != nullptr) {
*buflen = _binary_navpushpathhelper_abc_end - _binary_navpushpathhelper_abc_start;
}
}
/*
* Module define
*/
static napi_module NavPushPathHelperModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "atomicservice.NavPushPathHelper",
.nm_priv = ((void*)0),
.reserved = { 0 },
};
/*
* Module registerfunction
*/
extern "C" __attribute__((constructor)) void NavPushPathHelperRegisterModule(void)
{
napi_module_register(&NavPushPathHelperModule);
}
}