diff --git a/bundle.json b/bundle.json index 5a1b8db5c815e2e1e16f670b7f5b78777a616238..b0357886a0f337a6e44c20b3910c2c7e3b77365b 100644 --- a/bundle.json +++ b/bundle.json @@ -53,6 +53,7 @@ "sub_component": [ "//foundation/aafwk/standard/services:services_target", "//foundation/aafwk/standard/interfaces/innerkits:innerkits_target", + "//foundation/aafwk/standard/frameworks/kits/ability/native:datashare_ext_ability_module", "//foundation/aafwk/standard/frameworks/kits/ability/native:static_subscriber_ipc", "//foundation/aafwk/standard/frameworks/kits/ability/native:service_extension_module", "//foundation/aafwk/standard/sa_profile:aafwk_sa_profile", @@ -185,12 +186,12 @@ "header_base": "//foundation/aafwk/standard/common/task_dispatcher/include", "header_files": [ "dispatcher/parallel_task_dispatcher.h", - "dispatcher/task_dispatcher_context", + "dispatcher/task_dispatcher_context.h", "threading/runnable.h", "task/task.h" ] }, - "name": "//foundation/aafwk/standard/common:common_target" + "name": "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher" } ], "test": [ diff --git a/common/BUILD.gn b/common/BUILD.gn index 682a10893206fcf67f22c99243334b3be37f69bd..b58b035353d6828f8f7b2adf91f6a7800e0b44d8 100644 --- a/common/BUILD.gn +++ b/common/BUILD.gn @@ -15,5 +15,5 @@ import("//build/ohos.gni") import("//foundation/aafwk/standard/aafwk.gni") group("common_target") { - deps = [ "task_dispatcher:appkit_dispatcher_td" ] + deps = [ "task_dispatcher:task_dispatcher" ] } diff --git a/common/task_dispatcher/BUILD.gn b/common/task_dispatcher/BUILD.gn index eb88f17eef79a63ee123243f4b8d2e8328446a0b..ad7a6c3f64f84e910ac2b20ebc1348e11d7ab66f 100644 --- a/common/task_dispatcher/BUILD.gn +++ b/common/task_dispatcher/BUILD.gn @@ -13,15 +13,8 @@ import("//build/ohos.gni") import("//foundation/aafwk/standard/aafwk.gni") -config("appkit_config") { - config("appkit_public_config") { - visibility = [ ":*" ] - include_dirs = [] - } - include_dirs = [] -} -ohos_shared_library("appkit_dispatcher_td") { +config("task_dispatcher_public_config") { include_dirs = [ "${appexecfwk_path}/common/log/include", "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", @@ -32,10 +25,10 @@ ohos_shared_library("appkit_dispatcher_td") { "${aafwk_path}/frameworks/kits/appkit/native/app/include/task", "${aafwk_path}/frameworks/kits/appkit/native/app/include", ] +} - configs = [ ":appkit_config" ] - - public_configs = [ ":appkit_public_config" ] +ohos_shared_library("task_dispatcher") { + public_configs = [ ":task_dispatcher_public_config" ] sources = [ "${aafwk_path}/common/task_dispatcher/src/dispatcher/base_task_dispatcher.cpp", @@ -66,5 +59,6 @@ ohos_shared_library("appkit_dispatcher_td") { ] external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + subsystem_name = "aafwk" part_name = "ability_runtime" } diff --git a/frameworks/kits/ability/ability_runtime/include/ability_context.h b/frameworks/kits/ability/ability_runtime/include/ability_context.h index 5b4e07de892a0f9a1bb8ada38e8af6f5965d13c1..7941d55ae566a37be222e09e743ccdad1019f606 100755 --- a/frameworks/kits/ability/ability_runtime/include/ability_context.h +++ b/frameworks/kits/ability/ability_runtime/include/ability_context.h @@ -16,6 +16,7 @@ #ifndef ABILITY_RUNTIME_ABILITY_CONTEXT_H #define ABILITY_RUNTIME_ABILITY_CONTEXT_H +#include "foundation/aafwk/standard/frameworks/kits/ability/native/include/iability_callback.h" #include "foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/context/context.h" #include "foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr/configuration.h" @@ -162,13 +163,6 @@ public: virtual ErrCode TerminateSelf() = 0; - /** - * @brief Obtains token. - * - * @return Returns the token. - */ - virtual sptr GetAbilityToken() = 0; - /** * @brief Requests certain permissions from the system. * This method is called for permission request. This is an asynchronous method. When it is executed, @@ -235,6 +229,10 @@ public: virtual std::shared_ptr GetConfiguration() const = 0; + virtual void RegisterAbilityCallback(std::weak_ptr abilityCallback) = 0; + + virtual int GetCurrentWindowMode() = 0; + using SelfType = AbilityContext; static const size_t CONTEXT_TYPE_ID; diff --git a/frameworks/kits/ability/ability_runtime/include/ability_context_impl.h b/frameworks/kits/ability/ability_runtime/include/ability_context_impl.h index b35f3092c3b5275c309bbea6f6e76c42ef9bb66f..7bd20fb81c4ffda129ad641934aeabd3de1dae3b 100755 --- a/frameworks/kits/ability/ability_runtime/include/ability_context_impl.h +++ b/frameworks/kits/ability/ability_runtime/include/ability_context_impl.h @@ -68,11 +68,14 @@ public: void MinimizeAbility() override; ErrCode TerminateSelf() override; - sptr GetAbilityToken() override; + + sptr GetToken() override; + void RequestPermissionsFromUser(const std::vector &permissions, int requestCode, PermissionRequestTask &&task) override; void OnRequestPermissionsFromUserResult( int requestCode, const std::vector &permissions, const std::vector &grantResults) override; + ErrCode RestoreWindowStage(void* contentStorage) override; /** @@ -97,7 +100,7 @@ public: * * @param token The token represents ability. */ - inline void SetToken(const sptr &token) + void SetToken(const sptr &token) override { token_ = token; } @@ -134,6 +137,17 @@ public: */ ErrCode ReleaseAbility(const std::shared_ptr &callback) override; + /** + * regist ability callback + * + * @param abilityCallback Indicates the abilityCallback object. + */ + void RegisterAbilityCallback(std::weak_ptr abilityCallback) override; + + /** + * get current window mode + */ + int GetCurrentWindowMode() override; private: sptr token_; std::shared_ptr abilityInfo_ = nullptr; @@ -143,6 +157,7 @@ private: void* contentStorage_ = nullptr; std::shared_ptr config_; sptr localCallContainer_; + std::weak_ptr abilityCallback_; }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/kits/ability/ability_runtime/src/ability_context_impl.cpp b/frameworks/kits/ability/ability_runtime/src/ability_context_impl.cpp index 1095c4478a704727fb474d387d40bf49c8b4a0e5..29ee6b2c77faf1ef7694f4e7b91bc763d6b7d3b2 100755 --- a/frameworks/kits/ability/ability_runtime/src/ability_context_impl.cpp +++ b/frameworks/kits/ability/ability_runtime/src/ability_context_impl.cpp @@ -276,7 +276,7 @@ ErrCode AbilityContextImpl::TerminateSelf() return err; } -sptr AbilityContextImpl::GetAbilityToken() +sptr AbilityContextImpl::GetToken() { return token_; } @@ -343,5 +343,21 @@ ErrCode AbilityContextImpl::SetMissionLabel(const std::string &label) } return err; } + +void AbilityContextImpl::RegisterAbilityCallback(std::weak_ptr abilityCallback) +{ + HILOG_INFO("%{public}s called.", __func__); + abilityCallback_ = abilityCallback; +} + +int AbilityContextImpl::GetCurrentWindowMode() +{ + HILOG_INFO("%{public}s called.", __func__); + auto abilityCallback = abilityCallback_.lock(); + if (abilityCallback == nullptr) { + return AAFwk::AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED; + } + return abilityCallback->GetCurrentWindowMode(); +} } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/ability_runtime/src/local_call_container.cpp b/frameworks/kits/ability/ability_runtime/src/local_call_container.cpp index 8ef298e70f40786018b681ff1a77208f1ce96ad6..13ed5205b1c666bd6775fc2628088cd028216297 100644 --- a/frameworks/kits/ability/ability_runtime/src/local_call_container.cpp +++ b/frameworks/kits/ability/ability_runtime/src/local_call_container.cpp @@ -24,7 +24,7 @@ int LocalCallContainer::StartAbilityInner( HILOG_DEBUG("start ability by call."); if (!callback) { - HILOG_ERROR("callback)is nullptr."); + HILOG_ERROR("callback is nullptr."); return ERR_INVALID_VALUE; } diff --git a/frameworks/kits/ability/native/BUILD.gn b/frameworks/kits/ability/native/BUILD.gn index 61691f2f0b031b9b65e54410d5c4bc87e4c5a66d..6053ad90c7787b0e4c61373cbe500c2fd4b142c3 100644 --- a/frameworks/kits/ability/native/BUILD.gn +++ b/frameworks/kits/ability/native/BUILD.gn @@ -85,7 +85,7 @@ config("ability_public_config") { "//foundation/aafwk/standard/frameworks/kits/fmskit/native/include", "//foundation/aafwk/standard/interfaces/innerkits/form_manager/include", "//foundation/windowmanager/interfaces/innerkits/wm", - "//foundation/windowmanager/interfaces/kits/napi/window_runtime/window_napi", + "//foundation/windowmanager/interfaces/kits/napi/window_runtime/window_stage_napi", "//third_party/jsoncpp/include", "//third_party/json/include", ] @@ -148,6 +148,12 @@ ohos_shared_library("abilitykit_native") { "${SUBSYSTEM_DIR}/src/data_ability_operation_builder.cpp", "${SUBSYSTEM_DIR}/src/data_ability_result.cpp", "${SUBSYSTEM_DIR}/src/data_uri_utils.cpp", + "${SUBSYSTEM_DIR}/src/datashare_connection.cpp", + "${SUBSYSTEM_DIR}/src/datashare_ext_ability.cpp", + "${SUBSYSTEM_DIR}/src/datashare_helper.cpp", + "${SUBSYSTEM_DIR}/src/datashare_proxy.cpp", + "${SUBSYSTEM_DIR}/src/datashare_stub.cpp", + "${SUBSYSTEM_DIR}/src/datashare_stub_impl.cpp", "${SUBSYSTEM_DIR}/src/extension.cpp", "${SUBSYSTEM_DIR}/src/extension_impl.cpp", "${SUBSYSTEM_DIR}/src/extension_module_loader.cpp", @@ -161,6 +167,8 @@ ohos_shared_library("abilitykit_native") { "${SUBSYSTEM_DIR}/src/form_runtime/form_extension_provider_client.cpp", "${SUBSYSTEM_DIR}/src/form_runtime/js_form_extension.cpp", "${SUBSYSTEM_DIR}/src/form_runtime/js_form_extension_context.cpp", + "${SUBSYSTEM_DIR}/src/js_datashare_ext_ability.cpp", + "${SUBSYSTEM_DIR}/src/js_datashare_ext_ability_context.cpp", "${SUBSYSTEM_DIR}/src/js_service_extension.cpp", "${SUBSYSTEM_DIR}/src/js_service_extension_context.cpp", "${SUBSYSTEM_DIR}/src/js_static_subscriber_extension.cpp", @@ -197,6 +205,7 @@ ohos_shared_library("abilitykit_native") { "${SUBSYSTEM_DIR}/src/continuation/remote_register_service/remote_register_service_stub.cpp", "${SUBSYSTEM_DIR}/src/distributed_ability_runtime/distributed_client.cpp", "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/context/context_impl.cpp", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/datashare_ext_ability_context.cpp", "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/extension_context.cpp", "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/form_extension_context.cpp", "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/service_extension_context.cpp", @@ -216,7 +225,6 @@ ohos_shared_library("abilitykit_native") { "${SUBSYSTEM_DIR}/src/ability_runtime/js_ability.cpp", "${SUBSYSTEM_DIR}/src/ability_runtime/js_ability_context.cpp", "${SUBSYSTEM_DIR}/src/ability_runtime/js_caller_complex.cpp", - "${SUBSYSTEM_DIR}/src/ability_runtime/js_window_stage.cpp", "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_dataability/src/napi_data_ability_predicates.cpp", "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_resultset/src/napi_result_set.cpp", ] @@ -231,7 +239,7 @@ ohos_shared_library("abilitykit_native") { "${INNERKITS_PATH}/base:base", "${INNERKITS_PATH}/want:want", "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", - "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native", "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", @@ -272,7 +280,7 @@ ohos_shared_library("abilitykit_native") { "//foundation/ace/napi:ace_napi", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/graphic/standard:libwmclient", - "//foundation/windowmanager/interfaces/kits/napi/window_runtime:window_native_kit", + "//foundation/windowmanager/interfaces/kits/napi/window_runtime:windowstage_kit", "//foundation/windowmanager/wm:libwm", ] @@ -327,3 +335,27 @@ ohos_shared_library("service_extension_module") { subsystem_name = "aafwk" part_name = "ability_runtime" } + +ohos_shared_library("datashare_ext_ability_module") { + include_dirs = + [ "//foundation/aafwk/standard/frameworks/kits/ability/native/include" ] + + sources = [ "//foundation/aafwk/standard/frameworks/kits/ability/native/src/datashare_ext_ability_module_loader.cpp" ] + + configs = [ ":ability_config" ] + public_configs = [ ":ability_public_config" ] + + deps = [ + ":abilitykit_native", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_runtime:runtime", + "hiviewdfx_hilog_native:libhilog", + ] + + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/frameworks/kits/ability/native/include/ability.h b/frameworks/kits/ability/native/include/ability.h index 8cd852e2d80fbedaa4bd93276a182a4d05329667..55b6f88512d06c6b7b8b07a5a346a41e34ac2a8b 100755 --- a/frameworks/kits/ability/native/include/ability.h +++ b/frameworks/kits/ability/native/include/ability.h @@ -40,6 +40,7 @@ #include "form_provider_info.h" #include "foundation/multimodalinput/input/interfaces/native/innerkits/event/include/key_event.h" #include "foundation/multimodalinput/input/interfaces/native/innerkits/event/include/pointer_event.h" +#include "iability_callback.h" #include "iremote_object.h" #include "pac_map.h" #include "want.h" @@ -76,6 +77,7 @@ class Ability : public IAbilityEvent, public AbilityContext, public FormCallbackInterface, public IAbilityContinuation, + public IAbilityCallback, public std::enable_shared_from_this { public: friend class PageAbilityImpl; @@ -893,6 +895,11 @@ public: */ bool StopAbility(const AAFwk::Want &want) override; + /** + * @brief Release the window and ability. + */ + void Destroy(); + /** * @brief Posts a scheduled Runnable task to a new non-UI thread. * The task posted via this method will be executed in a new thread, which allows you to perform certain @@ -1300,7 +1307,7 @@ public: * * @return A string represents page ability stack info, empty if failed; */ - virtual const std::string& GetContentInfo(); + virtual std::string GetContentInfo(); /** * @brief Migrates this ability to the given device on the same distributed network. The ability to migrate and its @@ -1385,13 +1392,19 @@ public: * @return None. */ void SetSceneListener(const sptr &listener); - + /** * @brief request a remote object of callee from this ability. * @return Returns the remote object of callee. */ virtual sptr CallRequest(); + /** + * @brief Called back at ability context. + */ + virtual int GetCurrentWindowMode() override; + + uint32_t sceneFlag_ = 0; protected: /** * @brief Acquire a form provider remote object. @@ -1595,7 +1608,6 @@ private: */ bool ReAcquireForm(const int64_t formId, const Want &want); }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_H diff --git a/frameworks/kits/ability/native/include/ability_context.h b/frameworks/kits/ability/native/include/ability_context.h index 946802351549154f5d4e703b7c9cecb57ed1f6d1..02466e25abe71992a4ed1bab08380d5794069ea7 100644 --- a/frameworks/kits/ability/native/include/ability_context.h +++ b/frameworks/kits/ability/native/include/ability_context.h @@ -20,6 +20,7 @@ #include "context_container.h" #include "data_ability_helper.h" +#include "datashare_helper.h" namespace OHOS { namespace AppExecFwk { @@ -699,6 +700,7 @@ public: void SetShowOnLockScreen(bool isAllow) override; friend DataAbilityHelper; + friend DataShareHelper; static int ABILITY_CONTEXT_DEFAULT_REQUEST_CODE; protected: diff --git a/frameworks/kits/ability/native/include/ability_runtime/js_ability_context.h b/frameworks/kits/ability/native/include/ability_runtime/js_ability_context.h index 2058b5c0756ec9e6e14dfd971448a0e3b03f826f..30a8e4827736a70a5c3fa47e7d1adbf0b5f7e0af 100755 --- a/frameworks/kits/ability/native/include/ability_runtime/js_ability_context.h +++ b/frameworks/kits/ability/native/include/ability_runtime/js_ability_context.h @@ -81,6 +81,7 @@ private: static NativeValue* WrapAbilityResult(NativeEngine& engine, const int& resultCode, const AAFwk::Want& want); static NativeValue* WrapPermissionRequestResult(NativeEngine& engine, const std::vector &permissions, const std::vector &grantResults); + void InheritWindowMode(AAFwk::Want &want); std::weak_ptr context_; int curRequestCode_ = 0; diff --git a/frameworks/kits/ability/native/include/ability_runtime/js_window_stage.h b/frameworks/kits/ability/native/include/ability_runtime/js_window_stage.h deleted file mode 100644 index a74eb1804418881a93f85bb5805de320468e64c8..0000000000000000000000000000000000000000 --- a/frameworks/kits/ability/native/include/ability_runtime/js_window_stage.h +++ /dev/null @@ -1,74 +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. - */ - -#ifndef INTERFACES_INNERKITS_JS_WINDOW_STAGE_H -#define INTERFACES_INNERKITS_JS_WINDOW_STAGE_H - -#include -#include -#include -#include -#include "window_scene.h" - -class NativeEngine; -class NativeValue; - -namespace OHOS { -namespace AbilityRuntime { -NativeValue* CreateJsWindowStage(NativeEngine& engine, std::shared_ptr windowScene); - -class JsWindowStage : Rosen::IWindowLifeCycle { -public: - JsWindowStage(const std::shared_ptr& windowScene, NativeValue* object) - : windowScene_(windowScene), object_(object) {} - ~JsWindowStage() = default; - static void Finalizer(NativeEngine* engine, void* data, void* hint); - static NativeValue* SetUIContent(NativeEngine* engine, NativeCallbackInfo* info); - static NativeValue* GetMainWindow(NativeEngine* engine, NativeCallbackInfo* info); - static NativeValue* On(NativeEngine* engine, NativeCallbackInfo* info); - static NativeValue* Off(NativeEngine* engine, NativeCallbackInfo* info); - static NativeValue* LoadContent(NativeEngine* engine, NativeCallbackInfo* info); - static NativeValue* GetWindowMode(NativeEngine* engine, NativeCallbackInfo* info); - virtual void AfterForeground() override; - virtual void AfterBackground() override; - virtual void AfterFocused() override; - virtual void AfterUnFocused() override; - -private: - NativeValue* OnSetUIContent(NativeEngine& engine, NativeCallbackInfo& info); - NativeValue* OnGetMainWindow(NativeEngine& engine, NativeCallbackInfo& info); - NativeValue* OnEvent(NativeEngine& engine, NativeCallbackInfo& info); - NativeValue* OffEvent(NativeEngine& engine, NativeCallbackInfo& info); - NativeValue* OnLoadContent(NativeEngine& engine, NativeCallbackInfo& info); - NativeValue* OnGetWindowMode(NativeEngine& engine, NativeCallbackInfo& info); - enum WindowStageEventType { - VISIBLE = 1, - FOCUSED, - UNFOCUSED, - INVISIBLE, - }; - void LifeCycleCallBack(WindowStageEventType type); - - std::shared_ptr windowScene_; - NativeValue* object_ = nullptr; - NativeEngine* engine_ = nullptr; - void* contentStorage_ = nullptr; - sptr lifecycleListener_ = nullptr; - std::map, int> eventCallbackMap_; - bool regLifeCycleListenerFlag_ = false; -}; -} // namespace AbilityRuntime -} // namespace OHOS -#endif // INTERFACES_INNERKITS_JS_WINDOW_STAGE_H diff --git a/frameworks/kits/ability/native/include/ability_window.h b/frameworks/kits/ability/native/include/ability_window.h index 69b5005901dfde25e5486ec41c169991c16cc28b..7006e7443a898ea5e4ceefcc851976b01080ee9c 100644 --- a/frameworks/kits/ability/native/include/ability_window.h +++ b/frameworks/kits/ability/native/include/ability_window.h @@ -74,14 +74,16 @@ public: /** * @brief Called when this ability is background. * + * @param sceneFlag flag for screen, lock or unlock, power on or off. */ - void OnPostAbilityBackground(); + void OnPostAbilityBackground(uint32_t sceneFlag); /** * @brief Called when this ability is foreground. * + * @param sceneFlag flag for screen, lock or unlock, power on or off. */ - void OnPostAbilityForeground(); + void OnPostAbilityForeground(uint32_t sceneFlag); /** * @brief Called when this ability is stopped. diff --git a/frameworks/kits/ability/native/include/data_ability_helper.h b/frameworks/kits/ability/native/include/data_ability_helper.h index d5b5c4c05a978e95f4f92441aa6db36fd34753ad..373531beb72ac84058119a89198251b4bfd064b5 100644 --- a/frameworks/kits/ability/native/include/data_ability_helper.h +++ b/frameworks/kits/ability/native/include/data_ability_helper.h @@ -21,6 +21,7 @@ #include #include "context.h" +#include "foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/context/context.h" #include "uri.h" using Uri = OHOS::Uri; @@ -61,6 +62,17 @@ public: static std::shared_ptr Creator( const std::shared_ptr &context, const std::shared_ptr &uri); + /** + * @brief Creates a DataAbilityHelper instance with the Uri specified based on the given Context. + * + * @param context Indicates the Context object on OHOS. + * @param uri Indicates the database table or disk file to operate. + * + * @return Returns the created DataAbilityHelper instance with a specified Uri. + */ + static std::shared_ptr Creator( + const std::shared_ptr &context, const std::shared_ptr &uri); + /** * @brief You can use this method to specify the Uri of the data to operate and set the binding relationship * between the ability using the Data template (Data ability for short) and the associated client process in @@ -76,6 +88,21 @@ public: static std::shared_ptr Creator( const std::shared_ptr &context, const std::shared_ptr &uri, const bool tryBind); + /** + * @brief You can use this method to specify the Uri of the data to operate and set the binding relationship + * between the ability using the Data template (Data ability for short) and the associated client process in + * a DataAbilityHelper instance. + * + * @param context Indicates the Context object on OHOS. + * @param uri Indicates the database table or disk file to operate. + * @param tryBind Specifies whether the exit of the corresponding Data ability process causes the exit of the + * client process. + * + * @return Returns the created DataAbilityHelper instance. + */ + static std::shared_ptr Creator(const std::shared_ptr &context, + const std::shared_ptr &uri, const bool tryBind); + /** * @brief Creates a DataAbilityHelper instance without specifying the Uri based. * @@ -280,6 +307,8 @@ public: private: DataAbilityHelper(const std::shared_ptr &context, const std::shared_ptr &uri, const sptr &dataAbilityProxy, bool tryBind = false); + DataAbilityHelper(const std::shared_ptr &context, const std::shared_ptr &uri, + const sptr &dataAbilityProxy, bool tryBind = false); DataAbilityHelper(const std::shared_ptr &context); DataAbilityHelper(const sptr &token, const std::shared_ptr &uri, const sptr &dataAbilityProxy); diff --git a/frameworks/kits/ability/native/include/datashare_connection.h b/frameworks/kits/ability/native/include/datashare_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..6b605e761a419d952ed44d24a07b502a4d6564c0 --- /dev/null +++ b/frameworks/kits/ability/native/include/datashare_connection.h @@ -0,0 +1,95 @@ +/* + * 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 + * + * 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_APPEXECFWK_OHOS_DATASHARE_CONNECTION_H +#define FOUNDATION_APPEXECFWK_OHOS_DATASHARE_CONNECTION_H + +#include + +#include "ability_connect_callback_stub.h" +#include "event_handler.h" +#include "idatashare.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +class DataShareConnection : public AAFwk::AbilityConnectionStub { +public: + DataShareConnection() = default; + virtual ~DataShareConnection() = default; + + /** + * @brief get singleton of Class DataShareConnection + * + * @return The singleton of DataShareConnection + */ + static sptr GetInstance(); + + /** + * @brief This method is called back to receive the connection result after an ability calls the + * ConnectAbility method to connect it to a extension ability. + * + * @param element: Indicates information about the connected extension ability. + * @param remote: Indicates the remote proxy object of the extension ability. + * @param resultCode: Indicates the connection result code. The value 0 indicates a successful connection, and any + * other value indicates a connection failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + + /** + * @brief This method is called back to receive the disconnection result after the connected extension ability + * crashes or is killed. If the extension ability exits unexpectedly, all its connections are disconnected, and + * each ability previously connected to it will call onAbilityDisconnectDone. + * + * @param element: Indicates information about the disconnected extension ability. + * @param resultCode: Indicates the disconnection result code. The value 0 indicates a successful disconnection, + * and any other value indicates a disconnection failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; + + /** + * @brief connect remote ability of DataShareExtAbility. + */ + void ConnectDataShareExtAbility(const AAFwk::Want &want, const sptr &token); + + /** + * @brief disconnect remote ability of DataShareExtAbility. + */ + void DisconnectDataShareExtAbility(); + + /** + * @brief check whether connected to remote extension ability. + * + * @return bool true if connected, otherwise false. + */ + bool IsExtAbilityConnected(); + + /** + * @brief get the proxy of datashare extension ability. + * + * @return the proxy of datashare extension ability. + */ + sptr GetDataShareProxy(); + +private: + static sptr instance_; + static std::mutex mutex_; + std::atomic isConnected_ = {false}; + sptr dataShareProxy_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_DATASHARE_CONNECTION_H diff --git a/frameworks/kits/ability/native/include/datashare_ext_ability.h b/frameworks/kits/ability/native/include/datashare_ext_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..53f70397d5ef7dd107b3feee3d34b5401871f091 --- /dev/null +++ b/frameworks/kits/ability/native/include/datashare_ext_ability.h @@ -0,0 +1,245 @@ +/* + * 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 + * + * 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_ABILITYRUNTIME_OHOS_DATASHARE_EXT_ABILITY_H +#define FOUNDATION_ABILITYRUNTIME_OHOS_DATASHARE_EXT_ABILITY_H + +#include "extension_base.h" + +namespace OHOS { +namespace NativeRdb { +class AbsSharedResultSet; +class DataAbilityPredicates; +class ValuesBucket; +} +namespace AAFwk { +class IDataAbilityObserver; +} +namespace AppExecFwk { +class DataAbilityOperation; +class DataAbilityResult; +} +namespace AbilityRuntime { +class DataShareExtAbilityContext; +class Runtime; +/** + * @brief Basic datashare extension ability components. + */ +class DataShareExtAbility : public ExtensionBase { +public: + DataShareExtAbility() = default; + virtual ~DataShareExtAbility() = default; + + /** + * @brief Create and init context. + * + * @param record the extension record. + * @param application the application info. + * @param handler the extension handler. + * @param token the remote token. + * @return The created context. + */ + virtual std::shared_ptr CreateAndInitContext( + const std::shared_ptr &record, + const std::shared_ptr &application, + std::shared_ptr &handler, + const sptr &token) override; + + /** + * @brief Init the extension. + * + * @param record the extension record. + * @param application the application info. + * @param handler the extension handler. + * @param token the remote token. + */ + virtual void Init(const std::shared_ptr &record, + const std::shared_ptr &application, + std::shared_ptr &handler, + const sptr &token) override; + + /** + * @brief Create Extension. + * + * @param runtime The runtime. + * @return The DataShareExtAbility instance. + */ + static DataShareExtAbility* Create(const std::unique_ptr& runtime); + + /** + * @brief Obtains the MIME types of files supported. + * + * @param uri Indicates the path of the files to obtain. + * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. + * + * @return Returns the matched MIME types. If there is no match, null is returned. + */ + virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter); + + /** + * @brief Opens a file in a specified remote path. + * + * @param uri Indicates the path of the file to open. + * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access + * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, + * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data, + * or "rwt" for read and write access that truncates any existing file. + * + * @return Returns the file descriptor. + */ + virtual int OpenFile(const Uri &uri, const std::string &mode); + + /** + * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets + * inside of their .hap. + * + * @param uri Indicates the path of the file to open. + * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access + * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, + * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing + * data, or "rwt" for read and write access that truncates any existing file. + * + * @return Returns the RawFileDescriptor object containing file descriptor. + */ + virtual int OpenRawFile(const Uri &uri, const std::string &mode); + + /** + * @brief Inserts a single data record into the database. + * + * @param uri Indicates the path of the data to operate. + * @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted. + * + * @return Returns the index of the inserted data record. + */ + virtual int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value); + + /** + * @brief Updates data records in the database. + * + * @param uri Indicates the path of data to update. + * @param value Indicates the data to update. This parameter can be null. + * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. + * + * @return Returns the number of data records updated. + */ + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, + const NativeRdb::DataAbilityPredicates &predicates); + + /** + * @brief Deletes one or more data records from the database. + * + * @param uri Indicates the path of the data to operate. + * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. + * + * @return Returns the number of data records deleted. + */ + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates); + + /** + * @brief Deletes one or more data records from the database. + * + * @param uri Indicates the path of data to query. + * @param columns Indicates the columns to query. If this parameter is null, all columns are queried. + * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. + * + * @return Returns the query result. + */ + virtual std::shared_ptr Query( + const Uri &uri, std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates); + + /** + * @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be + * implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG. + * + * @param uri Indicates the URI of the data. + * + * @return Returns the MIME type that matches the data specified by uri. + */ + virtual std::string GetType(const Uri &uri); + + /** + * @brief Inserts multiple data records into the database. + * + * @param uri Indicates the path of the data to operate. + * @param values Indicates the data records to insert. + * + * @return Returns the number of data records inserted. + */ + virtual int BatchInsert(const Uri &uri, const std::vector &values); + + /** + * @brief Registers an observer to DataObsMgr specified by the given Uri. + * + * @param uri, Indicates the path of the data to operate. + * @param dataObserver, Indicates the IDataAbilityObserver object. + */ + virtual bool RegisterObserver(const Uri &uri, const sptr &dataObserver); + + /** + * @brief Deregisters an observer used for DataObsMgr specified by the given Uri. + * + * @param uri, Indicates the path of the data to operate. + * @param dataObserver, Indicates the IDataAbilityObserver object. + */ + virtual bool UnregisterObserver(const Uri &uri, const sptr &dataObserver); + + /** + * @brief Notifies the registered observers of a change to the data resource specified by Uri. + * + * @param uri, Indicates the path of the data to operate. + * + * @return Return true if success. otherwise return false. + */ + virtual bool NotifyChange(const Uri &uri); + + /** + * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used + * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if + * the context has changed. If you implement URI normalization for a Data ability, you must also implement + * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to + * any method that is called on the Data ability must require normalization verification and denormalization. The + * default implementation of this method returns null, indicating that this Data ability does not support URI + * normalization. + * + * @param uri Indicates the Uri object to normalize. + * + * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. + */ + virtual Uri NormalizeUri(const Uri &uri); + + /** + * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. + * The default implementation of this method returns the original URI passed to it. + * + * @param uri uri Indicates the Uri object to denormalize. + * + * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri + * passed to this method if there is nothing to do; returns null if the data identified by the original Uri cannot + * be found in the current environment. + */ + virtual Uri DenormalizeUri(const Uri &uri); + + /** + * @brief Performs batch operations on the database. + * + * @param operations Indicates a list of database operations on the database. + * @return Returns the result of each operation, in array. + */ + virtual std::vector> ExecuteBatch( + const std::vector> &operations); +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // FOUNDATION_ABILITYRUNTIME_OHOS_DATASHARE_EXT_ABILITY_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/datashare_ext_ability_module_loader.h b/frameworks/kits/ability/native/include/datashare_ext_ability_module_loader.h new file mode 100644 index 0000000000000000000000000000000000000000..cc929460a515eddb5325fdd9018fa4e1b124be3b --- /dev/null +++ b/frameworks/kits/ability/native/include/datashare_ext_ability_module_loader.h @@ -0,0 +1,36 @@ +/* + * 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 + * + * 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_ABILITYRUTIME_DATASHARE_EXT_ABILITY_MODULE_LOADER_H +#define FOUNDATION_ABILITYRUTIME_DATASHARE_EXT_ABILITY_MODULE_LOADER_H + +#include "extension_module_loader.h" + +namespace OHOS::AbilityRuntime { +class DataShareExtAbilityModuleLoader : public ExtensionModuleLoader, + public Singleton { + DECLARE_SINGLETON(DataShareExtAbilityModuleLoader); + +public: + /** + * @brief Create Extension. + * + * @param runtime The runtime. + * @return The Extension instance. + */ + virtual Extension *Create(const std::unique_ptr& runtime) const override; +}; +} +#endif // FOUNDATION_ABILITYRUTIME_DATASHARE_EXT_ABILITY_MODULE_LOADER_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/datashare_helper.h b/frameworks/kits/ability/native/include/datashare_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..39cb1935acea396869e28e72de8bf2f7f1732525 --- /dev/null +++ b/frameworks/kits/ability/native/include/datashare_helper.h @@ -0,0 +1,290 @@ +/* + * 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 + * + * 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_APPEXECFWK_OHOS_DATASHARE_HELPER_H +#define FOUNDATION_APPEXECFWK_OHOS_DATASHARE_HELPER_H + +#include +#include +#include + +#include "context.h" +#include "datashare_connection.h" +#include "foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/context/context.h" +#include "idatashare.h" +#include "uri.h" +#include "want.h" + +using Uri = OHOS::Uri; + +namespace OHOS { +namespace NativeRdb { +class AbsSharedResultSet; +class DataAbilityPredicates; +class ValuesBucket; +} // namespace NativeRdb +namespace AppExecFwk { +using string = std::string; +class DataAbilityResult; +class DataAbilityOperation; +class PacMap; +class IDataAbilityObserver; +class DataShareHelper final : public std::enable_shared_from_this { +public: + ~DataShareHelper() = default; + + /** + * @brief Creates a DataShareHelper instance without specifying the Uri based on the given Context. + * + * @param context Indicates the Context object on OHOS. + * @param want Indicates the Want containing information about the target extension ability to connect. + * + * @return Returns the created DataShareHelper instance where Uri is not specified. + */ + static std::shared_ptr Creator(const std::shared_ptr &context, + const AAFwk::Want &want); + + /** + * @brief Creates a DataShareHelper instance with the Uri specified based on the given Context. + * + * @param context Indicates the Context object on OHOS. + * @param want Indicates the Want containing information about the target extension ability to connect. + * @param uri Indicates the database table or disk file to operate. + * + * @return Returns the created DataShareHelper instance with a specified Uri. + */ + static std::shared_ptr Creator(const std::shared_ptr &context, + const AAFwk::Want &want, const std::shared_ptr &uri); + + /** + * @brief Creates a DataShareHelper instance with the Uri specified based on the given Context. + * + * @param context Indicates the Context object on OHOS. + * @param want Indicates the Want containing information about the target extension ability to connect. + * @param uri Indicates the database table or disk file to operate. + * + * @return Returns the created DataShareHelper instance with a specified Uri. + */ + static std::shared_ptr Creator(const std::shared_ptr &context, + const AAFwk::Want &want, const std::shared_ptr &uri); + + /** + * @brief Releases the client resource of the Data share. + * You should call this method to releases client resource after the data operations are complete. + * + * @return Returns true if the resource is successfully released; returns false otherwise. + */ + bool Release(); + /** + * @brief Obtains the MIME types of files supported. + * + * @param uri Indicates the path of the files to obtain. + * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. + * + * @return Returns the matched MIME types. If there is no match, null is returned. + */ + std::vector GetFileTypes(Uri &uri, const std::string &mimeTypeFilter); + + /** + * @brief Opens a file in a specified remote path. + * + * @param uri Indicates the path of the file to open. + * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access + * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, + * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data, + * or "rwt" for read and write access that truncates any existing file. + * + * @return Returns the file descriptor. + */ + int OpenFile(Uri &uri, const std::string &mode); + + /** + * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets + * inside of their .hap. + * + * @param uri Indicates the path of the file to open. + * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access + * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, + * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing + * data, or "rwt" for read and write access that truncates any existing file. + * + * @return Returns the RawFileDescriptor object containing file descriptor. + */ + int OpenRawFile(Uri &uri, const std::string &mode); + + /** + * @brief Inserts a single data record into the database. + * + * @param uri Indicates the path of the data to operate. + * @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted. + * + * @return Returns the index of the inserted data record. + */ + int Insert(Uri &uri, const NativeRdb::ValuesBucket &value); + + /** + * @brief Updates data records in the database. + * + * @param uri Indicates the path of data to update. + * @param value Indicates the data to update. This parameter can be null. + * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. + * + * @return Returns the number of data records updated. + */ + int Update(Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates); + + /** + * @brief Deletes one or more data records from the database. + * + * @param uri Indicates the path of the data to operate. + * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. + * + * @return Returns the number of data records deleted. + */ + int Delete(Uri &uri, const NativeRdb::DataAbilityPredicates &predicates); + + /** + * @brief Deletes one or more data records from the database. + * + * @param uri Indicates the path of data to query. + * @param columns Indicates the columns to query. If this parameter is null, all columns are queried. + * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. + * + * @return Returns the query result. + */ + std::shared_ptr Query( + Uri &uri, std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates); + + /** + * @brief Obtains the MIME type matching the data specified by the URI of the Data share. This method should be + * implemented by a Data share. Data abilities supports general data types, including text, HTML, and JPEG. + * + * @param uri Indicates the URI of the data. + * + * @return Returns the MIME type that matches the data specified by uri. + */ + std::string GetType(Uri &uri); + + /** + * @brief Inserts multiple data records into the database. + * + * @param uri Indicates the path of the data to operate. + * @param values Indicates the data records to insert. + * + * @return Returns the number of data records inserted. + */ + int BatchInsert(Uri &uri, const std::vector &values); + + /** + * @brief Registers an observer to DataObsMgr specified by the given Uri. + * + * @param uri, Indicates the path of the data to operate. + * @param dataObserver, Indicates the IDataAbilityObserver object. + */ + void RegisterObserver(const Uri &uri, const sptr &dataObserver); + + /** + * @brief Deregisters an observer used for DataObsMgr specified by the given Uri. + * + * @param uri, Indicates the path of the data to operate. + * @param dataObserver, Indicates the IDataAbilityObserver object. + */ + void UnregisterObserver(const Uri &uri, const sptr &dataObserver); + + /** + * @brief Notifies the registered observers of a change to the data resource specified by Uri. + * + * @param uri, Indicates the path of the data to operate. + */ + void NotifyChange(const Uri &uri); + + /** + * @brief Converts the given uri that refer to the Data share into a normalized URI. A normalized URI can be used + * across devices, persisted, backed up, and restored. It can refer to the same item in the Data share even if the + * context has changed. If you implement URI normalization for a Data share, you must also implement + * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to + * any method that is called on the Data share must require normalization verification and denormalization. The + * default implementation of this method returns null, indicating that this Data share does not support URI + * normalization. + * + * @param uri Indicates the Uri object to normalize. + * + * @return Returns the normalized Uri object if the Data share supports URI normalization; returns null otherwise. + */ + Uri NormalizeUri(Uri &uri); + + /** + * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. + * The default implementation of this method returns the original URI passed to it. + * + * @param uri uri Indicates the Uri object to denormalize. + * + * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed + * to this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found + * in the current environment. + */ + Uri DenormalizeUri(Uri &uri); + + /** + * @brief Performs batch operations on the database. + * + * @param uri Indicates the path of data to operate. + * @param operations Indicates a list of database operations on the database. + * @return Returns the result of each operation, in array. + */ + std::vector> ExecuteBatch( + const Uri &uri, const std::vector> &operations); + +private: + DataShareHelper(const std::shared_ptr &context, const AAFwk::Want &want); + DataShareHelper(const std::shared_ptr &context, const AAFwk::Want &want, + const std::shared_ptr &uri, const sptr &dataShareProxy); + DataShareHelper(const std::shared_ptr &context, const AAFwk::Want &want, + const std::shared_ptr &uri, const sptr &dataShareProxy); + void AddDataShareDeathRecipient(const sptr &token); + void OnSchedulerDied(const wptr &remote); + bool CheckUriParam(const Uri &uri); + bool CheckOhosUri(const Uri &uri); + + sptr token_ = {}; + std::shared_ptr context_ = nullptr; + AAFwk::Want want_ = {}; + std::shared_ptr uri_ = nullptr; + sptr dataShareProxy_ = nullptr; + bool isSystemCaller_ = false; + std::mutex lock_; + static std::mutex oplock_; + sptr callerDeathRecipient_ = nullptr; + std::map, sptr> registerMap_; + std::map, std::string> uriMap_; + sptr dataShareConnection_ = nullptr; +}; + +class DataShareDeathRecipient : public IRemoteObject::DeathRecipient { +public: + using RemoteDiedHandler = std::function &)>; + + explicit DataShareDeathRecipient(RemoteDiedHandler handler); + + virtual ~DataShareDeathRecipient(); + + virtual void OnRemoteDied(const wptr &remote); + +private: + RemoteDiedHandler handler_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_DATASHARE_HELPER_H diff --git a/frameworks/kits/ability/native/include/datashare_proxy.h b/frameworks/kits/ability/native/include/datashare_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..3f14ee178631d03a8a1e7acf655e2548d9859d20 --- /dev/null +++ b/frameworks/kits/ability/native/include/datashare_proxy.h @@ -0,0 +1,68 @@ +/* + * 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 + * + * 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 OHOS_APPEXECFWK_DATASHARE_PROXY_H +#define OHOS_APPEXECFWK_DATASHARE_PROXY_H + +#include +#include "idatashare.h" + +namespace OHOS { +namespace AppExecFwk { +class DataShareProxy : public IRemoteProxy { +public: + explicit DataShareProxy(const sptr& remote) : IRemoteProxy(remote) {} + + virtual ~DataShareProxy() {} + + virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; + + virtual int OpenFile(const Uri &uri, const std::string &mode) override; + + virtual int OpenRawFile(const Uri &uri, const std::string &mode) override; + + virtual int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, + const NativeRdb::DataAbilityPredicates &predicates) override; + + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + + virtual std::shared_ptr Query(const Uri &uri, + std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) override; + + virtual std::string GetType(const Uri &uri) override; + + virtual int BatchInsert(const Uri &uri, const std::vector &values) override; + + virtual bool RegisterObserver(const Uri &uri, const sptr &dataObserver) override; + + virtual bool UnregisterObserver(const Uri &uri, const sptr &dataObserver) override; + + virtual bool NotifyChange(const Uri &uri) override; + + virtual Uri NormalizeUri(const Uri &uri) override; + + virtual Uri DenormalizeUri(const Uri &uri) override; + + virtual std::vector> ExecuteBatch( + const std::vector> &operations) override; +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_APPEXECFWK_DATASHARE_PROXY_H + diff --git a/frameworks/kits/ability/native/include/datashare_stub.h b/frameworks/kits/ability/native/include/datashare_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..55b90d9f77584c3cc533b76c18c61dff87a5edd2 --- /dev/null +++ b/frameworks/kits/ability/native/include/datashare_stub.h @@ -0,0 +1,54 @@ +/* + * 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 + * + * 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 OHOS_APPEXECFWK_DATASHARE_STUB_H +#define OHOS_APPEXECFWK_DATASHARE_STUB_H + +#include +#include + +#include "idatashare.h" + +namespace OHOS { +namespace AppExecFwk { +class DataShareStub : public IRemoteStub { +public: + DataShareStub(); + ~DataShareStub(); + int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; +private: + ErrCode CmdGetFileTypes(MessageParcel &data, MessageParcel &reply); + ErrCode CmdOpenFile(MessageParcel &data, MessageParcel &reply); + ErrCode CmdOpenRawFile(MessageParcel &data, MessageParcel &reply); + ErrCode CmdInsert(MessageParcel &data, MessageParcel &reply); + ErrCode CmdUpdate(MessageParcel &data, MessageParcel &reply); + ErrCode CmdDelete(MessageParcel &data, MessageParcel &reply); + ErrCode CmdQuery(MessageParcel &data, MessageParcel &reply); + ErrCode CmdGetType(MessageParcel &data, MessageParcel &reply); + ErrCode CmdBatchInsert(MessageParcel &data, MessageParcel &reply); + ErrCode CmdRegisterObserver(MessageParcel &data, MessageParcel &reply); + ErrCode CmdUnregisterObserver(MessageParcel &data, MessageParcel &reply); + ErrCode CmdNotifyChange(MessageParcel &data, MessageParcel &reply); + ErrCode CmdNormalizeUri(MessageParcel &data, MessageParcel &reply); + ErrCode CmdDenormalizeUri(MessageParcel &data, MessageParcel &reply); + ErrCode CmdExecuteBatch(MessageParcel &data, MessageParcel &reply); + + using RequestFuncType = int (DataShareStub::*)(MessageParcel &data, MessageParcel &reply); + std::map stubFuncMap_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_APPEXECFWK_DATASHARE_STUB_H + diff --git a/frameworks/kits/ability/native/include/datashare_stub_impl.h b/frameworks/kits/ability/native/include/datashare_stub_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..0bb655fc779f95f2a6d4f598976af9b77c5e3b31 --- /dev/null +++ b/frameworks/kits/ability/native/include/datashare_stub_impl.h @@ -0,0 +1,70 @@ +/* + * 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 + * + * 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 OHOS_APPEXECFWK_DATASHARE_STUB_IMPL_H +#define OHOS_APPEXECFWK_DATASHARE_STUB_IMPL_H + +#include +#include "datashare_stub.h" +#include "js_datashare_ext_ability.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityRuntime::JsDataShareExtAbility; +class DataShareStubImpl : public DataShareStub { +public: + explicit DataShareStubImpl(const std::shared_ptr& extension) : extension_(extension) {} + + virtual ~DataShareStubImpl() {} + + std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; + + int OpenFile(const Uri &uri, const std::string &mode) override; + + int OpenRawFile(const Uri &uri, const std::string &mode) override; + + int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + + int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, + const NativeRdb::DataAbilityPredicates &predicates) override; + + int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + + std::shared_ptr Query(const Uri &uri, + std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) override; + + std::string GetType(const Uri &uri) override; + + int BatchInsert(const Uri &uri, const std::vector &values) override; + + bool RegisterObserver(const Uri &uri, const sptr &dataObserver) override; + + bool UnregisterObserver(const Uri &uri, const sptr &dataObserver) override; + + bool NotifyChange(const Uri &uri) override; + + Uri NormalizeUri(const Uri &uri) override; + + Uri DenormalizeUri(const Uri &uri) override; + + std::vector> ExecuteBatch( + const std::vector> &operations) override; +private: + std::weak_ptr extension_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_APPEXECFWK_DATASHARE_STUB_IMPL_H + diff --git a/frameworks/kits/ability/native/include/form_runtime/js_form_extension.h b/frameworks/kits/ability/native/include/form_runtime/js_form_extension.h index 03324f275e5b9e04f96692607f82144556977206..179cda869d87b53f1669e4927d282c6528abf3e9 100644 --- a/frameworks/kits/ability/native/include/form_runtime/js_form_extension.h +++ b/frameworks/kits/ability/native/include/form_runtime/js_form_extension.h @@ -18,6 +18,7 @@ #include "form_extension.h" +class NativeEngine; class NativeReference; class NativeValue; @@ -53,9 +54,12 @@ public: void OnVisibilityChange(const std::map& formEventsMap) override; sptr OnConnect(const OHOS::AAFwk::Want& want) override; - private: NativeValue* CallObjectMethod(const char* name, NativeValue* const* argv = nullptr, size_t argc = 0); + bool UnwrapRawImageDataMap(NativeEngine& engine, NativeValue* argv, + std::map& rawImageDataMap); + + void GetSrcPath(std::string &srcPath); JsRuntime& jsRuntime_; std::unique_ptr jsObj_; diff --git a/frameworks/kits/ability/native/include/iability_callback.h b/frameworks/kits/ability/native/include/iability_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..a62753795d5072be4f603e408ca9f91fb6c4a1fc --- /dev/null +++ b/frameworks/kits/ability/native/include/iability_callback.h @@ -0,0 +1,30 @@ +/* + * 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. + */ + +#ifndef FOUNDATION_APPEXECFWK_OHOS_ABILITY_CALLBACK_INTERFACE_H +#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_CALLBACK_INTERFACE_H + +namespace OHOS { +namespace AppExecFwk { +class IAbilityCallback { +public: + /** + * @brief Called back at ability context. + */ + virtual int GetCurrentWindowMode() = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_CALLBACK_INTERFACE_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/idatashare.h b/frameworks/kits/ability/native/include/idatashare.h new file mode 100644 index 0000000000000000000000000000000000000000..ec4275efffe6b63e269007b2754be1b22355b322 --- /dev/null +++ b/frameworks/kits/ability/native/include/idatashare.h @@ -0,0 +1,223 @@ +/* + * 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 + * + * 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 OHOS_APPEXECFWK_I_DATASHARE_H +#define OHOS_APPEXECFWK_I_DATASHARE_H + +#include +#include +#include "uri.h" + +namespace OHOS { +namespace NativeRdb { +class AbsSharedResultSet; +class DataAbilityPredicates; +class ValuesBucket; +} +namespace AAFwk { +class IDataAbilityObserver; +} +namespace AppExecFwk { +class DataAbilityResult; +class DataAbilityOperation; + +class IDataShare : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.AppExecFwk.IDataShare"); + + enum { + CMD_GET_FILE_TYPES = 1, + CMD_OPEN_FILE = 2, + CMD_OPEN_RAW_FILE = 3, + CMD_INSERT = 4, + CMD_UPDATE = 5, + CMD_DELETE = 6, + CMD_QUERY = 7, + CMD_GET_TYPE = 8, + CMD_BATCH_INSERT = 9, + CMD_REGISTER_OBSERVER = 10, + CMD_UNREGISTER_OBSERVER = 11, + CMD_NOTIFY_CHANGE = 12, + CMD_NORMALIZE_URI = 13, + CMD_DENORMALIZE_URI = 14, + CMD_EXECUTE_BATCH = 15, + }; + + /** + * @brief Obtains the MIME types of files supported. + * + * @param uri Indicates the path of the files to obtain. + * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. + * + * @return Returns the matched MIME types. If there is no match, null is returned. + */ + virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) = 0; + + /** + * @brief Opens a file in a specified remote path. + * + * @param uri Indicates the path of the file to open. + * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access + * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, + * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data, + * or "rwt" for read and write access that truncates any existing file. + * + * @return Returns the file descriptor. + */ + virtual int OpenFile(const Uri &uri, const std::string &mode) = 0; + + /** + * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets + * inside of their .hap. + * + * @param uri Indicates the path of the file to open. + * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access + * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, + * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing + * data, or "rwt" for read and write access that truncates any existing file. + * + * @return Returns the RawFileDescriptor object containing file descriptor. + */ + virtual int OpenRawFile(const Uri &uri, const std::string &mode) = 0; + + /** + * @brief Inserts a single data record into the database. + * + * @param uri Indicates the path of the data to operate. + * @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted. + * + * @return Returns the index of the inserted data record. + */ + virtual int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) = 0; + + /** + * @brief Updates data records in the database. + * + * @param uri Indicates the path of data to update. + * @param value Indicates the data to update. This parameter can be null. + * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. + * + * @return Returns the number of data records updated. + */ + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, + const NativeRdb::DataAbilityPredicates &predicates) = 0; + + /** + * @brief Deletes one or more data records from the database. + * + * @param uri Indicates the path of the data to operate. + * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. + * + * @return Returns the number of data records deleted. + */ + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) = 0; + + /** + * @brief Deletes one or more data records from the database. + * + * @param uri Indicates the path of data to query. + * @param columns Indicates the columns to query. If this parameter is null, all columns are queried. + * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. + * + * @return Returns the query result. + */ + virtual std::shared_ptr Query( + const Uri &uri, std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) = 0; + + /** + * @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be + * implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG. + * + * @param uri Indicates the URI of the data. + * + * @return Returns the MIME type that matches the data specified by uri. + */ + virtual std::string GetType(const Uri &uri) = 0; + + /** + * @brief Inserts multiple data records into the database. + * + * @param uri Indicates the path of the data to operate. + * @param values Indicates the data records to insert. + * + * @return Returns the number of data records inserted. + */ + virtual int BatchInsert(const Uri &uri, const std::vector &values) = 0; + + /** + * @brief Registers an observer to DataObsMgr specified by the given Uri. + * + * @param uri, Indicates the path of the data to operate. + * @param dataObserver, Indicates the IDataAbilityObserver object. + */ + virtual bool RegisterObserver(const Uri &uri, const sptr &dataObserver) = 0; + + /** + * @brief Deregisters an observer used for DataObsMgr specified by the given Uri. + * + * @param uri, Indicates the path of the data to operate. + * @param dataObserver, Indicates the IDataAbilityObserver object. + */ + virtual bool UnregisterObserver(const Uri &uri, const sptr &dataObserver) = 0; + + /** + * @brief Notifies the registered observers of a change to the data resource specified by Uri. + * + * @param uri, Indicates the path of the data to operate. + * + * @return Return true if success. otherwise return false. + */ + virtual bool NotifyChange(const Uri &uri) = 0; + + /** + * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used + * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if + * the context has changed. If you implement URI normalization for a Data ability, you must also implement + * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to + * any method that is called on the Data ability must require normalization verification and denormalization. The + * default implementation of this method returns null, indicating that this Data ability does not support URI + * normalization. + * + * @param uri Indicates the Uri object to normalize. + * + * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. + */ + virtual Uri NormalizeUri(const Uri &uri) = 0; + + /** + * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. + * The default implementation of this method returns the original URI passed to it. + * + * @param uri uri Indicates the Uri object to denormalize. + * + * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri + * passed to this method if there is nothing to do; returns null if the data identified by the original Uri cannot + * be found in the current environment. + */ + virtual Uri DenormalizeUri(const Uri &uri) = 0; + + /** + * @brief Performs batch operations on the database. + * + * @param operations Indicates a list of database operations on the database. + * @return Returns the result of each operation, in array. + */ + virtual std::vector> ExecuteBatch( + const std::vector> &operations) = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_APPEXECFWK_I_DATASHARE_H + diff --git a/frameworks/kits/ability/native/include/js_datashare_ext_ability.h b/frameworks/kits/ability/native/include/js_datashare_ext_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..ce8d41ec9c1a0fba94cf55e0c41db53536ef3f4c --- /dev/null +++ b/frameworks/kits/ability/native/include/js_datashare_ext_ability.h @@ -0,0 +1,261 @@ +/* + * 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 + * + * 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_ABILITYRUNTIME_OHOS_JS_DATASHARE_EXT_ABILITY_H +#define FOUNDATION_ABILITYRUNTIME_OHOS_JS_DATASHARE_EXT_ABILITY_H + +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "datashare_ext_ability.h" +#include "js_runtime.h" +#include "native_engine/native_reference.h" +#include "native_engine/native_value.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AbilityRuntime { +using RdbValueBucketNewInstance = napi_value (*)(napi_env env, OHOS::NativeRdb::ValuesBucket& valueBucket); +using RdbResultSetProxyGetNativeObject = OHOS::NativeRdb::AbsSharedResultSet* (*)(const napi_env& env, + const napi_value& arg); +using DataAbilityPredicatesNewInstance = napi_value (*)( + napi_env env, OHOS::NativeRdb::DataAbilityPredicates* predicates); + +/** + * @brief Basic datashare extension ability components. + */ +class JsDataShareExtAbility : public DataShareExtAbility { +public: + JsDataShareExtAbility(JsRuntime& jsRuntime); + virtual ~JsDataShareExtAbility() override; + + /** + * @brief Create JsDataShareExtAbility. + * + * @param runtime The runtime. + * @return The JsDataShareExtAbility instance. + */ + static JsDataShareExtAbility* Create(const std::unique_ptr& runtime); + + /** + * @brief Init the extension. + * + * @param record the extension record. + * @param application the application info. + * @param handler the extension handler. + * @param token the remote token. + */ + void Init(const std::shared_ptr &record, + const std::shared_ptr &application, + std::shared_ptr &handler, + const sptr &token) override; + + /** + * @brief Called when this datashare extension ability is started. You must override this function if you want to + * perform some initialization operations during extension startup. + * + * This function can be called only once in the entire lifecycle of an extension. + * @param Want Indicates the {@link Want} structure containing startup information about the extension. + */ + void OnStart(const AAFwk::Want &want) override; + + /** + * @brief Called when this datashare extension ability is connected for the first time. + * + * You can override this function to implement your own processing logic. + * + * @param want Indicates the {@link Want} structure containing connection information about the datashare + * extension. + * @return Returns a pointer to the sid of the connected datashare extension ability. + */ + sptr OnConnect(const AAFwk::Want &want) override; + + /** + * @brief Obtains the MIME types of files supported. + * + * @param uri Indicates the path of the files to obtain. + * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. + * + * @return Returns the matched MIME types. If there is no match, null is returned. + */ + std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; + + /** + * @brief Opens a file in a specified remote path. + * + * @param uri Indicates the path of the file to open. + * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access + * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, + * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data, + * or "rwt" for read and write access that truncates any existing file. + * + * @return Returns the file descriptor. + */ + int OpenFile(const Uri &uri, const std::string &mode) override; + + /** + * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets + * inside of their .hap. + * + * @param uri Indicates the path of the file to open. + * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access + * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, + * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing + * data, or "rwt" for read and write access that truncates any existing file. + * + * @return Returns the RawFileDescriptor object containing file descriptor. + */ + int OpenRawFile(const Uri &uri, const std::string &mode) override; + + /** + * @brief Inserts a single data record into the database. + * + * @param uri Indicates the path of the data to operate. + * @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted. + * + * @return Returns the index of the inserted data record. + */ + int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + + /** + * @brief Updates data records in the database. + * + * @param uri Indicates the path of data to update. + * @param value Indicates the data to update. This parameter can be null. + * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. + * + * @return Returns the number of data records updated. + */ + int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, + const NativeRdb::DataAbilityPredicates &predicates) override; + + /** + * @brief Deletes one or more data records from the database. + * + * @param uri Indicates the path of the data to operate. + * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. + * + * @return Returns the number of data records deleted. + */ + int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + + /** + * @brief Deletes one or more data records from the database. + * + * @param uri Indicates the path of data to query. + * @param columns Indicates the columns to query. If this parameter is null, all columns are queried. + * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. + * + * @return Returns the query result. + */ + std::shared_ptr Query(const Uri &uri, std::vector &columns, + const NativeRdb::DataAbilityPredicates &predicates) override; + + /** + * @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be + * implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG. + * + * @param uri Indicates the URI of the data. + * + * @return Returns the MIME type that matches the data specified by uri. + */ + std::string GetType(const Uri &uri) override; + + /** + * @brief Inserts multiple data records into the database. + * + * @param uri Indicates the path of the data to operate. + * @param values Indicates the data records to insert. + * + * @return Returns the number of data records inserted. + */ + int BatchInsert(const Uri &uri, const std::vector &values) override; + + /** + * @brief Registers an observer to DataObsMgr specified by the given Uri. + * + * @param uri, Indicates the path of the data to operate. + * @param dataObserver, Indicates the IDataAbilityObserver object. + */ + bool RegisterObserver(const Uri &uri, const sptr &dataObserver) override; + + /** + * @brief Deregisters an observer used for DataObsMgr specified by the given Uri. + * + * @param uri, Indicates the path of the data to operate. + * @param dataObserver, Indicates the IDataAbilityObserver object. + */ + bool UnregisterObserver(const Uri &uri, const sptr &dataObserver) override; + + /** + * @brief Notifies the registered observers of a change to the data resource specified by Uri. + * + * @param uri, Indicates the path of the data to operate. + * + * @return Return true if success. otherwise return false. + */ + bool NotifyChange(const Uri &uri) override; + + /** + * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used + * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if + * the context has changed. If you implement URI normalization for a Data ability, you must also implement + * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to + * any method that is called on the Data ability must require normalization verification and denormalization. The + * default implementation of this method returns null, indicating that this Data ability does not support URI + * normalization. + * + * @param uri Indicates the Uri object to normalize. + * + * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. + */ + Uri NormalizeUri(const Uri &uri) override; + + /** + * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. + * The default implementation of this method returns the original URI passed to it. + * + * @param uri uri Indicates the Uri object to denormalize. + * + * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri + * passed to this method if there is nothing to do; returns null if the data identified by the original Uri cannot + * be found in the current environment. + */ + Uri DenormalizeUri(const Uri &uri) override; + + /** + * @brief Performs batch operations on the database. + * + * @param operations Indicates a list of database operations on the database. + * @return Returns the result of each operation, in array. + */ + std::vector> ExecuteBatch( + const std::vector> &operations) override; +private: + NativeValue* CallObjectMethod(const char* name, NativeValue* const* argv = nullptr, size_t argc = 0); + void GetSrcPath(std::string &srcPath); + void LoadLibrary(); + void UnloadLibrary(); + + JsRuntime& jsRuntime_; + std::unique_ptr jsObj_; + void* libRdbHandle_ = nullptr; + void* libDataAbilityHandle_ = nullptr; + RdbValueBucketNewInstance rdbValueBucketNewInstance_ = nullptr; + RdbResultSetProxyGetNativeObject rdbResultSetProxyGetNativeObject_ = nullptr; + DataAbilityPredicatesNewInstance dataAbilityPredicatesNewInstance_ = nullptr; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // FOUNDATION_ABILITYRUNTIME_OHOS_JS_DATASHARE_EXT_ABILITY_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/js_datashare_ext_ability_context.h b/frameworks/kits/ability/native/include/js_datashare_ext_ability_context.h new file mode 100644 index 0000000000000000000000000000000000000000..02478ffaf943157f29d2007d4d296f4c5e96ed64 --- /dev/null +++ b/frameworks/kits/ability/native/include/js_datashare_ext_ability_context.h @@ -0,0 +1,32 @@ +/* + * 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 + * + * 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 ABILITY_RUNTIME_JS_DATASHARE_EXT_ABILITY_CONTEXT_H +#define ABILITY_RUNTIME_JS_DATASHARE_EXT_ABILITY_CONTEXT_H + +#include + +#include "ability_connect_callback.h" +#include "datashare_ext_ability_context.h" +#include "native_engine/native_engine.h" +#include "native_engine/native_value.h" + +namespace OHOS { +namespace AbilityRuntime { +NativeValue* CreateJsDataShareExtAbilityContext(NativeEngine& engine, + std::shared_ptr context); +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_JS_DATASHARE_EXT_ABILITY_CONTEXT_H diff --git a/frameworks/kits/ability/native/src/ability.cpp b/frameworks/kits/ability/native/src/ability.cpp index 177a9b69f731a92f64053201e48f50670cceeb0f..78046a8c561b05256d5041200682682af6f555fb 100755 --- a/frameworks/kits/ability/native/src/ability.cpp +++ b/frameworks/kits/ability/native/src/ability.cpp @@ -139,6 +139,9 @@ void Ability::Init(const std::shared_ptr &abilityInfo, const std::s } application_ = application; + if (abilityContext_ != nullptr) { + abilityContext_->RegisterAbilityCallback(weak_from_this()); + } APP_LOGI("%{public}s end.", __func__); } @@ -250,15 +253,6 @@ void Ability::OnStop() { BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); APP_LOGI("%{public}s begin.", __func__); - if (scene_ != nullptr) { - scene_ = nullptr; - onSceneDestroyed(); - } - if (abilityWindow_ != nullptr && abilityInfo_->type == AppExecFwk::AbilityType::PAGE) { - APP_LOGI("%{public}s begin abilityWindow_->OnPostAbilityStop.", __func__); - abilityWindow_->OnPostAbilityStop(); - APP_LOGI("%{public}s end abilityWindow_->OnPostAbilityStop.", __func__); - } if (abilityLifecycleExecutor_ == nullptr) { APP_LOGE("Ability::OnStop error. abilityLifecycleExecutor_ == nullptr."); return; @@ -273,6 +267,25 @@ void Ability::OnStop() APP_LOGI("%{public}s end.", __func__); } +/** + * @brief Release the window and ability. + */ +void Ability::Destroy() +{ + APP_LOGI("%{public}s begin.", __func__); + // Release the scene. + if (scene_ != nullptr) { + scene_ = nullptr; + onSceneDestroyed(); + } + + // Release the window. + if (abilityWindow_ != nullptr && abilityInfo_->type == AppExecFwk::AbilityType::PAGE) { + abilityWindow_->OnPostAbilityStop(); // Ability will been released when window destroy. + } + APP_LOGI("%{public}s end.", __func__); +} + /** * @brief Called when this ability enters the STATE_ACTIVE state. * @@ -435,13 +448,15 @@ void Ability::OnBackground() APP_LOGE("Ability::OnBackground error. scene_ == nullptr."); return; } - scene_->GoBackground(); + APP_LOGI("GoBackground sceneFlag:%{public}d.", sceneFlag_); + scene_->GoBackground(sceneFlag_); } else { if (abilityWindow_ == nullptr) { APP_LOGE("Ability::OnBackground error. abilityWindow_ == nullptr."); return; } - abilityWindow_->OnPostAbilityBackground(); + APP_LOGI("OnPostAbilityBackground sceneFlag:%{public}d.", sceneFlag_); + abilityWindow_->OnPostAbilityBackground(sceneFlag_); } APP_LOGI("%{public}s end OnPostAbilityBackground.", __func__); } @@ -1623,7 +1638,7 @@ bool Ability::OnContinue(WantParams &wantParams) * * @return A string represents page ability stack info, empty if failed; */ -const std::string& Ability::GetContentInfo() +std::string Ability::GetContentInfo() { if (scene_ == nullptr) { return ""; @@ -3240,6 +3255,12 @@ sptr Ability::GetWindowOption(const Want &want) APP_LOGI("Ability::GetWindowOption window mode is %{public}d.", windowMode); option->SetWindowMode(static_cast(windowMode)); + if (want.GetElement().GetBundleName() == LAUNCHER_BUNDLE_NAME && + want.GetElement().GetAbilityName() == LAUNCHER_ABILITY_NAME) { + APP_LOGI("Set window type for launcher"); + option->SetWindowType(Rosen::WindowType::WINDOW_TYPE_WALLPAPER); + } + APP_LOGI("%{public}s end", __func__); return option; } @@ -3247,8 +3268,9 @@ sptr Ability::GetWindowOption(const Want &want) void Ability::DoOnForeground(const Want& want) { if (abilityWindow_ != nullptr) { - APP_LOGI("%{public}s begin abilityWindow_->OnPostAbilityForeground.", __func__); - abilityWindow_->OnPostAbilityForeground(); + APP_LOGI("%{public}s begin abilityWindow_->OnPostAbilityForeground, sceneFlag:%{public}d.", + __func__, sceneFlag_); + abilityWindow_->OnPostAbilityForeground(sceneFlag_); APP_LOGI("%{public}s end abilityWindow_->OnPostAbilityForeground.", __func__); } else { APP_LOGI("========================abilityWindow_ != nullptr ======================"); @@ -3264,5 +3286,19 @@ sptr Ability::CallRequest() { return nullptr; } + +int Ability::GetCurrentWindowMode() +{ + APP_LOGI("%{public}s start", __func__); + auto windowMode = static_cast(Rosen::WindowMode::WINDOW_MODE_UNDEFINED); + if (scene_ == nullptr) { + return windowMode; + } + auto window = scene_->GetMainWindow(); + if (window != nullptr) { + windowMode = static_cast(window->GetMode()); + } + return windowMode; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/src/ability_impl.cpp b/frameworks/kits/ability/native/src/ability_impl.cpp index a03ebf5caf71c71a1bdbb609f9587c6e00e5f186..d8c6ec9d22741c0847173449577171a790c6e446 100755 --- a/frameworks/kits/ability/native/src/ability_impl.cpp +++ b/frameworks/kits/ability/native/src/ability_impl.cpp @@ -112,7 +112,6 @@ void AbilityImpl::Stop() return; } - APP_LOGI("AbilityImpl::Stop"); ability_->OnStop(); if ((ability_->GetAbilityInfo()->type == AppExecFwk::AbilityType::PAGE) && (ability_->GetAbilityInfo()->isStageBasedModel)) { @@ -121,7 +120,8 @@ void AbilityImpl::Stop() lifecycleState_ = AAFwk::ABILITY_STATE_INITIAL; } abilityLifecycleCallbacks_->OnAbilityStop(ability_); - + ability_->Destroy(); // Release window and ability. + ability_ = nullptr; APP_LOGI("%{public}s end.", __func__); } diff --git a/frameworks/kits/ability/native/src/ability_process.cpp b/frameworks/kits/ability/native/src/ability_process.cpp index d0cc200cd811c93b769a137953c570ae4dbc1866..d7580e7fcad917c0f8b02b558af06e7755bcfda5 100644 --- a/frameworks/kits/ability/native/src/ability_process.cpp +++ b/frameworks/kits/ability/native/src/ability_process.cpp @@ -61,8 +61,15 @@ ErrCode AbilityProcess::StartAbility(Ability *ability, CallAbilityParam param, C return ERR_NULL_OBJECT; } - ErrCode err = ERR_OK; + // inherit split mode + auto windowMode = ability->GetCurrentWindowMode(); + if (windowMode == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY || + windowMode == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_SECONDARY) { + param.want.SetParam(Want::PARAM_RESV_WINDOW_MODE, windowMode); + } + APP_LOGI("window mode is %{public}d", windowMode); + ErrCode err = ERR_OK; if (param.forResultOption == true) { if (param.setting == nullptr) { APP_LOGI("%{public}s param.setting == nullptr call StartAbilityForResult.", __func__); diff --git a/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp b/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp index 314e95709ee42ba4ac6d5801cec23dfb606238d5..69e0df89b380ad50ecd43d4a3d091fa66c7e25fc 100755 --- a/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp +++ b/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp @@ -18,7 +18,6 @@ #include "ability_runtime/js_ability.h" #include "ability_runtime/js_ability_context.h" -#include "ability_runtime/js_window_stage.h" #include "ability_start_setting.h" #include "connection_manager.h" #include "hilog_wrapper.h" @@ -26,6 +25,7 @@ #include "js_runtime.h" #include "js_runtime_utils.h" #include "napi_common_configuration.h" +#include "js_window_stage.h" #include "napi_common_want.h" #include "napi_remote_object.h" #include "string_wrapper.h" @@ -392,7 +392,7 @@ std::unique_ptr JsAbility::CreateAppWindowStage() { HandleScope handleScope(jsRuntime_); auto &engine = jsRuntime_.GetNativeEngine(); - NativeValue *jsWindowStage = CreateJsWindowStage(engine, GetScene()); + NativeValue *jsWindowStage = Rosen::CreateJsWindowStage(engine, GetScene()); if (jsWindowStage == nullptr) { HILOG_ERROR("Failed to create jsWindowSatge object"); return nullptr; @@ -457,8 +457,8 @@ void JsAbility::DoOnForeground(const Want &want) OnSceneCreated(); } } - HILOG_INFO("%{public}s begin scene_->GoForeground.", __func__); - scene_->GoForeground(); + HILOG_INFO("%{public}s begin scene_->GoForeground, sceneFlag_:%{public}d.", __func__, Ability::sceneFlag_); + scene_->GoForeground(Ability::sceneFlag_); HILOG_INFO("%{public}s end scene_->GoForeground.", __func__); } } // namespace AbilityRuntime diff --git a/frameworks/kits/ability/native/src/ability_runtime/js_ability_context.cpp b/frameworks/kits/ability/native/src/ability_runtime/js_ability_context.cpp index 404dd116c9bb4eb047c73268843a44b3e66f410e..79c6822c09e796d4e25301f59f3dbcc12e60695b 100755 --- a/frameworks/kits/ability/native/src/ability_runtime/js_ability_context.cpp +++ b/frameworks/kits/ability/native/src/ability_runtime/js_ability_context.cpp @@ -40,6 +40,15 @@ constexpr size_t ARGC_TWO = 2; constexpr size_t ARGC_THREE = 3; constexpr int32_t ERROR_CODE_ONE = 1; +class StartAbilityByCallParameters { +public: + int err = 0; + sptr remoteCallee = nullptr; + std::shared_ptr callerCallBack = nullptr; + std::mutex mutexlock; + std::condition_variable condition; +}; + void JsAbilityContext::Finalizer(NativeEngine* engine, void* data, void* hint) { HILOG_INFO("JsAbilityContext::Finalizer is called"); @@ -67,6 +76,7 @@ NativeValue* JsAbilityContext::StartAbilityByCall(NativeEngine* engine, NativeCa NativeValue* JsAbilityContext::StartAbilityForResult(NativeEngine* engine, NativeCallbackInfo* info) { + BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); JsAbilityContext* me = CheckParamsAndGetThis(engine, info); return (me != nullptr) ? me->OnStartAbilityForResult(*engine, *info) : nullptr; } @@ -135,8 +145,8 @@ NativeValue* JsAbilityContext::OnStartAbility(NativeEngine& engine, NativeCallba } AAFwk::Want want; OHOS::AppExecFwk::UnwrapWant(reinterpret_cast(&engine), reinterpret_cast(info.argv[0]), want); + InheritWindowMode(want); decltype(info.argc) unwrapArgc = 1; - HILOG_INFO("abilityName=%{public}s", want.GetElement().GetAbilityName().c_str()); AAFwk::StartOptions startOptions; if (info.argc > ARGC_ONE && info.argv[1]->TypeOf() == NATIVE_OBJECT) { @@ -145,7 +155,6 @@ NativeValue* JsAbilityContext::OnStartAbility(NativeEngine& engine, NativeCallba reinterpret_cast(info.argv[1]), startOptions); unwrapArgc++; } - AsyncTask::CompleteCallback complete = [weak = context_, want, startOptions, unwrapArgc](NativeEngine& engine, AsyncTask& task, int32_t status) { auto context = weak.lock(); @@ -154,7 +163,6 @@ NativeValue* JsAbilityContext::OnStartAbility(NativeEngine& engine, NativeCallba task.Reject(engine, CreateJsError(engine, 1, "Context is released")); return; } - auto errcode = (unwrapArgc == 1) ? context->StartAbility(want, -1) : context->StartAbility(want, startOptions, -1); if (errcode == 0) { @@ -180,6 +188,7 @@ NativeValue* JsAbilityContext::OnStartAbilityWithAccount(NativeEngine& engine, N } AAFwk::Want want; OHOS::AppExecFwk::UnwrapWant(reinterpret_cast(&engine), reinterpret_cast(info.argv[0]), want); + InheritWindowMode(want); decltype(info.argc) unwrapArgc = 1; HILOG_INFO("abilityName=%{public}s", want.GetElement().GetAbilityName().c_str()); int32_t accountId = 0; @@ -196,7 +205,6 @@ NativeValue* JsAbilityContext::OnStartAbilityWithAccount(NativeEngine& engine, N reinterpret_cast(info.argv[ARGC_TWO]), startOptions); unwrapArgc++; } - AsyncTask::CompleteCallback complete = [weak = context_, want, accountId, startOptions, unwrapArgc]( NativeEngine& engine, AsyncTask& task, int32_t status) { @@ -226,54 +234,117 @@ NativeValue* JsAbilityContext::OnStartAbilityWithAccount(NativeEngine& engine, N NativeValue* JsAbilityContext::OnStartAbilityByCall(NativeEngine& engine, NativeCallbackInfo& info) { - int errCode = 0; - sptr remoteCallee; - if (info.argc != ARGC_ONE || info.argv[0]->TypeOf() != NATIVE_OBJECT) { + HILOG_DEBUG("JsAbilityContext::%{public}s, called", __func__); + constexpr size_t ARGC_ONE = 1; + constexpr size_t ARGC_TWO = 2; + if (info.argc < ARGC_ONE || info.argv[0]->TypeOf() != NATIVE_OBJECT) { HILOG_ERROR("int put params count error"); return engine.CreateUndefined(); } + AAFwk::Want want; OHOS::AppExecFwk::UnwrapWant(reinterpret_cast(&engine), reinterpret_cast(info.argv[0]), want); - NativeValue* callerComplex = nullptr; - std::mutex mutexlock; - std::condition_variable condition; - auto callBackDone = [&mutexlock, &condition, &remoteCallee](const sptr &obj) { - std::unique_lock lock(mutexlock); - remoteCallee = obj; - condition.notify_all(); - HILOG_INFO("OnStartAbilityByCall callBackDone is called"); + InheritWindowMode(want); + + StartAbilityByCallParameters *calls = new (std::nothrow) StartAbilityByCallParameters(); + if (calls == nullptr) { + HILOG_ERROR("calls create error"); + return engine.CreateUndefined(); + } + HILOG_INFO("OnStartAbilityByCall calls is %{public}p", calls); + + NativeValue* lastParam = ((info.argc == ARGC_TWO) ? info.argv[ARGC_ONE] : nullptr); + NativeValue* retsult = nullptr; + + calls->callerCallBack = std::make_shared(); + + auto callBackDone = [calldata = calls] (const sptr &obj) { + HILOG_INFO("OnStartAbilityByCall callBackDone calls is %{public}p", calldata); + HILOG_DEBUG("OnStartAbilityByCall callBackDone mutexlock"); + std::unique_lock lock(calldata->mutexlock); + HILOG_DEBUG("OnStartAbilityByCall callBackDone remoteCallee assignment"); + calldata->remoteCallee = obj; + HILOG_DEBUG("OnStartAbilityByCall callBackDone notifyall %{public}p", calldata->remoteCallee.GetRefPtr()); + calldata->condition.notify_all(); + HILOG_INFO("OnStartAbilityByCall callBackDone is called end"); }; + auto releaseListen = [](const std::string &str) { HILOG_INFO("OnStartAbilityByCall releaseListen is called %{public}s", str.c_str()); }; + + auto callExecute = [calldata = calls] (NativeEngine& engine, AsyncTask& task) { + HILOG_INFO("OnStartAbilityByCall callExecute begin, calls is %{public}p", calldata); + constexpr int CALLER_TIME_OUT = 10; // 10s + std::unique_lock lock(calldata->mutexlock); + if (calldata->remoteCallee != nullptr) { + HILOG_INFO("OnStartAbilityByCall callExecute callee isn`t nullptr"); + return; + } + HILOG_DEBUG("OnStartAbilityByCall callExecute remoteCallee %{public}p", calldata->remoteCallee.GetRefPtr()); + + if (calldata->condition.wait_for(lock, std::chrono::seconds(CALLER_TIME_OUT)) == std::cv_status::timeout) { + HILOG_ERROR("OnStartAbilityByCall callExecute waiting callee timeout"); + calldata->err = -1; + } + HILOG_DEBUG("OnStartAbilityByCall callExecute end"); + }; + + auto callComplete = [weak = context_, calldata = calls] ( + NativeEngine& engine, AsyncTask& task, int32_t status) { + HILOG_INFO("OnStartAbilityByCall callComplete begin, calls is %{public}p", calldata); + if (calldata->err != 0) { + HILOG_ERROR("OnStartAbilityByCall callComplete err is %{public}d", calldata->err); + task.Reject(engine, CreateJsError(engine, calldata->err, "callComplete err.")); + delete calldata; + return; + } + + auto context = weak.lock(); + if (context != nullptr && calldata->callerCallBack != nullptr && calldata->remoteCallee != nullptr) { + task.Resolve(engine, + CreateJsCallerComplex(engine, context, calldata->remoteCallee, calldata->callerCallBack)); + } else { + HILOG_ERROR("OnStartAbilityByCall callComplete params error %{public}s is nullptr", + context == nullptr ? "context" : + (calldata->remoteCallee == nullptr ? "remoteCallee" : "callerCallBack")); + task.Reject(engine, CreateJsError(engine, -1, "Create Call Failed.")); + } + + delete calldata; + HILOG_DEBUG("OnStartAbilityByCall callComplete end"); + }; + + calls->callerCallBack->SetCallBack(callBackDone); + calls->callerCallBack->SetOnRelease(releaseListen); + auto context = context_.lock(); - constexpr int CALLER_TIME_OUT = 5; // 5s - if (!context) { - HILOG_ERROR("context is released"); - errCode = -1; + if (context == nullptr) { + HILOG_ERROR("OnStartAbilityByCall context is nullptr"); return engine.CreateUndefined(); } - std::shared_ptr callerCallBack = std::make_shared(); - callerCallBack->SetCallBack(callBackDone); - callerCallBack->SetOnRelease(releaseListen); - HILOG_INFO("OnStartAbilityByCall execute is StartAbility"); - errCode = context->StartAbility(want, callerCallBack); - if (remoteCallee == nullptr) { - HILOG_INFO("OnStartAbilityByCall lock mutexlock Done"); - std::unique_lock lock(mutexlock); - HILOG_INFO("OnStartAbilityByCall lock waiting callBackDone"); - if (condition.wait_for(lock, std::chrono::seconds(CALLER_TIME_OUT)) == std::cv_status::timeout) { - remoteCallee = nullptr; - errCode = -1; - HILOG_ERROR("Waiting callee timeout"); - return engine.CreateUndefined(); - } + + if (context->StartAbility(want, calls->callerCallBack) != 0) { + HILOG_ERROR("OnStartAbilityByCall StartAbility is failed"); + return engine.CreateUndefined(); + } + + if (calls->remoteCallee == nullptr) { + HILOG_INFO("OnStartAbilityByCall async wait execute"); + AsyncTask::Schedule( + engine, + CreateAsyncTaskWithLastParam( + engine, lastParam, std::move(callExecute), std::move(callComplete), &retsult)); } else { - HILOG_INFO("OnStartAbilityByCall remoteCallee isn~t nullptr"); + HILOG_INFO("OnStartAbilityByCall promiss return result execute"); + AsyncTask::Schedule( + engine, + CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(callComplete), &retsult)); } - callerComplex = CreateJsCallerComplex(engine, context, remoteCallee, callerCallBack); - return callerComplex; + + HILOG_DEBUG("JsAbilityContext::%{public}s, called end", __func__); + return retsult; } NativeValue* JsAbilityContext::OnStartAbilityForResult(NativeEngine& engine, NativeCallbackInfo& info) @@ -290,6 +361,7 @@ NativeValue* JsAbilityContext::OnStartAbilityForResult(NativeEngine& engine, Nat HILOG_ERROR("%s Failed to parse want!", __func__); return engine.CreateUndefined(); } + InheritWindowMode(want); decltype(info.argc) unwrapArgc = 1; AAFwk::StartOptions startOptions; if (info.argc > ARGC_ONE && info.argv[1]->TypeOf() == NATIVE_OBJECT) { @@ -340,6 +412,7 @@ NativeValue* JsAbilityContext::OnStartAbilityForResultWithAccount(NativeEngine& HILOG_ERROR("%s Failed to parse want!", __func__); return engine.CreateUndefined(); } + InheritWindowMode(want); decltype(info.argc) unwrapArgc = 1; int32_t accountId = 0; if (!OHOS::AppExecFwk::UnwrapInt32FromJS2(reinterpret_cast(&engine), @@ -799,6 +872,23 @@ NativeValue* JsAbilityContext::WrapPermissionRequestResult(NativeEngine& engine, return jsPermissionRequestResult; } +void JsAbilityContext::InheritWindowMode(AAFwk::Want &want) +{ + HILOG_INFO("%{public}s called.", __func__); + // only split mode need inherit + auto context = context_.lock(); + if (!context) { + HILOG_ERROR("context is nullptr."); + return; + } + auto windowMode = context->GetCurrentWindowMode(); + if (windowMode == AAFwk::AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY || + windowMode == AAFwk::AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_SECONDARY) { + want.SetParam(Want::PARAM_RESV_WINDOW_MODE, windowMode); + } + HILOG_INFO("%{public}s called end. window mode is %{public}d", __func__, windowMode); +} + void JsAbilityContext::ConfigurationUpdated(NativeEngine* engine, std::shared_ptr &jsContext, const std::shared_ptr &config) { diff --git a/frameworks/kits/ability/native/src/ability_runtime/js_caller_complex.cpp b/frameworks/kits/ability/native/src/ability_runtime/js_caller_complex.cpp index bb553457003aa3e85fcf3ba3ce53745eba92e499..1f317c0f8e9729646c611f12a4bc69529d1bd776 100644 --- a/frameworks/kits/ability/native/src/ability_runtime/js_caller_complex.cpp +++ b/frameworks/kits/ability/native/src/ability_runtime/js_caller_complex.cpp @@ -128,6 +128,8 @@ private: NativeValue* callback = jsreleaseCallBackObj_->Get(); NativeValue* args[] = { CreateJsValue(releaseCallBackEngine_, str) }; releaseCallBackEngine_.CallFunction(value, callback, args, 1); + HILOG_DEBUG("OnReleaseNotifyTask CallFunction call done"); + callee_ = nullptr; HILOG_DEBUG("OnReleaseNotifyTask end"); } @@ -234,6 +236,12 @@ NativeValue* CreateJsCallerComplex( std::shared_ptr callerCallBack) { HILOG_DEBUG("JsCallerComplex::%{public}s, begin", __func__); + if (callee == nullptr || callerCallBack == nullptr || context == nullptr) { + HILOG_ERROR("%{public}s is called, input params error. %{public}s is nullptr", __func__, + (callee == nullptr) ? ("callee") : ((context == nullptr) ? ("context") : ("callerCallBack"))); + return engine.CreateUndefined(); + } + NativeValue* objValue = engine.CreateObject(); NativeObject* object = ConvertNativeValueTo(objValue); @@ -260,6 +268,10 @@ NativeValue* CreateJsCallerComplex( NativeValue* CreateJsCalleeRemoteObject(NativeEngine& engine, sptr callee) { + if (callee == nullptr) { + HILOG_ERROR("%{public}s is called, input params is nullptr", __func__); + return engine.CreateUndefined(); + } napi_value napiRemoteObject = NAPI_ohos_rpc_CreateJsRemoteObject( reinterpret_cast(&engine), callee); NativeValue* nativeRemoteObject = reinterpret_cast(napiRemoteObject); diff --git a/frameworks/kits/ability/native/src/ability_runtime/js_window_stage.cpp b/frameworks/kits/ability/native/src/ability_runtime/js_window_stage.cpp deleted file mode 100644 index 4f50cf344b5a0a8dada3c0628f65c2cec12c1998..0000000000000000000000000000000000000000 --- a/frameworks/kits/ability/native/src/ability_runtime/js_window_stage.cpp +++ /dev/null @@ -1,393 +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. - */ - -#include "ability_runtime/js_window_stage.h" - -#include -#include "ability_runtime/js_ability_context.h" -#include "hilog_wrapper.h" -#include "js_runtime_utils.h" -#include "js_window.h" - -namespace OHOS { -namespace AbilityRuntime { -namespace { -const int CONTENT_STORAGE_ARG = 2; -constexpr size_t ARGC_TWO = 2; -constexpr size_t ARGC_THREE = 3; -constexpr size_t INDEX_ONE = 1; -constexpr size_t INDEX_TWO = 2; -} // namespace - -void JsWindowStage::Finalizer(NativeEngine* engine, void* data, void* hint) -{ - HILOG_INFO("JsWindowStage::Finalizer is called"); - std::unique_ptr(static_cast(data)); -} - -NativeValue* JsWindowStage::SetUIContent(NativeEngine* engine, NativeCallbackInfo* info) -{ - HILOG_INFO("JsWindowStage::SetUIContent is called"); - JsWindowStage* me = AbilityRuntime::CheckParamsAndGetThis(engine, info); - return (me != nullptr) ? me->OnSetUIContent(*engine, *info) : nullptr; -} - -NativeValue* JsWindowStage::GetMainWindow(NativeEngine* engine, NativeCallbackInfo* info) -{ - HILOG_INFO("JsWindowStage::GetMainWindow is called"); - JsWindowStage* me = AbilityRuntime::CheckParamsAndGetThis(engine, info); - return (me != nullptr) ? me->OnGetMainWindow(*engine, *info) : nullptr; -} - -NativeValue* JsWindowStage::On(NativeEngine* engine, NativeCallbackInfo* info) -{ - HILOG_INFO("JsWindowStage::On is called"); - JsWindowStage* me = AbilityRuntime::CheckParamsAndGetThis(engine, info); - return (me != nullptr) ? me->OnEvent(*engine, *info) : nullptr; -} - -NativeValue* JsWindowStage::Off(NativeEngine* engine, NativeCallbackInfo* info) -{ - HILOG_INFO("JsWindowStage::Off is called"); - JsWindowStage* me = AbilityRuntime::CheckParamsAndGetThis(engine, info); - return (me != nullptr) ? me->OffEvent(*engine, *info) : nullptr; -} - -NativeValue* JsWindowStage::LoadContent(NativeEngine* engine, NativeCallbackInfo* info) -{ - HILOG_INFO("JsWindowStage::LoadContent is called"); - JsWindowStage* me = CheckParamsAndGetThis(engine, info); - return (me != nullptr) ? me->OnLoadContent(*engine, *info) : nullptr; -} - -NativeValue* JsWindowStage::GetWindowMode(NativeEngine* engine, NativeCallbackInfo* info) -{ - HILOG_INFO("JsWindowStage::GetWindowMode is called"); - JsWindowStage* me = CheckParamsAndGetThis(engine, info); - return (me != nullptr) ? me->OnGetWindowMode(*engine, *info) : nullptr; -} - -void JsWindowStage::AfterForeground() -{ - LifeCycleCallBack(WindowStageEventType::VISIBLE); -} - -void JsWindowStage::AfterBackground() -{ - LifeCycleCallBack(WindowStageEventType::INVISIBLE); -} - -void JsWindowStage::AfterFocused() -{ - LifeCycleCallBack(WindowStageEventType::FOCUSED); -} - -void JsWindowStage::AfterUnFocused() -{ - LifeCycleCallBack(WindowStageEventType::UNFOCUSED); -} - -void JsWindowStage::LifeCycleCallBack(WindowStageEventType type) -{ - HILOG_INFO("JsWindowStage::LifeCycleCallBack is called, type: %{public}d", type); - if (engine_ == nullptr) { - HILOG_INFO("JsWindowStage::LifeCycleCallBack engine_ is nullptr"); - return; - } - for (auto iter = eventCallbackMap_.begin(); iter != eventCallbackMap_.end(); iter++) { - std::shared_ptr callback = iter->first; - int argc = 1; - NativeValue* argv[1]; - argv[0] = engine_->CreateNumber((int32_t)type); - engine_->CallFunction(object_, callback->Get(), argv, argc); - } -} - -NativeValue* JsWindowStage::OnSetUIContent(NativeEngine& engine, NativeCallbackInfo& info) -{ - HILOG_INFO("JsWindowStage::OnSetUIContent is called"); - if (info.argc < 2) { // 2: minimum param nums - HILOG_ERROR("JsWindowStage::OnSetUIContent Not enough params"); - return engine.CreateUndefined(); - } - if (windowScene_ == nullptr || windowScene_->GetMainWindow() == nullptr) { - HILOG_ERROR("JsWindowStage::OnSetUIContent windowScene_ or MainWindow is nullptr"); - return engine.CreateUndefined(); - } - - // Parse info->argv[0] as abilitycontext - auto objContext = AbilityRuntime::ConvertNativeValueTo(info.argv[0]); - if (objContext == nullptr) { - HILOG_ERROR("JsWindowStage::OnSetUIContent info->argv[0] InValid"); - return engine.CreateUndefined(); - } - - auto context = static_cast*>(objContext->GetNativePointer()); - auto abilityContext = Context::ConvertTo(context->lock()); - if (abilityContext == nullptr) { - HILOG_ERROR("JsWindowStage::OnSetUIContent context is nullptr"); - return engine.CreateUndefined(); - } - - HILOG_INFO("JsWindowStage::OnSetUIContent Get context: %{public}p", abilityContext.get()); - - // Parse info->argv[1] as url - std::string contextUrl; - if (!ConvertFromJsValue(engine, info.argv[1], contextUrl)) { - HILOG_ERROR("JsWindowStage::OnSetUIContent failed to convert parameter to url"); - return engine.CreateUndefined(); - } - HILOG_INFO("JsWindowStage::OnSetUIContent Get url: %{public}s", contextUrl.c_str()); - - windowScene_->GetMainWindow()->SetUIContent(contextUrl, &engine, info.argv[CONTENT_STORAGE_ARG]); - - return engine.CreateUndefined(); -} - -NativeValue* JsWindowStage::OnGetMainWindow(NativeEngine& engine, NativeCallbackInfo& info) -{ - HILOG_INFO("JsWindowStage::OnGetMainWindow is called"); - if (windowScene_ == nullptr) { - HILOG_ERROR("JsWindowStage::OnGetMainWindow windowScene_ is nullptr"); - return engine.CreateUndefined(); - } - AsyncTask::CompleteCallback complete = - [this](NativeEngine& engine, AsyncTask& task, int32_t status) { - auto window = windowScene_->GetMainWindow(); - if (window != nullptr) { - task.Resolve(engine, OHOS::Rosen::CreateJsWindowObject(engine, window)); - HILOG_INFO("JsWindowStage::OnGetMainWindow success"); - } else { - task.Reject(engine, CreateJsError(engine, - static_cast(Rosen::WMError::WM_ERROR_NULLPTR), - "JsWindowStage::OnGetMainWindow failed.")); - } - }; - - NativeValue* lastParam = (info.argc == 0) ? nullptr : info.argv[0]; - NativeValue* result = nullptr; - AsyncTask::Schedule( - engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, - std::move(complete), &result)); - return result; -} - -NativeValue* JsWindowStage::OnEvent(NativeEngine& engine, NativeCallbackInfo& info) -{ - HILOG_INFO("JsWindowStage::OnEvent is called"); - if (windowScene_ == nullptr) { - HILOG_ERROR("JsWindowStage::OnEvent windowScene_ is nullptr"); - return engine.CreateUndefined(); - } - - if (info.argc < 2) { // 2: minimum param nums - HILOG_ERROR("JsWindowStage::OnEvent wrong input params"); - return engine.CreateUndefined(); - } - - // Parse info->argv[0] as string - std::string eventString; - if (!ConvertFromJsValue(engine, info.argv[0], eventString)) { - HILOG_ERROR("JsWindowStage::OnEvent info->argv[0] Failed to convert parameter to string"); - return engine.CreateUndefined(); - } - if (eventString.compare("windowStageEvent") != 0) { - HILOG_ERROR("JsWindowStage::OnEvent info->argv[0] is %{public}s, InValid", - eventString.c_str()); - return engine.CreateUndefined(); - } - - NativeValue* value = info.argv[1]; - if (!value->IsCallable()) { - HILOG_ERROR("JsWindowStage::OnEvent info->argv[1] is not callable"); - return engine.CreateUndefined(); - } - - std::shared_ptr refence = nullptr; - refence.reset(engine.CreateReference(value, 1)); - eventCallbackMap_[refence] = 1; - engine_ = &engine; - - AsyncTask::CompleteCallback complete = - [this](NativeEngine& engine, AsyncTask& task, int32_t status) { - // regist lifecycle listener - if (regLifeCycleListenerFlag_ == false) { - auto window = windowScene_->GetMainWindow(); - if (window != nullptr) { - sptr listener = this; - window->RegisterLifeCycleListener(listener); - regLifeCycleListenerFlag_ = true; - } - } - task.Resolve(engine, engine.CreateUndefined()); - HILOG_INFO("JsWindowStage::OnEvent regist lifecycle success"); - }; - NativeValue* lastParam = (info.argc == 2) ? nullptr : info.argv[2]; // 2: minimum param nums - NativeValue* result = nullptr; - AsyncTask::Schedule(engine, - CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); - return result; -} - -NativeValue* JsWindowStage::OffEvent(NativeEngine& engine, NativeCallbackInfo& info) -{ - HILOG_INFO("JsWindowStage::OffEvent is called"); - if (windowScene_ == nullptr) { - HILOG_ERROR("JsWindowStage::OffEvent windowScene_ is nullptr"); - return engine.CreateUndefined(); - } - if (info.argc < 1 || info.argc > 2) { // 1: minimum param nums, 2: maximum param nums - HILOG_ERROR("JsWindowStage::OffEvent wrong input params"); - return engine.CreateUndefined(); - } - - // Parse info->argv[0] as string - std::string eventString; - if (!ConvertFromJsValue(engine, info.argv[0], eventString)) { - HILOG_ERROR("JsWindowStage::OffEvent info->argv[0] Failed to convert parameter to string"); - return engine.CreateUndefined(); - } - if (eventString.compare("windowStageEvent") != 0) { - HILOG_ERROR("JsWindowStage::OffEvent info->argv[0] is InValid"); - return engine.CreateUndefined(); - } - - if (info.argc == 1) { // 1: input param nums - HILOG_ERROR("JsWindowStage::OffEvent info.argc == 1"); - eventCallbackMap_.clear(); - return engine.CreateUndefined(); - } - - HILOG_INFO("JsWindowStage::OffEvent info.argc == 2"); - NativeValue* value = info.argv[1]; - if (value->IsCallable()) { - HILOG_INFO("JsWindowStage::OffEvent info->argv[1] is callable type"); - for (auto iter = eventCallbackMap_.begin(); iter != eventCallbackMap_.end(); iter++) { - std::shared_ptr callback = iter->first; - if (value->StrictEquals(callback->Get())) { - eventCallbackMap_.erase(iter); - break; - } - } - return engine.CreateUndefined(); - } else if (value->TypeOf() == NativeValueType::NATIVE_UNDEFINED) { - HILOG_INFO("JsWindowStage::OffEvent info->argv[1] is native undefined type"); - eventCallbackMap_.clear(); - } else { - HILOG_ERROR("JsWindowStage::OffEvent info->argv[1] is InValid param"); - } - return engine.CreateUndefined(); -} - -NativeValue* JsWindowStage::OnLoadContent(NativeEngine& engine, NativeCallbackInfo& info) -{ - HILOG_INFO("JsWindowStage::OnLoadContent is called"); - if (info.argc <= 0 || windowScene_ == nullptr) { - HILOG_ERROR("JsWindowStage param not match or windowScene_ is nullptr"); - return engine.CreateUndefined(); - } - std::string contextUrl; - if (!ConvertFromJsValue(engine, info.argv[0], contextUrl)) { - HILOG_ERROR("Failed to convert parameter to context url"); - return engine.CreateUndefined(); - } - NativeValue* storage = nullptr; - NativeValue* callBack = nullptr; - if (info.argc == ARGC_TWO) { - NativeValue* value = info.argv[INDEX_ONE]; - if (value->TypeOf() == NATIVE_FUNCTION) { - callBack = info.argv[INDEX_ONE]; - } else { - storage = info.argv[INDEX_ONE]; - } - } else if (info.argc == ARGC_THREE) { - storage = info.argv[INDEX_ONE]; - callBack = info.argv[INDEX_TWO]; - } - contentStorage_ = static_cast(storage); - AsyncTask::CompleteCallback complete = - [this, contextUrl](NativeEngine& engine, AsyncTask& task, int32_t status) { - auto win = windowScene_->GetMainWindow(); - if (win == nullptr) { - task.Reject(engine, - CreateJsError(engine, static_cast(Rosen::WMError::WM_ERROR_NULLPTR), - "JsWindowStage::OnLoadContent failed.")); - } - Rosen::WMError ret = win->SetUIContent(contextUrl, &engine, - static_cast(contentStorage_), false); - if (ret == Rosen::WMError::WM_OK) { - task.Resolve(engine, engine.CreateUndefined()); - HILOG_INFO("JsWindowStage::OnLoadContent success"); - } else { - task.Reject(engine, - CreateJsError(engine, static_cast(ret), "JsWindowStage::OnLoadContent failed.")); - } - }; - NativeValue* result = nullptr; - AsyncTask::Schedule( - engine, CreateAsyncTaskWithLastParam(engine, callBack, nullptr, std::move(complete), &result)); - return result; -} - -NativeValue* JsWindowStage::OnGetWindowMode(NativeEngine& engine, NativeCallbackInfo& info) -{ - HILOG_INFO("JsWindowStage::OnGetWindowMode is called"); - AsyncTask::CompleteCallback complete = - [this](NativeEngine& engine, AsyncTask& task, int32_t status) { - auto window = windowScene_->GetMainWindow(); - if (window == nullptr) { - task.Reject(engine, CreateJsError(engine, static_cast(Rosen::WMError::WM_ERROR_NULLPTR), - "JsWindowStage::OnGetWindowMode failed.")); - HILOG_ERROR("JsWindowStage window is nullptr"); - return; - } - Rosen::WindowMode mode = window->GetMode(); - task.Resolve(engine, CreateJsValue(engine, mode)); - HILOG_INFO("JsWindowStage OnGetWindowMode success"); - }; - - NativeValue* lastParam = (info.argc == 0) ? nullptr : info.argv[0]; - NativeValue* result = nullptr; - AsyncTask::Schedule( - engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); - return result; -} - -NativeValue* CreateJsWindowStage(NativeEngine& engine, - std::shared_ptr windowScene) -{ - HILOG_INFO("JsWindowStage::CreateJsWindowStage is called"); - NativeValue* objValue = engine.CreateObject(); - NativeObject* object = AbilityRuntime::ConvertNativeValueTo(objValue); - - std::unique_ptr jsWindowStage = - std::make_unique(windowScene, objValue); - object->SetNativePointer(jsWindowStage.release(), JsWindowStage::Finalizer, nullptr); - - AbilityRuntime::BindNativeFunction(engine, - *object, "setUIContent", JsWindowStage::SetUIContent); - AbilityRuntime::BindNativeFunction(engine, - *object, "loadContent", JsWindowStage::LoadContent); - AbilityRuntime::BindNativeFunction(engine, - *object, "getMainWindow", JsWindowStage::GetMainWindow); - AbilityRuntime::BindNativeFunction(engine, - *object, "getWindowMode", JsWindowStage::GetWindowMode); - AbilityRuntime::BindNativeFunction(engine, *object, "on", JsWindowStage::On); - AbilityRuntime::BindNativeFunction(engine, *object, "off", JsWindowStage::Off); - - return objValue; -} -} // namespace AbilityRuntime -} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/ability_runtime/window_stage_api/@ohos.window_stage.d.ts b/frameworks/kits/ability/native/src/ability_runtime/window_stage_api/@ohos.window_stage.d.ts deleted file mode 100644 index 20c3d44392163da41edfc317e391727cef727d9b..0000000000000000000000000000000000000000 --- a/frameworks/kits/ability/native/src/ability_runtime/window_stage_api/@ohos.window_stage.d.ts +++ /dev/null @@ -1,91 +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 { AsyncCallback, Callback } from './basic'; - -declare namespace windowStage { - - enum WindowStageEventType { - VISIBLE = 1, - FOCUSED, - UNFOCUSED, - INVISIBLE, - } - - /** - * WindowStage - * @devices tv, phone, tablet, wearable, liteWearable. - */ - interface WindowStage { - /** - * Get main window of the stage. - * @since 8 - */ - getMainWindow(): Promise; - /** - * Loads content - * @param path path Path of the page to which the content will be loaded - * @param storage storage The data object shared within the content instance loaded by the window - * @devices tv, phone, tablet, wearable, car - * @since 8 - */ - loadContent(path: string, storage: ContenStorage, callback: AsyncCallback): void; - /** - * Loads content - * @param path path of the page to which the content will be loaded - * @devices tv, phone, tablet, wearable, car - * @since 8 - */ - loadContent(path: string, callback: AsyncCallback): void; - /** - * Loads content - * @param path path of the page to which the content will be loaded - * @devices tv, phone, tablet, wearable, car - * @since 8 - */ - loadContent(path: string, storage?: ContenStorage): Promise; - /** - * get the windowmode of current window - * @devices tv, phone, tablet, wearable, car - * @systemapi - * @since 8 - */ - getWindowMode(callback: AsyncCallback): void; - /** - * get the windowmode of current window - * @devices tv, phone, tablet, wearable, car - * @systemapi - * @since 8 - */ - getWindowMode(): Promise; - /** - * window stage event callback on. - * @since 8 - */ - on(eventType: 'windowStageEvent', callback: Callback): void; - /** - * window stage event callback off. - * @since 8 - */ - off(eventType: 'windowStageEvent', callback: Callback): void; - /** - * window stage event callback off. - * @since 8 - */ - off(eventType: 'windowStageEvent'): void; - } -} - -export default windowStage; diff --git a/frameworks/kits/ability/native/src/ability_thread.cpp b/frameworks/kits/ability/native/src/ability_thread.cpp index f7315491023ea6f02af03db769407ddaed5035b5..2b10f6edcac472e4f5011cb1da9bde758bd6e668 100644 --- a/frameworks/kits/ability/native/src/ability_thread.cpp +++ b/frameworks/kits/ability/native/src/ability_thread.cpp @@ -44,6 +44,7 @@ constexpr static char ACE_FORM_ABILITY_NAME[] = "AceFormAbility"; constexpr static char BASE_SERVICE_EXTENSION[] = "ServiceExtension"; constexpr static char FORM_EXTENSION[] = "FormExtension"; constexpr static char STATIC_SUBSCRIBER_EXTENSION[] = "StaticSubscriberExtension"; +constexpr static char DATA_SHARE_EXT_ABILITY[] = "DataShareExtAbility"; /** * @brief Default constructor used to create a AbilityThread instance. @@ -110,6 +111,9 @@ std::string AbilityThread::CreateAbilityName(const std::shared_ptrextensionAbilityType == ExtensionAbilityType::STATICSUBSCRIBER) { abilityName = STATIC_SUBSCRIBER_EXTENSION; } + if (abilityInfo->extensionAbilityType == ExtensionAbilityType::DATASHARE) { + abilityName = DATA_SHARE_EXT_ABILITY; + } APP_LOGI("CreateAbilityName extension type, abilityName:%{public}s", abilityName.c_str()); } else { abilityName = abilityInfo->name; diff --git a/frameworks/kits/ability/native/src/ability_window.cpp b/frameworks/kits/ability/native/src/ability_window.cpp index 25c1427e12a727c6e7f18b19feb7e9dd9a06ce3e..1f0894b6643ab4a4ed138ec1895cfdd38d8bcb53 100644 --- a/frameworks/kits/ability/native/src/ability_window.cpp +++ b/frameworks/kits/ability/native/src/ability_window.cpp @@ -143,7 +143,7 @@ void AbilityWindow::OnPostAbilityInactive() * @brief Called when this ability is background. * */ -void AbilityWindow::OnPostAbilityBackground() +void AbilityWindow::OnPostAbilityBackground(uint32_t sceneFlag) { APP_LOGI("AbilityWindow::OnPostAbilityBackground called."); if (!isWindowAttached) { @@ -152,8 +152,8 @@ void AbilityWindow::OnPostAbilityBackground() } if (windowScene_) { - APP_LOGI("%{public}s begin windowScene_->GoBackground.", __func__); - windowScene_->GoBackground(); + APP_LOGI("%{public}s begin windowScene_->GoBackground, sceneFlag:%{public}d.", __func__, sceneFlag); + windowScene_->GoBackground(sceneFlag); APP_LOGI("%{public}s end windowScene_->GoBackground.", __func__); } @@ -164,7 +164,7 @@ void AbilityWindow::OnPostAbilityBackground() * @brief Called when this ability is foreground. * */ -void AbilityWindow::OnPostAbilityForeground() +void AbilityWindow::OnPostAbilityForeground(uint32_t sceneFlag) { APP_LOGI("AbilityWindow::OnPostAbilityForeground called."); if (!isWindowAttached) { @@ -173,8 +173,8 @@ void AbilityWindow::OnPostAbilityForeground() } if (windowScene_) { - APP_LOGI("%{public}s begin windowScene_->GoForeground.", __func__); - windowScene_->GoForeground(); + APP_LOGI("%{public}s begin windowScene_->GoForeground, sceneFlag:%{public}d.", __func__, sceneFlag); + windowScene_->GoForeground(sceneFlag); APP_LOGI("%{public}s end windowScene_->GoForeground.", __func__); } diff --git a/frameworks/kits/ability/native/src/data_ability_helper.cpp b/frameworks/kits/ability/native/src/data_ability_helper.cpp index 4d1d99882b857148c1b67a65a9eb664852e4183b..7b1bf5fc64695d39a62a211c15b99127db8b17b8 100644 --- a/frameworks/kits/ability/native/src/data_ability_helper.cpp +++ b/frameworks/kits/ability/native/src/data_ability_helper.cpp @@ -43,6 +43,17 @@ DataAbilityHelper::DataAbilityHelper(const std::shared_ptr &context, co APP_LOGI("DataAbilityHelper::DataAbilityHelper end"); } +DataAbilityHelper::DataAbilityHelper(const std::shared_ptr &context, + const std::shared_ptr &uri, const sptr &dataAbilityProxy, bool tryBind) +{ + APP_LOGI("DataAbilityHelper::DataAbilityHelper start"); + token_ = context->GetToken(); + uri_ = uri; + tryBind_ = tryBind; + dataAbilityProxy_ = dataAbilityProxy; + APP_LOGI("DataAbilityHelper::DataAbilityHelper end"); +} + DataAbilityHelper::DataAbilityHelper(const std::shared_ptr &context) { APP_LOGI("DataAbilityHelper::DataAbilityHelper only with context start"); @@ -143,6 +154,21 @@ std::shared_ptr DataAbilityHelper::Creator( return DataAbilityHelper::Creator(context, uri, false); } +/** + * @brief Creates a DataAbilityHelper instance with the Uri specified based on the given Context. + * + * @param context Indicates the Context object on OHOS. + * @param uri Indicates the database table or disk file to operate. + * + * @return Returns the created DataAbilityHelper instance with a specified Uri. + */ +std::shared_ptr DataAbilityHelper::Creator( + const std::shared_ptr &context, const std::shared_ptr &uri) +{ + APP_LOGI("DataAbilityHelper::Creator with context uri called."); + return DataAbilityHelper::Creator(context, uri, false); +} + /** * @brief You can use this method to specify the Uri of the data to operate and set the binding relationship * between the ability using the Data template (Data ability for short) and the associated client process in @@ -196,6 +222,59 @@ std::shared_ptr DataAbilityHelper::Creator( return std::shared_ptr(ptrDataAbilityHelper); } +/** + * @brief You can use this method to specify the Uri of the data to operate and set the binding relationship + * between the ability using the Data template (Data ability for short) and the associated client process in + * a DataAbilityHelper instance. + * + * @param context Indicates the Context object on OHOS. + * @param uri Indicates the database table or disk file to operate. + * @param tryBind Specifies whether the exit of the corresponding Data ability process causes the exit of the + * client process. + * + * @return Returns the created DataAbilityHelper instance. + */ +std::shared_ptr DataAbilityHelper::Creator( + const std::shared_ptr &context, const std::shared_ptr &uri, const bool tryBind) +{ + APP_LOGI("DataAbilityHelper::Creator with context uri tryBind called start."); + if (context == nullptr) { + APP_LOGE("DataAbilityHelper::Creator (context, uri, tryBind) failed, context == nullptr"); + return nullptr; + } + + if (uri == nullptr) { + APP_LOGE("DataAbilityHelper::Creator (context, uri, tryBind) failed, uri == nullptr"); + return nullptr; + } + + if (uri->GetScheme() != SchemeOhos) { + APP_LOGE("DataAbilityHelper::Creator (context, uri, tryBind) failed, the Scheme is not dataability, Scheme: " + "%{public}s", + uri->GetScheme().c_str()); + return nullptr; + } + + APP_LOGI("DataAbilityHelper::Creator before AcquireDataAbility."); + sptr dataAbilityProxy = + AbilityManagerClient::GetInstance()->AcquireDataAbility(*uri.get(), tryBind, context->GetToken()); + if (dataAbilityProxy == nullptr) { + APP_LOGE("DataAbilityHelper::Creator failed get dataAbilityProxy"); + return nullptr; + } + APP_LOGI("DataAbilityHelper::Creator after AcquireDataAbility."); + + DataAbilityHelper *ptrDataAbilityHelper = + new (std::nothrow) DataAbilityHelper(context, uri, dataAbilityProxy, tryBind); + if (ptrDataAbilityHelper == nullptr) { + APP_LOGE("DataAbilityHelper::Creator (context, uri, tryBind) failed, create DataAbilityHelper failed"); + return nullptr; + } + + APP_LOGI("DataAbilityHelper::Creator with context uri tryBind called end."); + return std::shared_ptr(ptrDataAbilityHelper); +} + /** * @brief Creates a DataAbilityHelper instance without specifying the Uri based. * diff --git a/frameworks/kits/ability/native/src/datashare_connection.cpp b/frameworks/kits/ability/native/src/datashare_connection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2ebbef40d087e5e4ca3b21477f7e46c789a43eea --- /dev/null +++ b/frameworks/kits/ability/native/src/datashare_connection.cpp @@ -0,0 +1,123 @@ +/* + * 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 + * + * 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 "datashare_connection.h" + +#include "ability_manager_client.h" +#include "app_log_wrapper.h" +#include "datashare_proxy.h" + +namespace OHOS { +namespace AppExecFwk { +sptr DataShareConnection::instance_ = nullptr; +std::mutex DataShareConnection::mutex_; + +/** + * @brief get singleton of Class DataShareConnection + * + * @return The singleton of DataShareConnection + */ +sptr DataShareConnection::GetInstance() +{ + if (instance_ == nullptr) { + std::lock_guard lock(mutex_); + if (instance_ == nullptr) { + instance_ = sptr(new (std::nothrow) DataShareConnection()); + } + } + return instance_; +} + +/** + * @brief This method is called back to receive the connection result after an ability calls the + * ConnectAbility method to connect it to a extension ability. + * + * @param element: Indicates information about the connected extension ability. + * @param remote: Indicates the remote proxy object of the extension ability. + * @param resultCode: Indicates the connection result code. The value 0 indicates a successful connection, and any + * other value indicates a connection failure. + */ +void DataShareConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called begin", __func__); + if (remoteObject == nullptr) { + APP_LOGE("DataShareConnection::OnAbilityConnectDone failed, remote is nullptr"); + return; + } + dataShareProxy_ = iface_cast(remoteObject); + if (dataShareProxy_ == nullptr) { + APP_LOGE("DataShareConnection::OnAbilityConnectDone failed, dataShareProxy_ is nullptr"); + return; + } + isConnected_.store(true); + APP_LOGI("%{public}s called end", __func__); +} + +/** + * @brief This method is called back to receive the disconnection result after the connected extension ability crashes + * or is killed. If the extension ability exits unexpectedly, all its connections are disconnected, and each ability + * previously connected to it will call onAbilityDisconnectDone. + * + * @param element: Indicates information about the disconnected extension ability. + * @param resultCode: Indicates the disconnection result code. The value 0 indicates a successful disconnection, and + * any other value indicates a disconnection failure. + */ +void DataShareConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) +{ + APP_LOGI("%{public}s called begin", __func__); + dataShareProxy_ = nullptr; + isConnected_.store(false); + APP_LOGI("%{public}s called end", __func__); +} + +/** + * @brief connect remote ability of DataShareExtAbility. + */ +void DataShareConnection::ConnectDataShareExtAbility(const AAFwk::Want &want, const sptr &token) +{ + APP_LOGI("%{public}s called begin", __func__); + ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(want, this, token); + APP_LOGI("%{public}s called end, ret=%{public}d", __func__, ret); +} + +/** + * @brief disconnect remote ability of DataShareExtAbility. + */ +void DataShareConnection::DisconnectDataShareExtAbility() +{ + APP_LOGI("%{public}s called begin", __func__); + dataShareProxy_ = nullptr; + isConnected_.store(false); + ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(this); + APP_LOGI("%{public}s called end, ret=%{public}d", __func__, ret); +} + +/** + * @brief check whether connected to remote extension ability. + * + * @return bool true if connected, otherwise false. + */ +bool DataShareConnection::IsExtAbilityConnected() +{ + return isConnected_.load(); +} + +sptr DataShareConnection::GetDataShareProxy() +{ + return dataShareProxy_; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/datashare_ext_ability.cpp b/frameworks/kits/ability/native/src/datashare_ext_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ff998c9d7beb8c60c199f3d9bcc222d47a023409 --- /dev/null +++ b/frameworks/kits/ability/native/src/datashare_ext_ability.cpp @@ -0,0 +1,187 @@ +/* + * 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 + * + * 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 "datashare_ext_ability.h" + +#include "ability_loader.h" +#include "connection_manager.h" +#include "hilog_wrapper.h" +#include "js_datashare_ext_ability.h" +#include "runtime.h" +#include "datashare_ext_ability_context.h" + +namespace OHOS { +namespace AbilityRuntime { +using namespace OHOS::AppExecFwk; +DataShareExtAbility* DataShareExtAbility::Create(const std::unique_ptr& runtime) +{ + if (!runtime) { + return new DataShareExtAbility(); + } + HILOG_INFO("DataShareExtAbility::Create runtime"); + switch (runtime->GetLanguage()) { + case Runtime::Language::JS: + return JsDataShareExtAbility::Create(runtime); + + default: + return new DataShareExtAbility(); + } +} + +void DataShareExtAbility::Init(const std::shared_ptr &record, + const std::shared_ptr &application, + std::shared_ptr &handler, + const sptr &token) +{ + ExtensionBase::Init(record, application, handler, token); + HILOG_INFO("DataShareExtAbility begin init context"); +} + +std::shared_ptr DataShareExtAbility::CreateAndInitContext( + const std::shared_ptr &record, + const std::shared_ptr &application, + std::shared_ptr &handler, + const sptr &token) +{ + std::shared_ptr context = + ExtensionBase::CreateAndInitContext(record, application, handler, token); + if (record == nullptr) { + HILOG_ERROR("DataShareExtAbility::CreateAndInitContext record is nullptr"); + return context; + } + + auto abilityInfo = record->GetAbilityInfo(); + context->SetAbilityInfo(abilityInfo); + context->InitHapModuleInfo(abilityInfo); + auto appContext = Context::GetApplicationContext(); + context->SetApplicationInfo(appContext->GetApplicationInfo()); + context->SetResourceManager(appContext->GetResourceManager()); + return context; +} + +std::vector DataShareExtAbility::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) +{ + HILOG_INFO("%{public}s begin.", __func__); + std::vector ret; + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +int DataShareExtAbility::OpenFile(const Uri &uri, const std::string &mode) +{ + HILOG_INFO("%{public}s begin.", __func__); + HILOG_INFO("%{public}s end.", __func__); + return 0; +} + +int DataShareExtAbility::OpenRawFile(const Uri &uri, const std::string &mode) +{ + HILOG_INFO("%{public}s begin.", __func__); + HILOG_INFO("%{public}s end.", __func__); + return 0; +} + +int DataShareExtAbility::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) +{ + HILOG_INFO("%{public}s begin.", __func__); + HILOG_INFO("%{public}s end.", __func__); + return 0; +} + +int DataShareExtAbility::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, + const NativeRdb::DataAbilityPredicates &predicates) +{ + HILOG_INFO("%{public}s begin.", __func__); + HILOG_INFO("%{public}s end.", __func__); + return 0; +} + +int DataShareExtAbility::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) +{ + HILOG_INFO("%{public}s begin.", __func__); + HILOG_INFO("%{public}s end.", __func__); + return 0; +} + +std::shared_ptr DataShareExtAbility::Query(const Uri &uri, + std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) +{ + HILOG_INFO("%{public}s begin.", __func__); + std::shared_ptr ret; + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +std::string DataShareExtAbility::GetType(const Uri &uri) +{ + HILOG_INFO("%{public}s begin.", __func__); + HILOG_INFO("%{public}s end.", __func__); + return ""; +} + +int DataShareExtAbility::BatchInsert(const Uri &uri, const std::vector &values) +{ + HILOG_INFO("%{public}s begin.", __func__); + HILOG_INFO("%{public}s end.", __func__); + return 0; +} + +bool DataShareExtAbility::RegisterObserver(const Uri &uri, const sptr &dataObserver) +{ + HILOG_INFO("%{public}s begin.", __func__); + HILOG_INFO("%{public}s end.", __func__); + return true; +} + +bool DataShareExtAbility::UnregisterObserver(const Uri &uri, const sptr &dataObserver) +{ + HILOG_INFO("%{public}s begin.", __func__); + HILOG_INFO("%{public}s end.", __func__); + return true; +} + +bool DataShareExtAbility::NotifyChange(const Uri &uri) +{ + HILOG_INFO("%{public}s begin.", __func__); + HILOG_INFO("%{public}s end.", __func__); + return true; +} + +Uri DataShareExtAbility::NormalizeUri(const Uri &uri) +{ + HILOG_INFO("%{public}s begin.", __func__); + Uri urivalue(""); + HILOG_INFO("%{public}s end.", __func__); + return urivalue; +} + +Uri DataShareExtAbility::DenormalizeUri(const Uri &uri) +{ + HILOG_INFO("%{public}s begin.", __func__); + Uri urivalue(""); + HILOG_INFO("%{public}s end.", __func__); + return urivalue; +} + +std::vector> DataShareExtAbility::ExecuteBatch( + const std::vector> &operations) +{ + HILOG_INFO("%{public}s begin.", __func__); + std::vector> results; + HILOG_INFO("%{public}s end.", __func__); + return results; +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/datashare_ext_ability_module_loader.cpp b/frameworks/kits/ability/native/src/datashare_ext_ability_module_loader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..044aec9b2252e5068058f20475457ac087f57067 --- /dev/null +++ b/frameworks/kits/ability/native/src/datashare_ext_ability_module_loader.cpp @@ -0,0 +1,32 @@ +/* + * 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 + * + * 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 "datashare_ext_ability_module_loader.h" +#include "datashare_ext_ability.h" + +namespace OHOS::AbilityRuntime { +DataShareExtAbilityModuleLoader::DataShareExtAbilityModuleLoader() = default; +DataShareExtAbilityModuleLoader::~DataShareExtAbilityModuleLoader() = default; + +Extension *DataShareExtAbilityModuleLoader::Create(const std::unique_ptr& runtime) const +{ + return DataShareExtAbility::Create(runtime); +} + +extern "C" __attribute__((visibility("default"))) void* OHOS_EXTENSION_GetExtensionModule() +{ + return &DataShareExtAbilityModuleLoader::GetInstance(); +} +} // namespace OHOS::AbilityRuntime \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/datashare_helper.cpp b/frameworks/kits/ability/native/src/datashare_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..db011ced34f4b0abab034ba8c220b3f4672e2258 --- /dev/null +++ b/frameworks/kits/ability/native/src/datashare_helper.cpp @@ -0,0 +1,1098 @@ +/* + * 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 + * + * 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 "datashare_helper.h" + +#include "ability_scheduler_interface.h" +#include "ability_thread.h" +#include "abs_shared_result_set.h" +#include "app_log_wrapper.h" +#include "data_ability_observer_interface.h" +#include "data_ability_operation.h" +#include "data_ability_predicates.h" +#include "data_ability_result.h" +#include "idatashare.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const std::string SCHEME_DATASHARE = "datashare"; +} // namespace + +std::mutex DataShareHelper::oplock_; +DataShareHelper::DataShareHelper(const std::shared_ptr &context, + const AAFwk::Want &want) +{ + APP_LOGI("DataShareHelper::DataShareHelper with context and want start"); + token_ = context->GetToken(); + want_ = want; + uri_ = nullptr; + dataShareProxy_ = nullptr; + dataShareConnection_ = DataShareConnection::GetInstance(); + APP_LOGI("DataShareHelper::DataShareHelper with context and want end"); +} + +DataShareHelper::DataShareHelper(const std::shared_ptr &context, const AAFwk::Want &want, + const std::shared_ptr &uri, const sptr &dataShareProxy) +{ + APP_LOGI("DataShareHelper::DataShareHelper start"); + token_ = context->GetToken(); + context_ = std::shared_ptr(context); + want_ = want; + uri_ = uri; + dataShareProxy_ = dataShareProxy; + dataShareConnection_ = DataShareConnection::GetInstance(); + APP_LOGI("DataShareHelper::DataShareHelper end"); +} + +DataShareHelper::DataShareHelper(const std::shared_ptr &context, + const AAFwk::Want &want, const std::shared_ptr &uri, const sptr &dataShareProxy) +{ + APP_LOGI("DataShareHelper::DataShareHelper start"); + token_ = context->GetToken(); + want_ = want; + uri_ = uri; + dataShareProxy_ = dataShareProxy; + dataShareConnection_ = DataShareConnection::GetInstance(); + APP_LOGI("DataShareHelper::DataShareHelper end"); +} + +void DataShareHelper::AddDataShareDeathRecipient(const sptr &token) +{ + APP_LOGI("DataShareHelper::AddDataShareDeathRecipient start."); + if (token != nullptr && callerDeathRecipient_ != nullptr) { + APP_LOGI("token RemoveDeathRecipient."); + token->RemoveDeathRecipient(callerDeathRecipient_); + } + if (callerDeathRecipient_ == nullptr) { + callerDeathRecipient_ = + new DataShareDeathRecipient(std::bind(&DataShareHelper::OnSchedulerDied, this, std::placeholders::_1)); + } + if (token != nullptr) { + APP_LOGI("token AddDeathRecipient."); + token->AddDeathRecipient(callerDeathRecipient_); + } + APP_LOGI("DataShareHelper::AddDataShareDeathRecipient end."); +} + +void DataShareHelper::OnSchedulerDied(const wptr &remote) +{ + APP_LOGI("'%{public}s start':", __func__); + std::lock_guard guard(lock_); + auto object = remote.promote(); + object = nullptr; + dataShareProxy_ = nullptr; + uri_ = nullptr; + APP_LOGI("DataShareHelper::OnSchedulerDied end."); +} + +/** + * @brief Creates a DataShareHelper instance without specifying the Uri based on the given Context. + * + * @param context Indicates the Context object on OHOS. + * @param want Indicates the Want containing information about the target extension ability to connect. + * + * @return Returns the created DataShareHelper instance where Uri is not specified. + */ +std::shared_ptr DataShareHelper::Creator( + const std::shared_ptr &context, const AAFwk::Want &want) +{ + APP_LOGI("DataShareHelper::Creator with context start."); + if (context == nullptr) { + APP_LOGE("DataShareHelper::Creator (context) failed, context == nullptr"); + return nullptr; + } + + APP_LOGI("DataShareHelper::Creator before ConnectDataShareExtAbility."); + sptr dataShareConnection = DataShareConnection::GetInstance(); + if (!dataShareConnection->IsExtAbilityConnected()) { + dataShareConnection->ConnectDataShareExtAbility(want, context->GetToken()); + } + APP_LOGI("DataShareHelper::Creator after ConnectDataShareExtAbility."); + + DataShareHelper *ptrDataShareHelper = new (std::nothrow) DataShareHelper(context, want); + if (ptrDataShareHelper == nullptr) { + APP_LOGE("DataShareHelper::Creator (context) failed, create DataShareHelper failed"); + return nullptr; + } + + APP_LOGI("DataShareHelper::Creator with context end."); + return std::shared_ptr(ptrDataShareHelper); +} + +/** + * @brief You can use this method to specify the Uri of the data to operate and set the binding relationship + * between the ability using the Data template (data share for short) and the associated client process in + * a DataShareHelper instance. + * + * @param context Indicates the Context object on OHOS. + * @param want Indicates the Want containing information about the target extension ability to connect. + * @param uri Indicates the database table or disk file to operate. + * + * @return Returns the created DataShareHelper instance. + */ +std::shared_ptr DataShareHelper::Creator( + const std::shared_ptr &context, const AAFwk::Want &want, const std::shared_ptr &uri) +{ + APP_LOGI("DataShareHelper::Creator with context uri called start."); + if (context == nullptr) { + APP_LOGE("DataShareHelper::Creator (context, uri) failed, context == nullptr"); + return nullptr; + } + + if (uri == nullptr) { + APP_LOGE("DataShareHelper::Creator (context, uri) failed, uri == nullptr"); + return nullptr; + } + + if (uri->GetScheme() != SCHEME_DATASHARE) { + APP_LOGE("DataShareHelper::Creator (context, uri) failed, the Scheme is not datashare, Scheme: %{public}s", + uri->GetScheme().c_str()); + return nullptr; + } + + APP_LOGI("DataShareHelper::Creator before ConnectDataShareExtAbility."); + sptr dataShareProxy = nullptr; + + sptr dataShareConnection = DataShareConnection::GetInstance(); + if (!dataShareConnection->IsExtAbilityConnected()) { + dataShareConnection->ConnectDataShareExtAbility(want, context->GetToken()); + } + dataShareProxy = dataShareConnection->GetDataShareProxy(); + if (dataShareProxy == nullptr) { + APP_LOGW("DataShareHelper::Creator get invalid dataShareProxy"); + } + APP_LOGI("DataShareHelper::Creator after ConnectDataShareExtAbility."); + + DataShareHelper *ptrDataShareHelper = new (std::nothrow) DataShareHelper(context, want, uri, dataShareProxy); + if (ptrDataShareHelper == nullptr) { + APP_LOGE("DataShareHelper::Creator (context, uri) failed, create DataShareHelper failed"); + return nullptr; + } + + APP_LOGI("DataShareHelper::Creator with context uri called end."); + return std::shared_ptr(ptrDataShareHelper); +} + +/** + * @brief You can use this method to specify the Uri of the data to operate and set the binding relationship + * between the ability using the Data template (data share for short) and the associated client process in + * a DataShareHelper instance. + * + * @param context Indicates the Context object on OHOS. + * @param want Indicates the Want containing information about the target extension ability to connect. + * @param uri Indicates the database table or disk file to operate. + * + * @return Returns the created DataShareHelper instance. + */ +std::shared_ptr DataShareHelper::Creator( + const std::shared_ptr &context, const AAFwk::Want &want, + const std::shared_ptr &uri) +{ + APP_LOGI("DataShareHelper::Creator with context uri called start."); + if (context == nullptr) { + APP_LOGE("DataShareHelper::Creator (context, uri) failed, context == nullptr"); + return nullptr; + } + + if (uri == nullptr) { + APP_LOGE("DataShareHelper::Creator (context, uri) failed, uri == nullptr"); + return nullptr; + } + + if (uri->GetScheme() != SCHEME_DATASHARE) { + APP_LOGE("DataShareHelper::Creator (context, uri) failed, the Scheme is not datashare, Scheme: %{public}s", + uri->GetScheme().c_str()); + return nullptr; + } + + APP_LOGI("DataShareHelper::Creator before ConnectDataShareExtAbility."); + sptr dataShareProxy = nullptr; + + sptr dataShareConnection = DataShareConnection::GetInstance(); + if (!dataShareConnection->IsExtAbilityConnected()) { + dataShareConnection->ConnectDataShareExtAbility(want, context->GetToken()); + } + dataShareProxy = dataShareConnection->GetDataShareProxy(); + if (dataShareProxy == nullptr) { + APP_LOGW("DataShareHelper::Creator get invalid dataShareProxy"); + } + APP_LOGI("DataShareHelper::Creator after ConnectDataShareExtAbility."); + + DataShareHelper *ptrDataShareHelper = new (std::nothrow) DataShareHelper(context, want, uri, dataShareProxy); + if (ptrDataShareHelper == nullptr) { + APP_LOGE("DataShareHelper::Creator (context, uri) failed, create DataShareHelper failed"); + return nullptr; + } + + APP_LOGI("DataShareHelper::Creator with context uri called end."); + return std::shared_ptr(ptrDataShareHelper); +} + +/** + * @brief Releases the client resource of the data share. + * You should call this method to releases client resource after the data operations are complete. + * + * @return Returns true if the resource is successfully released; returns false otherwise. + */ +bool DataShareHelper::Release() +{ + APP_LOGI("DataShareHelper::Release start."); + std::lock_guard guard(lock_); + if (uri_ == nullptr) { + APP_LOGE("DataShareHelper::Release failed, uri_ is nullptr"); + return false; + } + + APP_LOGI("DataShareHelper::Release before DisconnectDataShareExtAbility."); + if (dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->DisconnectDataShareExtAbility(); + } + APP_LOGI("DataShareHelper::Release after DisconnectDataShareExtAbility."); + dataShareProxy_ = nullptr; + uri_.reset(); + APP_LOGI("DataShareHelper::Release end."); + return true; +} + +/** + * @brief Obtains the MIME types of files supported. + * + * @param uri Indicates the path of the files to obtain. + * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. + * + * @return Returns the matched MIME types. If there is no match, null is returned. + */ +std::vector DataShareHelper::GetFileTypes(Uri &uri, const std::string &mimeTypeFilter) +{ + APP_LOGI("DataShareHelper::GetFileTypes start."); + std::lock_guard guard(lock_); + std::vector matchedMIMEs; + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return matchedMIMEs; + } + + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::GetFileTypes before ConnectDataShareExtAbility."); + if (!dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->ConnectDataShareExtAbility(want_, token_); + } + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); + APP_LOGI("DataShareHelper::GetFileTypes after ConnectDataShareExtAbility."); + if (isSystemCaller_ && dataShareProxy_) { + AddDataShareDeathRecipient(dataShareProxy_->AsObject()); + } + } + + if (dataShareProxy_ == nullptr) { + APP_LOGE("%{public}s failed with invalid dataShareProxy_", __func__); + return matchedMIMEs; + } + + APP_LOGI("DataShareHelper::GetFileTypes before dataShareProxy_->GetFileTypes."); + matchedMIMEs = dataShareProxy_->GetFileTypes(uri, mimeTypeFilter); + APP_LOGI("DataShareHelper::GetFileTypes after dataShareProxy_->GetFileTypes."); + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::GetFileTypes before DisconnectDataShareExtAbility."); + if (dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->DisconnectDataShareExtAbility(); + } + APP_LOGI("DataShareHelper::GetFileTypes after DisconnectDataShareExtAbility."); + dataShareProxy_ = nullptr; + } + + APP_LOGI("DataShareHelper::GetFileTypes end."); + return matchedMIMEs; +} + +/** + * @brief Opens a file in a specified remote path. + * + * @param uri Indicates the path of the file to open. + * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access + * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, + * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data, + * or "rwt" for read and write access that truncates any existing file. + * + * @return Returns the file descriptor. + */ +int DataShareHelper::OpenFile(Uri &uri, const std::string &mode) +{ + APP_LOGI("DataShareHelper::OpenFile start."); + std::lock_guard guard(lock_); + int fd = -1; + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return fd; + } + + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::OpenFile before ConnectDataShareExtAbility."); + if (!dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->ConnectDataShareExtAbility(want_, token_); + } + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); + APP_LOGI("DataShareHelper::OpenFile after ConnectDataShareExtAbility."); + if (isSystemCaller_ && dataShareProxy_) { + AddDataShareDeathRecipient(dataShareProxy_->AsObject()); + } + } + + if (dataShareProxy_ == nullptr) { + APP_LOGE("%{public}s failed with invalid dataShareProxy_", __func__); + return fd; + } + + APP_LOGI("DataShareHelper::OpenFile before dataShareProxy_->OpenFile."); + fd = dataShareProxy_->OpenFile(uri, mode); + APP_LOGI("DataShareHelper::OpenFile after dataShareProxy_->OpenFile."); + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::OpenFile before DisconnectDataShareExtAbility."); + if (dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->DisconnectDataShareExtAbility(); + } + APP_LOGI("DataShareHelper::OpenFile after DisconnectDataShareExtAbility."); + dataShareProxy_ = nullptr; + } + APP_LOGI("DataShareHelper::OpenFile end."); + return fd; +} + +/** + * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets + * inside of their .hap. + * + * @param uri Indicates the path of the file to open. + * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access + * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, + * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing + * data, or "rwt" for read and write access that truncates any existing file. + * + * @return Returns the RawFileDescriptor object containing file descriptor. + */ +int DataShareHelper::OpenRawFile(Uri &uri, const std::string &mode) +{ + APP_LOGI("DataShareHelper::OpenRawFile start."); + std::lock_guard guard(lock_); + int fd = -1; + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return fd; + } + + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::OpenRawFile before ConnectDataShareExtAbility."); + if (!dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->ConnectDataShareExtAbility(want_, token_); + } + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); + APP_LOGI("DataShareHelper::OpenRawFile after ConnectDataShareExtAbility."); + if (isSystemCaller_ && dataShareProxy_) { + AddDataShareDeathRecipient(dataShareProxy_->AsObject()); + } + } + + if (dataShareProxy_ == nullptr) { + APP_LOGE("%{public}s failed with invalid dataShareProxy_", __func__); + return fd; + } + + APP_LOGI("DataShareHelper::OpenRawFile before dataShareProxy_->OpenRawFile."); + fd = dataShareProxy_->OpenRawFile(uri, mode); + APP_LOGI("DataShareHelper::OpenRawFile after dataShareProxy_->OpenRawFile."); + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::OpenRawFile before DisconnectDataShareExtAbility."); + if (dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->DisconnectDataShareExtAbility(); + } + APP_LOGI("DataShareHelper::OpenRawFile after DisconnectDataShareExtAbility."); + dataShareProxy_ = nullptr; + } + APP_LOGI("DataShareHelper::OpenRawFile end."); + return fd; +} + +/** + * @brief Inserts a single data record into the database. + * + * @param uri Indicates the path of the data to operate. + * @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted. + * + * @return Returns the index of the inserted data record. + */ +int DataShareHelper::Insert(Uri &uri, const NativeRdb::ValuesBucket &value) +{ + APP_LOGI("DataShareHelper::Insert start."); + std::lock_guard guard(lock_); + int index = -1; + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return index; + } + + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::Insert before ConnectDataShareExtAbility."); + if (!dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->ConnectDataShareExtAbility(want_, token_); + } + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); + APP_LOGI("DataShareHelper::Insert after ConnectDataShareExtAbility."); + if (isSystemCaller_ && dataShareProxy_) { + AddDataShareDeathRecipient(dataShareProxy_->AsObject()); + } + } + + if (dataShareProxy_ == nullptr) { + APP_LOGE("%{public}s failed with invalid dataShareProxy_", __func__); + return index; + } + + APP_LOGI("DataShareHelper::Insert before dataShareProxy_->Insert."); + index = dataShareProxy_->Insert(uri, value); + APP_LOGI("DataShareHelper::Insert after dataShareProxy_->Insert."); + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::Insert before DisconnectDataShareExtAbility."); + if (dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->DisconnectDataShareExtAbility(); + } + APP_LOGI("DataShareHelper::Insert after DisconnectDataShareExtAbility."); + dataShareProxy_ = nullptr; + } + APP_LOGI("DataShareHelper::Insert end."); + return index; +} + +/** + * @brief Updates data records in the database. + * + * @param uri Indicates the path of data to update. + * @param value Indicates the data to update. This parameter can be null. + * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. + * + * @return Returns the number of data records updated. + */ +int DataShareHelper::Update( + Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("DataShareHelper::Update start."); + std::lock_guard guard(lock_); + int index = -1; + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return index; + } + + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::Update before ConnectDataShareExtAbility."); + if (!dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->ConnectDataShareExtAbility(want_, token_); + } + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); + APP_LOGI("DataShareHelper::Update after ConnectDataShareExtAbility."); + if (isSystemCaller_ && dataShareProxy_) { + AddDataShareDeathRecipient(dataShareProxy_->AsObject()); + } + } + + if (dataShareProxy_ == nullptr) { + APP_LOGE("%{public}s failed with invalid dataShareProxy_", __func__); + return index; + } + + APP_LOGI("DataShareHelper::Update before dataShareProxy_->Update."); + index = dataShareProxy_->Update(uri, value, predicates); + APP_LOGI("DataShareHelper::Update after dataShareProxy_->Update."); + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::Update before DisconnectDataShareExtAbility."); + if (dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->DisconnectDataShareExtAbility(); + } + APP_LOGI("DataShareHelper::Update after DisconnectDataShareExtAbility."); + dataShareProxy_ = nullptr; + } + APP_LOGI("DataShareHelper::Update end."); + return index; +} + +/** + * @brief Deletes one or more data records from the database. + * + * @param uri Indicates the path of the data to operate. + * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. + * + * @return Returns the number of data records deleted. + */ +int DataShareHelper::Delete(Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("DataShareHelper::Delete start."); + std::lock_guard guard(lock_); + int index = -1; + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return index; + } + + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::Delete before ConnectDataShareExtAbility."); + if (!dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->ConnectDataShareExtAbility(want_, token_); + } + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); + APP_LOGI("DataShareHelper::Delete after ConnectDataShareExtAbility."); + if (isSystemCaller_ && dataShareProxy_) { + AddDataShareDeathRecipient(dataShareProxy_->AsObject()); + } + } + + if (dataShareProxy_ == nullptr) { + APP_LOGE("%{public}s failed with invalid dataShareProxy_", __func__); + return index; + } + + APP_LOGI("DataShareHelper::Delete before dataShareProxy_->Delete."); + index = dataShareProxy_->Delete(uri, predicates); + APP_LOGI("DataShareHelper::Delete after dataShareProxy_->Delete."); + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::Delete before DisconnectDataShareExtAbility."); + if (dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->DisconnectDataShareExtAbility(); + } + APP_LOGI("DataShareHelper::Delete after DisconnectDataShareExtAbility."); + dataShareProxy_ = nullptr; + } + APP_LOGI("DataShareHelper::Delete end."); + return index; +} + +/** + * @brief Deletes one or more data records from the database. + * + * @param uri Indicates the path of data to query. + * @param columns Indicates the columns to query. If this parameter is null, all columns are queried. + * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. + * + * @return Returns the query result. + */ +std::shared_ptr DataShareHelper::Query( + Uri &uri, std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("DataShareHelper::Query start."); + std::lock_guard guard(lock_); + std::shared_ptr resultset = nullptr; + + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return resultset; + } + + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::Query before ConnectDataShareExtAbility."); + if (!dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->ConnectDataShareExtAbility(want_, token_); + } + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); + APP_LOGI("DataShareHelper::Query after ConnectDataShareExtAbility."); + if (isSystemCaller_ && dataShareProxy_) { + AddDataShareDeathRecipient(dataShareProxy_->AsObject()); + } + } + + if (dataShareProxy_ == nullptr) { + APP_LOGE("%{public}s failed with invalid dataShareProxy_", __func__); + return resultset; + } + + APP_LOGI("DataShareHelper::Query before dataShareProxy_->Query."); + resultset = dataShareProxy_->Query(uri, columns, predicates); + APP_LOGI("DataShareHelper::Query after dataShareProxy_->Query."); + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::Query before DisconnectDataShareExtAbility."); + if (dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->DisconnectDataShareExtAbility(); + } + APP_LOGI("DataShareHelper::Query after DisconnectDataShareExtAbility."); + dataShareProxy_ = nullptr; + } + APP_LOGI("DataShareHelper::Query end."); + return resultset; +} + +/** + * @brief Obtains the MIME type matching the data specified by the URI of the data share. This method should be + * implemented by a data share. Data abilities supports general data types, including text, HTML, and JPEG. + * + * @param uri Indicates the URI of the data. + * + * @return Returns the MIME type that matches the data specified by uri. + */ +std::string DataShareHelper::GetType(Uri &uri) +{ + APP_LOGI("DataShareHelper::GetType start."); + std::lock_guard guard(lock_); + std::string type; + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return type; + } + + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::GetType before ConnectDataShareExtAbility."); + if (!dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->ConnectDataShareExtAbility(want_, token_); + } + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); + APP_LOGI("DataShareHelper::GetType after ConnectDataShareExtAbility."); + if (isSystemCaller_ && dataShareProxy_) { + AddDataShareDeathRecipient(dataShareProxy_->AsObject()); + } + } + + if (dataShareProxy_ == nullptr) { + APP_LOGE("%{public}s failed with invalid dataShareProxy_", __func__); + return type; + } + + APP_LOGI("DataShareHelper::GetType before dataShareProxy_->GetType."); + type = dataShareProxy_->GetType(uri); + APP_LOGI("DataShareHelper::GetType after dataShareProxy_->GetType."); + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::GetType before DisconnectDataShareExtAbility."); + if (dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->DisconnectDataShareExtAbility(); + } + APP_LOGI("DataShareHelper::GetType after DisconnectDataShareExtAbility."); + dataShareProxy_ = nullptr; + } + APP_LOGI("DataShareHelper::GetType end."); + return type; +} + +/** + * @brief Inserts multiple data records into the database. + * + * @param uri Indicates the path of the data to operate. + * @param values Indicates the data records to insert. + * + * @return Returns the number of data records inserted. + */ +int DataShareHelper::BatchInsert(Uri &uri, const std::vector &values) +{ + APP_LOGI("DataShareHelper::BatchInsert start."); + std::lock_guard guard(lock_); + int ret = -1; + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return ret; + } + + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::BatchInsert before ConnectDataShareExtAbility."); + if (!dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->ConnectDataShareExtAbility(want_, token_); + } + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); + APP_LOGI("DataShareHelper::BatchInsert after ConnectDataShareExtAbility."); + if (isSystemCaller_ && dataShareProxy_) { + AddDataShareDeathRecipient(dataShareProxy_->AsObject()); + } + } + + if (dataShareProxy_ == nullptr) { + APP_LOGE("%{public}s failed with invalid dataShareProxy_", __func__); + return ret; + } + + APP_LOGI("DataShareHelper::BatchInsert before dataShareProxy_->BatchInsert."); + ret = dataShareProxy_->BatchInsert(uri, values); + APP_LOGI("DataShareHelper::BatchInsert after dataShareProxy_->BatchInsert."); + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::BatchInsert before DisconnectDataShareExtAbility."); + if (dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->DisconnectDataShareExtAbility(); + } + APP_LOGI("DataShareHelper::BatchInsert after DisconnectDataShareExtAbility."); + dataShareProxy_ = nullptr; + } + APP_LOGI("DataShareHelper::BatchInsert end."); + return ret; +} + +bool DataShareHelper::CheckUriParam(const Uri &uri) +{ + APP_LOGI("DataShareHelper::CheckUriParam start."); + Uri checkUri(uri.ToString()); + if (!CheckOhosUri(checkUri)) { + APP_LOGE("DataShareHelper::CheckUriParam failed. CheckOhosUri uri failed"); + return false; + } + + if (uri_ != nullptr) { + if (!CheckOhosUri(*uri_)) { + APP_LOGE("DataShareHelper::CheckUriParam failed. CheckOhosUri uri_ failed"); + return false; + } + + std::vector checkSegments; + checkUri.GetPathSegments(checkSegments); + + std::vector segments; + uri_->GetPathSegments(segments); + + if (checkSegments[0] != segments[0]) { + APP_LOGE("DataShareHelper::CheckUriParam failed. the datashare in uri doesn't equal the one in uri_."); + return false; + } + } + APP_LOGI("DataShareHelper::CheckUriParam end."); + return true; +} + +bool DataShareHelper::CheckOhosUri(const Uri &uri) +{ + APP_LOGI("DataShareHelper::CheckOhosUri start."); + Uri checkUri(uri.ToString()); + if (checkUri.GetScheme() != SCHEME_DATASHARE) { + APP_LOGE("DataShareHelper::CheckOhosUri failed. uri is not a datashare one."); + return false; + } + + std::vector segments; + checkUri.GetPathSegments(segments); + if (segments.empty()) { + APP_LOGE("DataShareHelper::CheckOhosUri failed. There is no segments in the uri."); + return false; + } + + if (checkUri.GetPath() == "") { + APP_LOGE("DataShareHelper::CheckOhosUri failed. The path in the uri is empty."); + return false; + } + APP_LOGI("DataShareHelper::CheckOhosUri end."); + return true; +} + +/** + * @brief Registers an observer to DataObsMgr specified by the given Uri. + * + * @param uri, Indicates the path of the data to operate. + * @param dataObserver, Indicates the IDataAbilityObserver object. + */ +void DataShareHelper::RegisterObserver(const Uri &uri, const sptr &dataObserver) +{ + APP_LOGI("DataShareHelper::RegisterObserver start."); + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return; + } + + if (dataObserver == nullptr) { + APP_LOGE("%{public}s called. dataObserver is nullptr", __func__); + return; + } + + Uri tmpUri(uri.ToString()); + std::lock_guard lock_l(oplock_); + sptr dataShareProxy = nullptr; + if (uri_ == nullptr) { + auto datashare = registerMap_.find(dataObserver); + if (datashare == registerMap_.end()) { + if (!dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->ConnectDataShareExtAbility(want_, token_); + } + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); + registerMap_.emplace(dataObserver, dataShareProxy); + uriMap_.emplace(dataObserver, tmpUri.GetPath()); + } else { + auto path = uriMap_.find(dataObserver); + if (path->second != tmpUri.GetPath()) { + APP_LOGE("DataShareHelper::RegisterObserver failed input uri's path is not equal the one the " + "observer used"); + return; + } + dataShareProxy = datashare->second; + } + } else { + dataShareProxy = dataShareProxy_; + } + + if (dataShareProxy == nullptr) { + APP_LOGE("DataShareHelper::RegisterObserver failed dataShareProxy == nullptr"); + registerMap_.erase(dataObserver); + uriMap_.erase(dataObserver); + return; + } + dataShareProxy->RegisterObserver(uri, dataObserver); + APP_LOGI("DataShareHelper::RegisterObserver end."); +} + +/** + * @brief Deregisters an observer used for DataObsMgr specified by the given Uri. + * + * @param uri, Indicates the path of the data to operate. + * @param dataObserver, Indicates the IDataAbilityObserver object. + */ +void DataShareHelper::UnregisterObserver(const Uri &uri, const sptr &dataObserver) +{ + APP_LOGI("DataShareHelper::UnregisterObserver start."); + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return; + } + + if (dataObserver == nullptr) { + APP_LOGE("%{public}s called. dataObserver is nullptr", __func__); + return; + } + + Uri tmpUri(uri.ToString()); + std::lock_guard lock_l(oplock_); + sptr dataShareProxy = nullptr; + if (uri_ == nullptr) { + auto datashare = registerMap_.find(dataObserver); + if (datashare == registerMap_.end()) { + return; + } + auto path = uriMap_.find(dataObserver); + if (path->second != tmpUri.GetPath()) { + APP_LOGE("DataShareHelper::UnregisterObserver failed input uri's path is not equal the one the " + "observer used"); + return; + } + dataShareProxy = datashare->second; + } else { + dataShareProxy = dataShareProxy_; + } + + if (dataShareProxy == nullptr) { + APP_LOGE("DataShareHelper::UnregisterObserver failed dataShareProxy == nullptr"); + return; + } + + dataShareProxy->UnregisterObserver(uri, dataObserver); + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::UnregisterObserver before DisconnectDataShareExtAbility."); + if (dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->DisconnectDataShareExtAbility(); + } + APP_LOGI("DataShareHelper::UnregisterObserver after DisconnectDataShareExtAbility."); + dataShareProxy_ = nullptr; + } + registerMap_.erase(dataObserver); + uriMap_.erase(dataObserver); + APP_LOGI("DataShareHelper::UnregisterObserver end."); +} + +/** + * @brief Notifies the registered observers of a change to the data resource specified by Uri. + * + * @param uri, Indicates the path of the data to operate. + */ +void DataShareHelper::NotifyChange(const Uri &uri) +{ + APP_LOGI("DataShareHelper::NotifyChange start."); + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return; + } + + if (dataShareProxy_ == nullptr) { + if (!dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->ConnectDataShareExtAbility(want_, token_); + } + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); + } + + if (dataShareProxy_ == nullptr) { + APP_LOGE("%{public}s failed with invalid dataShareProxy_", __func__); + return; + } + + dataShareProxy_->NotifyChange(uri); + + if (uri_ == nullptr) { + if (dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->DisconnectDataShareExtAbility(); + } + dataShareProxy_ = nullptr; + } + APP_LOGI("DataShareHelper::NotifyChange end."); +} + +/** + * @brief Converts the given uri that refer to the data share into a normalized URI. A normalized URI can be used + * across devices, persisted, backed up, and restored. It can refer to the same item in the data share even if the + * context has changed. If you implement URI normalization for a data share, you must also implement + * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to any + * method that is called on the data share must require normalization verification and denormalization. The default + * implementation of this method returns null, indicating that this data share does not support URI normalization. + * + * @param uri Indicates the Uri object to normalize. + * + * @return Returns the normalized Uri object if the data share supports URI normalization; returns null otherwise. + */ +Uri DataShareHelper::NormalizeUri(Uri &uri) +{ + APP_LOGI("DataShareHelper::NormalizeUri start."); + std::lock_guard guard(lock_); + Uri urivalue(""); + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return urivalue; + } + + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::NormalizeUri before ConnectDataShareExtAbility."); + if (!dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->ConnectDataShareExtAbility(want_, token_); + } + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); + APP_LOGI("DataShareHelper::NormalizeUri after ConnectDataShareExtAbility."); + if (isSystemCaller_ && dataShareProxy_) { + AddDataShareDeathRecipient(dataShareProxy_->AsObject()); + } + } + + if (dataShareProxy_ == nullptr) { + APP_LOGE("%{public}s failed with invalid dataShareProxy_", __func__); + return urivalue; + } + + APP_LOGI("DataShareHelper::NormalizeUri before dataShareProxy_->NormalizeUri."); + urivalue = dataShareProxy_->NormalizeUri(uri); + APP_LOGI("DataShareHelper::NormalizeUri after dataShareProxy_->NormalizeUri."); + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::NormalizeUri before DisconnectDataShareExtAbility."); + if (dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->DisconnectDataShareExtAbility(); + } + APP_LOGI("DataShareHelper::NormalizeUri after DisconnectDataShareExtAbility."); + dataShareProxy_ = nullptr; + } + APP_LOGI("DataShareHelper::NormalizeUri end."); + return urivalue; +} + +/** + * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. + * The default implementation of this method returns the original URI passed to it. + * + * @param uri uri Indicates the Uri object to denormalize. + * + * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed to + * this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found in + * the current environment. + */ +Uri DataShareHelper::DenormalizeUri(Uri &uri) +{ + APP_LOGI("DataShareHelper::DenormalizeUri start."); + std::lock_guard guard(lock_); + Uri urivalue(""); + if (!CheckUriParam(uri)) { + APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); + return urivalue; + } + + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::DenormalizeUri before ConnectDataShareExtAbility."); + if (!dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->ConnectDataShareExtAbility(want_, token_); + } + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); + APP_LOGI("DataShareHelper::DenormalizeUri after ConnectDataShareExtAbility."); + if (isSystemCaller_ && dataShareProxy_) { + AddDataShareDeathRecipient(dataShareProxy_->AsObject()); + } + } + + if (dataShareProxy_ == nullptr) { + APP_LOGE("%{public}s failed with invalid dataShareProxy_", __func__); + return urivalue; + } + + APP_LOGI("DataShareHelper::DenormalizeUri before dataShareProxy_->DenormalizeUri."); + urivalue = dataShareProxy_->DenormalizeUri(uri); + APP_LOGI("DataShareHelper::DenormalizeUri after dataShareProxy_->DenormalizeUri."); + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::DenormalizeUri before DisconnectDataShareExtAbility."); + if (dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->DisconnectDataShareExtAbility(); + } + APP_LOGI("DataShareHelper::DenormalizeUri after DisconnectDataShareExtAbility."); + dataShareProxy_ = nullptr; + } + APP_LOGI("DataShareHelper::DenormalizeUri end."); + return urivalue; +} + +void DataShareDeathRecipient::OnRemoteDied(const wptr &remote) +{ + APP_LOGI("recv DataShareDeathRecipient death notice"); + if (handler_) { + handler_(remote); + } + APP_LOGI("DataShareHelper::OnRemoteDied end."); +} + +DataShareDeathRecipient::DataShareDeathRecipient(RemoteDiedHandler handler) : handler_(handler) +{} + +DataShareDeathRecipient::~DataShareDeathRecipient() +{} + +std::vector> DataShareHelper::ExecuteBatch( + const Uri &uri, const std::vector> &operations) +{ + APP_LOGI("DataShareHelper::ExecuteBatch start"); + std::vector> results; + if (!CheckUriParam(uri)) { + APP_LOGE("DataShareHelper::ExecuteBatch. CheckUriParam uri failed"); + return results; + } + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::ExecuteBatch before ConnectDataShareExtAbility."); + if (!dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->ConnectDataShareExtAbility(want_, token_); + } + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); + APP_LOGI("DataShareHelper::ExecuteBatch after ConnectDataShareExtAbility."); + if (dataShareProxy_ == nullptr) { + APP_LOGE("DataShareHelper::ExecuteBatch failed dataShareProxy_ == nullptr"); + return results; + } + } + + if (dataShareProxy_ == nullptr) { + APP_LOGE("%{public}s failed with invalid dataShareProxy_", __func__); + return results; + } + + APP_LOGI("DataShareHelper::ExecuteBatch before dataShareProxy_->ExecuteBatch."); + results = dataShareProxy_->ExecuteBatch(operations); + APP_LOGI("DataShareHelper::ExecuteBatch after dataShareProxy_->ExecuteBatch."); + if (uri_ == nullptr) { + APP_LOGI("DataShareHelper::ExecuteBatch before DisconnectDataShareExtAbility."); + if (dataShareConnection_->IsExtAbilityConnected()) { + dataShareConnection_->DisconnectDataShareExtAbility(); + } + APP_LOGI("DataShareHelper::ExecuteBatch after DisconnectDataShareExtAbility."); + dataShareProxy_ = nullptr; + } + APP_LOGI("DataShareHelper::ExecuteBatch end"); + return results; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/datashare_proxy.cpp b/frameworks/kits/ability/native/src/datashare_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7df5ade41a22c5ee6e27e8855cc2b30c992d51af --- /dev/null +++ b/frameworks/kits/ability/native/src/datashare_proxy.cpp @@ -0,0 +1,584 @@ +/* + * 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 + * + * 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 "datashare_proxy.h" + +#include +#include + +#include "abs_shared_result_set.h" +#include "app_log_wrapper.h" +#include "data_ability_observer_interface.h" +#include "data_ability_operation.h" +#include "data_ability_predicates.h" +#include "data_ability_result.h" +#include "ipc_types.h" +#include "ishared_result_set.h" +#include "pac_map.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +std::vector DataShareProxy::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) +{ + APP_LOGI("%{public}s begin.", __func__); + std::vector types; + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { + APP_LOGE("%{public}s WriteInterfaceToken failed", __func__); + return types; + } + + if (!data.WriteParcelable(&uri)) { + APP_LOGE("fail to WriteParcelable uri"); + return types; + } + + if (!data.WriteString(mimeTypeFilter)) { + APP_LOGE("fail to WriteString mimeTypeFilter"); + return types; + } + + int32_t err = Remote()->SendRequest(CMD_GET_FILE_TYPES, data, reply, option); + if (err != NO_ERROR) { + APP_LOGE("GetFileTypes fail to SendRequest. err: %d", err); + } + + if (!reply.ReadStringVector(&types)) { + APP_LOGE("fail to ReadStringVector types"); + } + + APP_LOGI("%{public}s end successfully.", __func__); + return types; +} + +int DataShareProxy::OpenFile(const Uri &uri, const std::string &mode) +{ + APP_LOGI("%{public}s begin.", __func__); + int fd = -1; + MessageParcel data; + if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { + APP_LOGE("%{public}s WriteInterfaceToken failed", __func__); + return fd; + } + + if (!data.WriteParcelable(&uri)) { + APP_LOGE("fail to WriteParcelable uri"); + return fd; + } + + if (!data.WriteString(mode)) { + APP_LOGE("fail to WriteString mode"); + return fd; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(CMD_OPEN_FILE, data, reply, option); + if (err != NO_ERROR) { + APP_LOGE("OpenFile fail to SendRequest. err: %d", err); + return fd; + } + + fd = reply.ReadFileDescriptor(); + if (fd == -1) { + APP_LOGE("fail to ReadFileDescriptor fd"); + return fd; + } + + APP_LOGI("%{public}s end successfully.", __func__); + return fd; +} + +int DataShareProxy::OpenRawFile(const Uri &uri, const std::string &mode) +{ + APP_LOGI("%{public}s begin.", __func__); + int fd = -1; + MessageParcel data; + if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { + APP_LOGE("%{public}s WriteInterfaceToken failed", __func__); + return fd; + } + + if (!data.WriteParcelable(&uri)) { + APP_LOGE("fail to WriteParcelable uri"); + return fd; + } + + if (!data.WriteString(mode)) { + APP_LOGE("fail to WriteString mode"); + return fd; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(CMD_OPEN_RAW_FILE, data, reply, option); + if (err != NO_ERROR) { + APP_LOGE("OpenRawFile fail to SendRequest. err: %d", err); + return fd; + } + + if (!reply.ReadInt32(fd)) { + APP_LOGE("fail to ReadInt32 fd"); + return fd; + } + + APP_LOGI("%{public}s end successfully.", __func__); + return fd; +} + +int DataShareProxy::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) +{ + APP_LOGI("%{public}s begin.", __func__); + int index = -1; + MessageParcel data; + if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { + APP_LOGE("%{public}s WriteInterfaceToken failed", __func__); + return index; + } + + if (!data.WriteParcelable(&uri)) { + APP_LOGE("fail to WriteParcelable uri"); + return index; + } + + if (!data.WriteParcelable(&value)) { + APP_LOGE("fail to WriteParcelable value"); + return index; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(CMD_INSERT, data, reply, option); + if (err != NO_ERROR) { + APP_LOGE("Insert fail to SendRequest. err: %d", err); + return index; + } + + if (!reply.ReadInt32(index)) { + APP_LOGE("fail to ReadInt32 index"); + return index; + } + + APP_LOGI("%{public}s end successfully.", __func__); + return index; +} + +int DataShareProxy::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, + const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("%{public}s begin.", __func__); + int index = -1; + MessageParcel data; + if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { + APP_LOGE("%{public}s WriteInterfaceToken failed", __func__); + return index; + } + + if (!data.WriteParcelable(&uri)) { + APP_LOGE("fail to WriteParcelable uri"); + return index; + } + + if (!data.WriteParcelable(&value)) { + APP_LOGE("fail to WriteParcelable value"); + return index; + } + + if (!data.WriteParcelable(&predicates)) { + APP_LOGE("fail to WriteParcelable predicates"); + return index; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(CMD_UPDATE, data, reply, option); + if (err != NO_ERROR) { + APP_LOGE("Update fail to SendRequest. err: %d", err); + return index; + } + + if (!reply.ReadInt32(index)) { + APP_LOGE("fail to ReadInt32 index"); + return index; + } + + APP_LOGI("%{public}s end successfully.", __func__); + return index; +} + +int DataShareProxy::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("%{public}s begin.", __func__); + int index = -1; + MessageParcel data; + if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { + APP_LOGE("%{public}s WriteInterfaceToken failed", __func__); + return index; + } + + if (!data.WriteParcelable(&uri)) { + APP_LOGE("fail to WriteParcelable uri"); + return index; + } + + if (!data.WriteParcelable(&predicates)) { + APP_LOGE("fail to WriteParcelable predicates"); + return index; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(CMD_DELETE, data, reply, option); + if (err != NO_ERROR) { + APP_LOGE("Delete fail to SendRequest. err: %d", err); + return index; + } + + if (!reply.ReadInt32(index)) { + APP_LOGE("fail to ReadInt32 index"); + return index; + } + + APP_LOGI("%{public}s end successfully.", __func__); + return index; +} + +std::shared_ptr DataShareProxy::Query(const Uri &uri, + std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) +{ + APP_LOGI("%{public}s begin.", __func__); + MessageParcel data; + if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { + APP_LOGE("%{public}s WriteInterfaceToken failed", __func__); + return nullptr; + } + + if (!data.WriteParcelable(&uri)) { + APP_LOGE("fail to WriteParcelable uri"); + return nullptr; + } + + if (!data.WriteStringVector(columns)) { + APP_LOGE("fail to WriteStringVector columns"); + return nullptr; + } + + if (!data.WriteParcelable(&predicates)) { + APP_LOGE("fail to WriteParcelable predicates"); + return nullptr; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(CMD_QUERY, data, reply, option); + if (err != NO_ERROR) { + APP_LOGE("Query fail to SendRequest. err: %d", err); + return nullptr; + } + APP_LOGI("%{public}s end successfully.", __func__); + return OHOS::NativeRdb::ISharedResultSet::ReadFromParcel(reply); +} + +std::string DataShareProxy::GetType(const Uri &uri) +{ + APP_LOGI("%{public}s begin.", __func__); + std::string type; + MessageParcel data; + if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { + APP_LOGE("%{public}s WriteInterfaceToken failed", __func__); + return type; + } + if (!data.WriteParcelable(&uri)) { + APP_LOGE("fail to WriteParcelable uri"); + return type; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(CMD_GET_TYPE, data, reply, option); + if (err != NO_ERROR) { + APP_LOGE("GetFileTypes fail to SendRequest. err: %d", err); + return type; + } + + type = reply.ReadString(); + if (type.empty()) { + APP_LOGE("fail to ReadString type"); + return type; + } + + APP_LOGI("%{public}s end successfully.", __func__); + return type; +} + +int DataShareProxy::BatchInsert(const Uri &uri, const std::vector &values) +{ + APP_LOGI("%{public}s begin.", __func__); + int ret = -1; + MessageParcel data; + if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { + APP_LOGE("%{public}s WriteInterfaceToken failed", __func__); + return ret; + } + + if (!data.WriteParcelable(&uri)) { + APP_LOGE("fail to WriteParcelable uri"); + return ret; + } + + int count = values.size(); + if (!data.WriteInt32(count)) { + APP_LOGE("fail to WriteInt32 ret"); + return ret; + } + + for (int i = 0; i < count; i++) { + if (!data.WriteParcelable(&values[i])) { + APP_LOGE("fail to WriteParcelable ret, index = %{public}d", i); + return ret; + } + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(CMD_BATCH_INSERT, data, reply, option); + if (err != NO_ERROR) { + APP_LOGE("GetFileTypes fail to SendRequest. err: %d", err); + return ret; + } + + if (!reply.ReadInt32(ret)) { + APP_LOGE("fail to ReadInt32 index"); + return ret; + } + + APP_LOGI("%{public}s end successfully.", __func__); + return ret; +} + +bool DataShareProxy::RegisterObserver(const Uri &uri, const sptr &dataObserver) +{ + APP_LOGI("%{public}s begin.", __func__); + MessageParcel data; + if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { + APP_LOGE("%{public}s WriteInterfaceToken failed", __func__); + return false; + } + + if (!data.WriteParcelable(&uri)) { + APP_LOGE("%{public}s failed to WriteParcelable uri ", __func__); + return false; + } + + if (!data.WriteParcelable(dataObserver->AsObject())) { + APP_LOGE("%{public}s failed to WriteParcelable dataObserver ", __func__); + return false; + } + + MessageParcel reply; + MessageOption option; + int32_t result = Remote()->SendRequest(CMD_REGISTER_OBSERVER, data, reply, option); + if (result == ERR_NONE) { + APP_LOGI("%{public}s SendRequest ok, retval is %{public}d", __func__, reply.ReadInt32()); + } else { + APP_LOGE("%{public}s SendRequest error, result=%{public}d", __func__, result); + return false; + } + APP_LOGI("%{public}s end.", __func__); + return true; +} + +bool DataShareProxy::UnregisterObserver(const Uri &uri, const sptr &dataObserver) +{ + APP_LOGI("%{public}s begin.", __func__); + MessageParcel data; + if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { + APP_LOGE("%{public}s WriteInterfaceToken failed", __func__); + return false; + } + + if (!data.WriteParcelable(&uri)) { + APP_LOGE("%{public}s failed to WriteParcelable uri ", __func__); + return false; + } + + if (!data.WriteParcelable(dataObserver->AsObject())) { + APP_LOGE("%{public}s failed to WriteParcelable dataObserver ", __func__); + return false; + } + + MessageParcel reply; + MessageOption option; + int32_t result = Remote()->SendRequest(CMD_UNREGISTER_OBSERVER, data, reply, option); + if (result == ERR_NONE) { + APP_LOGI("%{public}s SendRequest ok, retval is %{public}d", __func__, reply.ReadInt32()); + } else { + APP_LOGE("%{public}s SendRequest error, result=%{public}d", __func__, result); + return false; + } + APP_LOGI("%{public}s end successfully.", __func__); + return true; +} + +bool DataShareProxy::NotifyChange(const Uri &uri) +{ + APP_LOGI("%{public}s begin.", __func__); + MessageParcel data; + if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { + APP_LOGE("%{public}s WriteInterfaceToken failed", __func__); + return false; + } + + if (!data.WriteParcelable(&uri)) { + APP_LOGE("%{public}s failed to WriteParcelable uri ", __func__); + return false; + } + + MessageParcel reply; + MessageOption option; + int32_t result = Remote()->SendRequest(CMD_NOTIFY_CHANGE, data, reply, option); + if (result == ERR_NONE) { + APP_LOGI("%{public}s SendRequest ok, retval is %{public}d", __func__, reply.ReadInt32()); + } else { + APP_LOGE("%{public}s SendRequest error, result=%{public}d", __func__, result); + return false; + } + APP_LOGI("%{public}s end successfully.", __func__); + return true; +} + +Uri DataShareProxy::NormalizeUri(const Uri &uri) +{ + APP_LOGI("%{public}s begin.", __func__); + Uri urivalue(""); + MessageParcel data; + if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { + APP_LOGE("%{public}s WriteInterfaceToken failed", __func__); + return urivalue; + } + + if (!data.WriteParcelable(&uri)) { + APP_LOGE("fail to WriteParcelable uri"); + return urivalue; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(CMD_NORMALIZE_URI, data, reply, option); + if (err != NO_ERROR) { + APP_LOGE("NormalizeUri fail to SendRequest. err: %d", err); + return urivalue; + } + + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + APP_LOGE("ReadParcelable value is nullptr."); + return urivalue; + } + APP_LOGI("%{public}s end successfully.", __func__); + return *info; +} + +Uri DataShareProxy::DenormalizeUri(const Uri &uri) +{ + APP_LOGI("%{public}s begin.", __func__); + Uri urivalue(""); + MessageParcel data; + if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { + APP_LOGE("%{public}s WriteInterfaceToken failed", __func__); + return urivalue; + } + + if (!data.WriteParcelable(&uri)) { + APP_LOGE("fail to WriteParcelable uri"); + return urivalue; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(CMD_DENORMALIZE_URI, data, reply, option); + if (err != NO_ERROR) { + APP_LOGE("DenormalizeUri fail to SendRequest. err: %d", err); + return urivalue; + } + + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + APP_LOGE("ReadParcelable value is nullptr."); + return urivalue; + } + APP_LOGI("%{public}s end successfully.", __func__); + return *info; +} + +std::vector> DataShareProxy::ExecuteBatch( + const std::vector> &operations) +{ + APP_LOGI("%{public}s begin.", __func__); + MessageParcel data; + std::vector> results; + results.clear(); + + if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { + APP_LOGE("%{public}s WriteInterfaceToken failed", __func__); + return results; + } + + int count = operations.size(); + if (!data.WriteInt32(count)) { + APP_LOGE("fail to WriteInt32 ret"); + return results; + } + + for (int i = 0; i < count; i++) { + if (!data.WriteParcelable(operations[i].get())) { + APP_LOGE("fail to WriteParcelable ret, index = %{public}d", i); + return results; + } + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(CMD_EXECUTE_BATCH, data, reply, option); + if (err != NO_ERROR) { + APP_LOGE("fail to SendRequest. err: %{public}d", err); + return results; + } + + int total = 0; + if (!reply.ReadInt32(total)) { + APP_LOGE("fail to ReadInt32 count %{public}d", total); + return results; + } + + for (int i = 0; i < total; i++) { + AppExecFwk::DataAbilityResult *result = reply.ReadParcelable(); + if (result == nullptr) { + APP_LOGE("result is nullptr, index = %{public}d", i); + return results; + } + std::shared_ptr dataAbilityResult(result); + results.push_back(dataAbilityResult); + } + APP_LOGI("%{public}s end successfully.", __func__); + return results; +} +} // namespace AAFwk +} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/datashare_stub.cpp b/frameworks/kits/ability/native/src/datashare_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..166cf75b676c6ca8686c3bd8d020850c9289f408 --- /dev/null +++ b/frameworks/kits/ability/native/src/datashare_stub.cpp @@ -0,0 +1,419 @@ +/* + * 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 + * + * 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 "datashare_stub.h" + +#include "app_log_wrapper.h" +#include "data_ability_observer_interface.h" +#include "data_ability_operation.h" +#include "data_ability_predicates.h" +#include "data_ability_result.h" +#include "ipc_types.h" +#include "ishared_result_set.h" +#include "values_bucket.h" + +namespace OHOS { +namespace AppExecFwk { +DataShareStub::DataShareStub() +{ + stubFuncMap_[CMD_GET_FILE_TYPES] = &DataShareStub::CmdGetFileTypes; + stubFuncMap_[CMD_OPEN_FILE] = &DataShareStub::CmdOpenFile; + stubFuncMap_[CMD_OPEN_RAW_FILE] = &DataShareStub::CmdOpenRawFile; + stubFuncMap_[CMD_INSERT] = &DataShareStub::CmdInsert; + stubFuncMap_[CMD_UPDATE] = &DataShareStub::CmdUpdate; + stubFuncMap_[CMD_DELETE] = &DataShareStub::CmdDelete; + stubFuncMap_[CMD_QUERY] = &DataShareStub::CmdQuery; + stubFuncMap_[CMD_GET_TYPE] = &DataShareStub::CmdGetType; + stubFuncMap_[CMD_BATCH_INSERT] = &DataShareStub::CmdBatchInsert; + stubFuncMap_[CMD_REGISTER_OBSERVER] = &DataShareStub::CmdRegisterObserver; + stubFuncMap_[CMD_UNREGISTER_OBSERVER] = &DataShareStub::CmdUnregisterObserver; + stubFuncMap_[CMD_NOTIFY_CHANGE] = &DataShareStub::CmdNotifyChange; + stubFuncMap_[CMD_NORMALIZE_URI] = &DataShareStub::CmdNormalizeUri; + stubFuncMap_[CMD_DENORMALIZE_URI] = &DataShareStub::CmdDenormalizeUri; + stubFuncMap_[CMD_EXECUTE_BATCH] = &DataShareStub::CmdExecuteBatch; +} + +DataShareStub::~DataShareStub() +{ + stubFuncMap_.clear(); +} + +int DataShareStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, + MessageOption& option) +{ + APP_LOGI("%{public}s Received stub message: %{public}d", __func__, code); + std::u16string descriptor = DataShareStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGI("local descriptor is not equal to remote"); + return ERR_INVALID_STATE; + } + + const auto &itFunc = stubFuncMap_.find(code); + if (itFunc != stubFuncMap_.end()) { + return (this->*(itFunc->second))(data, reply); + } + + APP_LOGI("%{public}s remote request unhandled: %{public}d", __func__, code); + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +ErrCode DataShareStub::CmdGetFileTypes(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr uri(data.ReadParcelable()); + if (uri == nullptr) { + APP_LOGE("DataShareStub uri is nullptr"); + return ERR_INVALID_VALUE; + } + std::string mimeTypeFilter = data.ReadString(); + if (mimeTypeFilter.empty()) { + APP_LOGE("DataShareStub mimeTypeFilter is nullptr"); + return ERR_INVALID_VALUE; + } + std::vector types = GetFileTypes(*uri, mimeTypeFilter); + if (!reply.WriteStringVector(types)) { + APP_LOGE("fail to WriteStringVector types"); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +ErrCode DataShareStub::CmdOpenFile(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr uri(data.ReadParcelable()); + if (uri == nullptr) { + APP_LOGE("DataShareStub uri is nullptr"); + return ERR_INVALID_VALUE; + } + std::string mode = data.ReadString(); + if (mode.empty()) { + APP_LOGE("DataShareStub mode is nullptr"); + return ERR_INVALID_VALUE; + } + int fd = OpenFile(*uri, mode); + if (fd < 0) { + APP_LOGE("OpenFile fail, fd is %{pubilc}d", fd); + return ERR_INVALID_VALUE; + } + if (!reply.WriteFileDescriptor(fd)) { + APP_LOGE("fail to WriteFileDescriptor fd"); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +ErrCode DataShareStub::CmdOpenRawFile(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr uri(data.ReadParcelable()); + if (uri == nullptr) { + APP_LOGE("DataShareStub uri is nullptr"); + return ERR_INVALID_VALUE; + } + std::string mode = data.ReadString(); + if (mode.empty()) { + APP_LOGE("DataShareStub mode is nullptr"); + return ERR_INVALID_VALUE; + } + int fd = OpenRawFile(*uri, mode); + if (!reply.WriteInt32(fd)) { + APP_LOGE("fail to WriteInt32 fd"); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +ErrCode DataShareStub::CmdInsert(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr uri(data.ReadParcelable()); + if (uri == nullptr) { + APP_LOGE("DataShareStub uri is nullptr"); + return ERR_INVALID_VALUE; + } + std::shared_ptr value(data.ReadParcelable()); + if (value == nullptr) { + APP_LOGE("ReadParcelable value is nullptr"); + return ERR_INVALID_VALUE; + } + int index = Insert(*uri, *value); + if (!reply.WriteInt32(index)) { + APP_LOGE("fail to WriteInt32 index"); + return ERR_INVALID_VALUE; + } + APP_LOGI("DataShareStub::CmdInsertInner end"); + return NO_ERROR; +} + +ErrCode DataShareStub::CmdUpdate(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr uri(data.ReadParcelable()); + if (uri == nullptr) { + APP_LOGE("DataShareStub uri is nullptr"); + return ERR_INVALID_VALUE; + } + std::shared_ptr value(data.ReadParcelable()); + if (value == nullptr) { + APP_LOGE("ReadParcelable value is nullptr"); + return ERR_INVALID_VALUE; + } + std::shared_ptr predicates( + data.ReadParcelable()); + if (predicates == nullptr) { + APP_LOGE("ReadParcelable predicates is nullptr"); + return ERR_INVALID_VALUE; + } + int index = Update(*uri, *value, *predicates); + if (!reply.WriteInt32(index)) { + APP_LOGE("fail to WriteInt32 index"); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +ErrCode DataShareStub::CmdDelete(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr uri(data.ReadParcelable()); + if (uri == nullptr) { + APP_LOGE("DataShareStub uri is nullptr"); + return ERR_INVALID_VALUE; + } + std::shared_ptr predicates( + data.ReadParcelable()); + if (predicates == nullptr) { + APP_LOGE("ReadParcelable predicates is nullptr"); + return ERR_INVALID_VALUE; + } + int index = Delete(*uri, *predicates); + if (!reply.WriteInt32(index)) { + APP_LOGE("fail to WriteInt32 index"); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +ErrCode DataShareStub::CmdQuery(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr uri(data.ReadParcelable()); + if (uri == nullptr) { + APP_LOGE("DataShareStub uri is nullptr"); + return ERR_INVALID_VALUE; + } + std::vector columns; + if (!data.ReadStringVector(&columns)) { + APP_LOGE("fail to ReadStringVector columns"); + return ERR_INVALID_VALUE; + } + std::shared_ptr predicates( + data.ReadParcelable()); + if (predicates == nullptr) { + APP_LOGE("ReadParcelable predicates is nullptr"); + return ERR_INVALID_VALUE; + } + auto resultSet = Query(*uri, columns, *predicates); + if (resultSet == nullptr) { + APP_LOGE("fail to WriteParcelable resultSet"); + return ERR_INVALID_VALUE; + } + auto result = NativeRdb::ISharedResultSet::WriteToParcel(std::move(resultSet), reply); + if (result == nullptr) { + APP_LOGE("!resultSet->Marshalling(reply)"); + return ERR_INVALID_VALUE; + } + APP_LOGI("DataShareStub::CmdQueryInner end"); + return NO_ERROR; +} + +ErrCode DataShareStub::CmdGetType(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr uri(data.ReadParcelable()); + if (uri == nullptr) { + APP_LOGE("DataShareStub uri is nullptr"); + return ERR_INVALID_VALUE; + } + std::string type = GetType(*uri); + if (!reply.WriteString(type)) { + APP_LOGE("fail to WriteString type"); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +ErrCode DataShareStub::CmdBatchInsert(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr uri(data.ReadParcelable()); + if (uri == nullptr) { + APP_LOGE("DataShareStub uri is nullptr"); + return ERR_INVALID_VALUE; + } + + int count = 0; + if (!data.ReadInt32(count)) { + APP_LOGE("fail to ReadInt32 index"); + return ERR_INVALID_VALUE; + } + + std::vector values; + for (int i = 0; i < count; i++) { + NativeRdb::ValuesBucket *value = data.ReadParcelable(); + if (value == nullptr) { + APP_LOGE("DataShareStub value is nullptr, index = %{public}d", i); + return ERR_INVALID_VALUE; + } + values.emplace_back(*value); + } + + int ret = BatchInsert(*uri, values); + if (!reply.WriteInt32(ret)) { + APP_LOGE("fail to WriteInt32 ret"); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + + +ErrCode DataShareStub::CmdRegisterObserver(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr uri(data.ReadParcelable()); + if (uri == nullptr) { + APP_LOGE("DataShareStub uri is nullptr"); + return ERR_INVALID_VALUE; + } + auto obServer = iface_cast(data.ReadParcelable()); + if (obServer == nullptr) { + APP_LOGE("DataShareStub obServer is nullptr"); + return ERR_INVALID_VALUE; + } + + bool ret = RegisterObserver(*uri, obServer); + if (!reply.WriteInt32(ret)) { + APP_LOGE("fail to WriteInt32 ret"); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +ErrCode DataShareStub::CmdUnregisterObserver(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr uri(data.ReadParcelable()); + if (uri == nullptr) { + APP_LOGE("DataShareStub uri is nullptr"); + return ERR_INVALID_VALUE; + } + auto obServer = iface_cast(data.ReadParcelable()); + if (obServer == nullptr) { + APP_LOGE("DataShareStub obServer is nullptr"); + return ERR_INVALID_VALUE; + } + + bool ret = UnregisterObserver(*uri, obServer); + if (!reply.WriteInt32(ret)) { + APP_LOGE("fail to WriteInt32 ret"); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +ErrCode DataShareStub::CmdNotifyChange(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr uri(data.ReadParcelable()); + if (uri == nullptr) { + APP_LOGE("DataShareStub uri is nullptr"); + return ERR_INVALID_VALUE; + } + + bool ret = NotifyChange(*uri); + if (!reply.WriteInt32(ret)) { + APP_LOGE("fail to WriteInt32 ret"); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +ErrCode DataShareStub::CmdNormalizeUri(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr uri(data.ReadParcelable()); + if (uri == nullptr) { + APP_LOGE("DataShareStub uri is nullptr"); + return ERR_INVALID_VALUE; + } + + Uri ret(""); + ret = NormalizeUri(*uri); + if (!reply.WriteParcelable(&ret)) { + APP_LOGE("fail to WriteParcelable type"); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +ErrCode DataShareStub::CmdDenormalizeUri(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr uri(data.ReadParcelable()); + if (uri == nullptr) { + APP_LOGE("DataShareStub uri is nullptr"); + return ERR_INVALID_VALUE; + } + + Uri ret(""); + ret = DenormalizeUri(*uri); + if (!reply.WriteParcelable(&ret)) { + APP_LOGE("fail to WriteParcelable type"); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +ErrCode DataShareStub::CmdExecuteBatch(MessageParcel &data, MessageParcel &reply) +{ + APP_LOGI("DataShareStub::CmdExecuteBatchInner start"); + int count = 0; + if (!data.ReadInt32(count)) { + APP_LOGE("DataShareStub::CmdExecuteBatchInner fail to ReadInt32 count"); + return ERR_INVALID_VALUE; + } + APP_LOGI("DataShareStub::CmdExecuteBatchInner count:%{public}d", count); + std::vector> operations; + for (int i = 0; i < count; i++) { + AppExecFwk::DataAbilityOperation *operation = data.ReadParcelable(); + if (operation == nullptr) { + APP_LOGE("DataShareStub::CmdExecuteBatchInner operation is nullptr, index = %{public}d", i); + return ERR_INVALID_VALUE; + } + std::shared_ptr dataAbilityOperation(operation); + operations.push_back(dataAbilityOperation); + } + + std::vector> results = ExecuteBatch(operations); + int total = results.size(); + if (!reply.WriteInt32(total)) { + APP_LOGE("DataShareStub::CmdExecuteBatchInner fail to WriteInt32 ret"); + return ERR_INVALID_VALUE; + } + APP_LOGI("DataShareStub::CmdExecuteBatchInner total:%{public}d", total); + for (int i = 0; i < total; i++) { + if (results[i] == nullptr) { + APP_LOGE("DataShareStub::CmdExecuteBatchInner results[i] is nullptr, index = %{public}d", i); + return ERR_INVALID_VALUE; + } + if (!reply.WriteParcelable(results[i].get())) { + APP_LOGE( + "DataShareStub::CmdExecuteBatchInner fail to WriteParcelable operation, index = %{public}d", i); + return ERR_INVALID_VALUE; + } + } + APP_LOGI("DataShareStub::CmdExecuteBatchInner end"); + return NO_ERROR; +} +} // namespace AAFwk +} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/datashare_stub_impl.cpp b/frameworks/kits/ability/native/src/datashare_stub_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cdb64cb036ee96cb5328fba23dc514cf83564d89 --- /dev/null +++ b/frameworks/kits/ability/native/src/datashare_stub_impl.cpp @@ -0,0 +1,224 @@ +/* + * 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 + * + * 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 "datashare_stub_impl.h" + +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +std::vector DataShareStubImpl::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) +{ + HILOG_INFO("%{public}s begin.", __func__); + std::vector ret; + auto extension = extension_.lock(); + if (extension == nullptr) { + HILOG_INFO("%{public}s end failed.", __func__); + return ret; + } + ret = extension->GetFileTypes(uri, mimeTypeFilter); + HILOG_INFO("%{public}s end successfully.", __func__); + return ret; +} + +int DataShareStubImpl::OpenFile(const Uri &uri, const std::string &mode) +{ + HILOG_INFO("%{public}s begin.", __func__); + auto extension = extension_.lock(); + if (extension == nullptr) { + HILOG_INFO("%{public}s end failed.", __func__); + return -1; + } + auto ret = extension->OpenFile(uri, mode); + HILOG_INFO("%{public}s end successfully.", __func__); + return ret; +} + +int DataShareStubImpl::OpenRawFile(const Uri &uri, const std::string &mode) +{ + HILOG_INFO("%{public}s begin.", __func__); + auto extension = extension_.lock(); + if (extension == nullptr) { + HILOG_INFO("%{public}s end failed.", __func__); + return -1; + } + auto ret = extension->OpenRawFile(uri, mode); + HILOG_INFO("%{public}s end successfully.", __func__); + return ret; +} + +int DataShareStubImpl::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) +{ + HILOG_INFO("%{public}s begin.", __func__); + auto extension = extension_.lock(); + if (extension == nullptr) { + HILOG_INFO("%{public}s end failed.", __func__); + return -1; + } + auto ret = extension->Insert(uri, value); + HILOG_INFO("%{public}s end successfully.", __func__); + return ret; +} + +int DataShareStubImpl::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, + const NativeRdb::DataAbilityPredicates &predicates) +{ + HILOG_INFO("%{public}s begin.", __func__); + auto extension = extension_.lock(); + if (extension == nullptr) { + HILOG_INFO("%{public}s end failed.", __func__); + return -1; + } + auto ret = extension->Update(uri, value, predicates); + HILOG_INFO("%{public}s end successfully.", __func__); + return ret; +} + +int DataShareStubImpl::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) +{ + HILOG_INFO("%{public}s begin.", __func__); + auto extension = extension_.lock(); + if (extension == nullptr) { + HILOG_INFO("%{public}s end failed.", __func__); + return -1; + } + auto ret = extension->Delete(uri, predicates); + HILOG_INFO("%{public}s end successfully.", __func__); + return ret; +} + +std::shared_ptr DataShareStubImpl::Query(const Uri &uri, + std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) +{ + HILOG_INFO("%{public}s begin.", __func__); + auto extension = extension_.lock(); + if (extension == nullptr) { + HILOG_INFO("%{public}s end failed.", __func__); + return nullptr; + } + auto ret = extension->Query(uri, columns, predicates); + HILOG_INFO("%{public}s end successfully.", __func__); + return ret; +} + +std::string DataShareStubImpl::GetType(const Uri &uri) +{ + HILOG_INFO("%{public}s begin.", __func__); + auto extension = extension_.lock(); + if (extension == nullptr) { + HILOG_INFO("%{public}s end failed.", __func__); + return ""; + } + auto ret = extension->GetType(uri); + HILOG_INFO("%{public}s end successfully.", __func__); + return ret; +} + +int DataShareStubImpl::BatchInsert(const Uri &uri, const std::vector &values) +{ + HILOG_INFO("%{public}s begin.", __func__); + auto extension = extension_.lock(); + if (extension == nullptr) { + HILOG_INFO("%{public}s end failed.", __func__); + return -1; + } + auto ret = extension->BatchInsert(uri, values); + HILOG_INFO("%{public}s end successfully.", __func__); + return ret; +} + +bool DataShareStubImpl::RegisterObserver(const Uri &uri, const sptr &dataObserver) +{ + HILOG_INFO("%{public}s begin.", __func__); + auto extension = extension_.lock(); + if (extension == nullptr) { + HILOG_INFO("%{public}s end failed.", __func__); + return false; + } + bool ret = extension->RegisterObserver(uri, dataObserver); + HILOG_INFO("%{public}s end successfully.", __func__); + return ret; +} + +bool DataShareStubImpl::UnregisterObserver(const Uri &uri, const sptr &dataObserver) +{ + HILOG_INFO("%{public}s begin.", __func__); + auto extension = extension_.lock(); + if (extension == nullptr) { + HILOG_INFO("%{public}s end failed.", __func__); + return false; + } + bool ret = extension->UnregisterObserver(uri, dataObserver); + HILOG_INFO("%{public}s end successfully.", __func__); + return ret; +} + +bool DataShareStubImpl::NotifyChange(const Uri &uri) +{ + HILOG_INFO("%{public}s begin.", __func__); + auto extension = extension_.lock(); + if (extension == nullptr) { + HILOG_INFO("%{public}s end failed.", __func__); + return false; + } + bool ret = extension->NotifyChange(uri); + HILOG_INFO("%{public}s end successfully.", __func__); + return ret; +} + +Uri DataShareStubImpl::NormalizeUri(const Uri &uri) +{ + HILOG_INFO("%{public}s begin.", __func__); + Uri urivalue(""); + auto extension = extension_.lock(); + if (extension == nullptr) { + HILOG_INFO("%{public}s end failed.", __func__); + return urivalue; + } + urivalue = extension->NormalizeUri(uri); + HILOG_INFO("%{public}s end successfully.", __func__); + return urivalue; +} + +Uri DataShareStubImpl::DenormalizeUri(const Uri &uri) +{ + HILOG_INFO("%{public}s begin.", __func__); + Uri urivalue(""); + auto extension = extension_.lock(); + if (extension == nullptr) { + HILOG_INFO("%{public}s end failed.", __func__); + return urivalue; + } + urivalue = extension->DenormalizeUri(uri); + HILOG_INFO("%{public}s end successfully.", __func__); + return urivalue; +} + +std::vector> DataShareStubImpl::ExecuteBatch( + const std::vector> &operations) +{ + HILOG_INFO("%{public}s begin.", __func__); + std::vector> results; + auto extension = extension_.lock(); + if (extension == nullptr) { + HILOG_INFO("%{public}s end failed.", __func__); + return results; + } + results = extension->ExecuteBatch(operations); + HILOG_INFO("%{public}s end successfully.", __func__); + return results; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/form_provider_client.cpp b/frameworks/kits/ability/native/src/form_provider_client.cpp index 940c62ba58900119b90ca84a132fe3b82039da47..2755f4bbbba7909dc5f237e08d7805cb30382fbc 100644 --- a/frameworks/kits/ability/native/src/form_provider_client.cpp +++ b/frameworks/kits/ability/native/src/form_provider_client.cpp @@ -439,7 +439,9 @@ int FormProviderClient::HandleAcquire( const Want &newWant, const sptr &callerToken) { - APP_LOGI("%{public}s start", __func__); + APP_LOGI("%{public}s start, image state is %{public}d", + __func__, formProviderInfo.GetFormData().GetImageDataState()); + sptr formSupplyClient = iface_cast(callerToken); if (formSupplyClient == nullptr) { APP_LOGW("%{public}s warn, IFormSupply is nullptr", __func__); diff --git a/frameworks/kits/ability/native/src/form_runtime/js_form_extension.cpp b/frameworks/kits/ability/native/src/form_runtime/js_form_extension.cpp index 9e8cc7c6a1d5b152d55fc25b50c4e0790fb01805..540c967dc0e2a99db2de80602c545c645bcf7b6b 100644 --- a/frameworks/kits/ability/native/src/form_runtime/js_form_extension.cpp +++ b/frameworks/kits/ability/native/src/form_runtime/js_form_extension.cpp @@ -26,6 +26,7 @@ #include "js_runtime_utils.h" #include "napi/native_api.h" #include "napi/native_node_api.h" +#include "napi_common_util.h" #include "napi_common_want.h" namespace OHOS { @@ -49,12 +50,12 @@ void JsFormExtension::Init(const std::shared_ptr &record, { HILOG_INFO("JsFormExtension::Init begin."); FormExtension::Init(record, application, handler, token); - std::string srcPath(Extension::abilityInfo_->package); - srcPath.append("/assets/js/"); - if (!Extension::abilityInfo_->srcPath.empty()) { - srcPath.append(Extension::abilityInfo_->srcPath).append("/"); + std::string srcPath; + GetSrcPath(srcPath); + if (srcPath.empty()) { + HILOG_ERROR("Failed to get srcPath"); + return; } - srcPath.append(Extension::abilityInfo_->name).append(".abc"); std::string moduleName(Extension::abilityInfo_->moduleName); moduleName.append("::").append(abilityInfo_->name); @@ -137,6 +138,15 @@ OHOS::AppExecFwk::FormProviderInfo JsFormExtension::OnCreate(const OHOS::AAFwk:: } AppExecFwk::FormProviderData formData = AppExecFwk::FormProviderData(formDataStr); + nativeDataValue = nativeObject->GetProperty("image"); + if (nativeDataValue != nullptr) { + std::map rawImageDataMap; + UnwrapRawImageDataMap(*nativeEngine, nativeDataValue, rawImageDataMap); + HILOG_INFO("Image number is %{public}zu", rawImageDataMap.size()); + for (auto entry : rawImageDataMap) { + formData.AddImageData(entry.first, entry.second); + } + } formProviderInfo.SetFormData(formData); HILOG_INFO("%{public}s called end.", __func__); return formProviderInfo; @@ -266,5 +276,62 @@ NativeValue* JsFormExtension::CallObjectMethod(const char* name, NativeValue* co HILOG_INFO("JsFormExtension::CallFunction(%{public}s), success", name); return handleScope.Escape(nativeEngine.CallFunction(value, method, argv, argc)); } + +void JsFormExtension::GetSrcPath(std::string &srcPath) +{ + if (!Extension::abilityInfo_->isModuleJson) { + /* temporary compatibility api8 + config.json */ + srcPath.append(Extension::abilityInfo_->package); + srcPath.append("/assets/js/"); + if (!Extension::abilityInfo_->srcPath.empty()) { + srcPath.append(Extension::abilityInfo_->srcPath); + } + srcPath.append("/").append(Extension::abilityInfo_->name).append(".abc"); + return; + } + + if (!Extension::abilityInfo_->srcEntrance.empty()) { + srcPath.append(Extension::abilityInfo_->moduleName + "/"); + srcPath.append(Extension::abilityInfo_->srcEntrance); + srcPath.erase(srcPath.rfind('.')); + srcPath.append(".abc"); + } +} + +bool JsFormExtension::UnwrapRawImageDataMap(NativeEngine& engine, NativeValue* argv, + std::map& rawImageDataMap) +{ + HILOG_INFO("%{public}s called.", __func__); + auto env = reinterpret_cast(&engine); + auto param = reinterpret_cast(argv); + + if (!IsTypeForNapiValue(env, param, napi_object)) { + 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); + HILOG_INFO("%{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 = UnwrapStringFromJS(env, jsProName); + HILOG_INFO("%{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 = UnwrapInt32FromJS(env, jsProValue); + rawImageDataMap.emplace(strProName, natValue); + HILOG_INFO("%{public}s called. Property value=%{public}d.", __func__, natValue); + } + + return true; +} } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/js_datashare_ext_ability.cpp b/frameworks/kits/ability/native/src/js_datashare_ext_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ced5009c6b6d6ab87876e7451101769abf539161 --- /dev/null +++ b/frameworks/kits/ability/native/src/js_datashare_ext_ability.cpp @@ -0,0 +1,615 @@ +/* + * 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 + * + * 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_datashare_ext_ability.h" + +#include "ability_info.h" +#include "datashare_stub_impl.h" +#include "hilog_wrapper.h" +#include "js_datashare_ext_ability_context.h" +#include "js_runtime.h" +#include "js_runtime_utils.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "napi_common_util.h" +#include "napi_common_want.h" +#include "napi_remote_object.h" + +namespace OHOS { +namespace AbilityRuntime { +namespace { +constexpr size_t ARGC_ONE = 1; +constexpr size_t ARGC_TWO = 2; +constexpr size_t ARGC_THREE = 3; +#if BINDER_IPC_32BIT +const std::string LIB_RDB_PATH = "/system/lib/module/data/librdb.z.so"; +const std::string LIB_DATA_ABILITY_PATH = "/system/lib/module/data/libdataability.z.so"; +#else +const std::string LIB_RDB_PATH = "/system/lib64/module/data/librdb.z.so"; +const std::string LIB_DATA_ABILITY_PATH = "/system/lib64/module/data/libdataability.z.so"; +#endif +} + +using namespace OHOS::AppExecFwk; +JsDataShareExtAbility* JsDataShareExtAbility::Create(const std::unique_ptr& runtime) +{ + return new JsDataShareExtAbility(static_cast(*runtime)); +} + +JsDataShareExtAbility::JsDataShareExtAbility(JsRuntime& jsRuntime) : jsRuntime_(jsRuntime) {} + +JsDataShareExtAbility::~JsDataShareExtAbility() +{ + UnloadLibrary(); +} + +void JsDataShareExtAbility::Init(const std::shared_ptr &record, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + DataShareExtAbility::Init(record, application, handler, token); + std::string srcPath = ""; + GetSrcPath(srcPath); + if (srcPath.empty()) { + HILOG_ERROR("Failed to get srcPath"); + return; + } + + std::string moduleName(Extension::abilityInfo_->moduleName); + moduleName.append("::").append(abilityInfo_->name); + HILOG_INFO("JsDataShareExtAbility::Init module:%{public}s, srcPath:%{public}s.", + moduleName.c_str(), srcPath.c_str()); + HandleScope handleScope(jsRuntime_); + auto& engine = jsRuntime_.GetNativeEngine(); + + jsObj_ = jsRuntime_.LoadModule(moduleName, srcPath); + if (jsObj_ == nullptr) { + HILOG_ERROR("Failed to get jsObj_"); + return; + } + HILOG_INFO("JsDataShareExtAbility::Init ConvertNativeValueTo."); + NativeObject* obj = ConvertNativeValueTo(jsObj_->Get()); + if (obj == nullptr) { + HILOG_ERROR("Failed to get JsDataShareExtAbility object"); + return; + } + + LoadLibrary(); + + auto context = GetContext(); + if (context == nullptr) { + HILOG_ERROR("Failed to get context"); + return; + } + HILOG_INFO("JsDataShareExtAbility::Init CreateJsDataShareExtAbilityContext."); + NativeValue* contextObj = CreateJsDataShareExtAbilityContext(engine, context); + auto contextRef = jsRuntime_.LoadSystemModule("application.DataShareExtAbilityContext", &contextObj, ARGC_ONE); + contextObj = contextRef->Get(); + HILOG_INFO("JsDataShareExtAbility::Init Bind."); + context->Bind(jsRuntime_, contextRef.release()); + HILOG_INFO("JsDataShareExtAbility::SetProperty."); + obj->SetProperty("context", contextObj); + + auto nativeObj = ConvertNativeValueTo(contextObj); + if (nativeObj == nullptr) { + HILOG_ERROR("Failed to get datashare extension ability native object"); + return; + } + + HILOG_INFO("Set datashare extension ability context pointer: %{public}p", context.get()); + + nativeObj->SetNativePointer(new std::weak_ptr(context), + [](NativeEngine*, void* data, void*) { + HILOG_INFO("Finalizer for weak_ptr datashare extension ability context is called"); + delete static_cast*>(data); + }, nullptr); + + HILOG_INFO("JsDataShareExtAbility::Init end."); +} + +void JsDataShareExtAbility::LoadLibrary() +{ + libRdbHandle_ = dlopen(LIB_RDB_PATH.c_str(), RTLD_LAZY); + if (libRdbHandle_ == nullptr) { + HILOG_ERROR("dlopen failed: %{public}s", dlerror()); + } + + rdbValueBucketNewInstance_ = reinterpret_cast( + dlsym(libRdbHandle_, "NAPI_OHOS_Data_RdbJsKit_ValuesBucketProxy_NewInstance")); + if (rdbValueBucketNewInstance_ == nullptr) { + HILOG_ERROR("symbol not found: %{public}s", dlerror()); + } + + rdbResultSetProxyGetNativeObject_ = reinterpret_cast( + dlsym(libRdbHandle_, "NAPI_OHOS_Data_RdbJsKit_ResultSetProxy_GetNativeObject")); + if (rdbResultSetProxyGetNativeObject_ == nullptr) { + HILOG_ERROR("symbol not found: %{public}s", dlerror()); + } + + libDataAbilityHandle_ = dlopen(LIB_DATA_ABILITY_PATH.c_str(), RTLD_LAZY); + if (libDataAbilityHandle_ == nullptr) { + HILOG_ERROR("dlopen failed: %{public}s", dlerror()); + } + + dataAbilityPredicatesNewInstance_ = reinterpret_cast( + dlsym(libDataAbilityHandle_, "NAPI_OHOS_Data_DataAbilityJsKit_DataAbilityPredicatesProxy_NewInstance")); + if (dataAbilityPredicatesNewInstance_ == nullptr) { + HILOG_ERROR("symbol not found: %{public}s", dlerror()); + } +} + +void JsDataShareExtAbility::UnloadLibrary() +{ + if (libRdbHandle_ != nullptr) { + dlclose(libRdbHandle_); + } + if (libDataAbilityHandle_ != nullptr) { + dlclose(libDataAbilityHandle_); + } +} + +void JsDataShareExtAbility::OnStart(const AAFwk::Want &want) +{ + Extension::OnStart(want); + HILOG_INFO("%{public}s begin.", __func__); + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + napi_value napiWant = OHOS::AppExecFwk::WrapWant(env, want); + NativeValue* nativeWant = reinterpret_cast(napiWant); + NativeValue* argv[] = {nativeWant}; + CallObjectMethod("onCreate", argv, ARGC_ONE); + HILOG_INFO("%{public}s end.", __func__); +} + +sptr JsDataShareExtAbility::OnConnect(const AAFwk::Want &want) +{ + Extension::OnConnect(want); + HILOG_INFO("%{public}s begin.", __func__); + sptr remoteObject = new (std::nothrow) DataShareStubImpl( + std::static_pointer_cast(shared_from_this())); + HILOG_INFO("%{public}s end. ", __func__); + return remoteObject->AsObject(); +} + +NativeValue* JsDataShareExtAbility::CallObjectMethod(const char* name, NativeValue* const* argv, size_t argc) +{ + HILOG_INFO("JsDataShareExtAbility::CallObjectMethod(%{public}s), begin", name); + + if (!jsObj_) { + HILOG_WARN("Not found DataShareExtAbility.js"); + return nullptr; + } + + HandleScope handleScope(jsRuntime_); + auto& nativeEngine = jsRuntime_.GetNativeEngine(); + + NativeValue* value = jsObj_->Get(); + NativeObject* obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + HILOG_ERROR("Failed to get DataShareExtAbility object"); + return nullptr; + } + + NativeValue* method = obj->GetProperty(name); + if (method == nullptr) { + HILOG_ERROR("Failed to get '%{public}s' from DataShareExtAbility object", name); + return nullptr; + } + HILOG_INFO("JsDataShareExtAbility::CallFunction(%{public}s), success", name); + return nativeEngine.CallFunction(value, method, argv, argc); +} + +void JsDataShareExtAbility::GetSrcPath(std::string &srcPath) +{ + if (!Extension::abilityInfo_->isStageBasedModel) { + /* temporary compatibility api8 + config.json */ + srcPath.append(Extension::abilityInfo_->package); + srcPath.append("/assets/js/"); + if (!Extension::abilityInfo_->srcPath.empty()) { + srcPath.append(Extension::abilityInfo_->srcPath); + } + srcPath.append("/").append(Extension::abilityInfo_->name).append(".abc"); + return; + } + + if (!Extension::abilityInfo_->srcEntrance.empty()) { + srcPath.append(Extension::abilityInfo_->moduleName + "/"); + srcPath.append(Extension::abilityInfo_->srcEntrance); + srcPath.erase(srcPath.rfind('.')); + srcPath.append(".abc"); + } +} + +std::vector JsDataShareExtAbility::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) +{ + auto ret = DataShareExtAbility::GetFileTypes(uri, mimeTypeFilter); + HILOG_INFO("%{public}s begin.", __func__); + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + + napi_value napiUri = nullptr; + napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); + napi_value napiMimeTypeFilter = nullptr; + napi_create_string_utf8(env, mimeTypeFilter.c_str(), NAPI_AUTO_LENGTH, &napiMimeTypeFilter); + + NativeValue* nativeUri = reinterpret_cast(napiUri); + NativeValue* nativeMimeTypeFilter = reinterpret_cast(napiMimeTypeFilter); + NativeValue* argv[] = {nativeUri, nativeMimeTypeFilter}; + NativeValue* nativeResult = CallObjectMethod("getFileTypes", argv, ARGC_TWO); + if (nativeResult == nullptr) { + HILOG_ERROR("%{public}s call getFileTypes with return null.", __func__); + return ret; + } + + if (!OHOS::AppExecFwk::UnwrapArrayStringFromJS(env, reinterpret_cast(nativeResult), ret)) { + HILOG_ERROR("%{public}s call UnwrapArrayStringFromJS failed", __func__); + return ret; + } + + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +int JsDataShareExtAbility::OpenFile(const Uri &uri, const std::string &mode) +{ + auto ret = DataShareExtAbility::OpenFile(uri, mode); + HILOG_INFO("%{public}s begin.", __func__); + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + + napi_value napiUri = nullptr; + napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); + napi_value napiMode = nullptr; + napi_create_string_utf8(env, mode.c_str(), NAPI_AUTO_LENGTH, &napiMode); + + NativeValue* nativeUri = reinterpret_cast(napiUri); + NativeValue* nativeMode = reinterpret_cast(napiMode); + NativeValue* argv[] = {nativeUri, nativeMode}; + NativeValue* nativeResult = CallObjectMethod("openFile", argv, ARGC_TWO); + if (nativeResult == nullptr) { + HILOG_ERROR("%{public}s call openFile with return null.", __func__); + return ret; + } + + ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast(nativeResult)); + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +int JsDataShareExtAbility::OpenRawFile(const Uri &uri, const std::string &mode) +{ + auto ret = DataShareExtAbility::OpenRawFile(uri, mode); + HILOG_INFO("%{public}s begin.", __func__); + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + + napi_value napiUri = nullptr; + napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); + napi_value napiMode = nullptr; + napi_create_string_utf8(env, mode.c_str(), NAPI_AUTO_LENGTH, &napiMode); + + NativeValue* nativeUri = reinterpret_cast(napiUri); + NativeValue* nativeMode = reinterpret_cast(napiMode); + NativeValue* argv[] = {nativeUri, nativeMode}; + NativeValue* nativeResult = CallObjectMethod("openRawFile", argv, ARGC_TWO); + if (nativeResult == nullptr) { + HILOG_ERROR("%{public}s call openRawFile with return null.", __func__); + return ret; + } + + ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast(nativeResult)); + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +int JsDataShareExtAbility::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) +{ + auto ret = DataShareExtAbility::Insert(uri, value); + HILOG_INFO("%{public}s begin.", __func__); + if (rdbValueBucketNewInstance_ == nullptr) { + HILOG_ERROR("%{public}s invalid instance of rdb value bucket.", __func__); + return ret; + } + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + napi_value napiUri = nullptr; + napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); + napi_value napiValue = rdbValueBucketNewInstance_(env, const_cast(value)); + + NativeValue* nativeUri = reinterpret_cast(napiUri); + NativeValue* nativeValue = reinterpret_cast(napiValue); + NativeValue* argv[] = {nativeUri, nativeValue}; + NativeValue* nativeResult = CallObjectMethod("insert", argv, ARGC_TWO); + if (nativeResult == nullptr) { + HILOG_ERROR("%{public}s call insert with return null.", __func__); + return ret; + } + + ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast(nativeResult)); + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +int JsDataShareExtAbility::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, + const NativeRdb::DataAbilityPredicates &predicates) +{ + auto ret = DataShareExtAbility::Update(uri, value, predicates); + HILOG_INFO("%{public}s begin.", __func__); + if (rdbValueBucketNewInstance_ == nullptr) { + HILOG_ERROR("%{public}s invalid instance of ValuesBucket.", __func__); + return ret; + } + if (dataAbilityPredicatesNewInstance_ == nullptr) { + HILOG_ERROR("%{public}s invalid instance of DataAbilityPredicates.", __func__); + return ret; + } + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + napi_value napiUri = nullptr; + napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); + napi_value napiValue = rdbValueBucketNewInstance_(env, const_cast(value)); + + OHOS::NativeRdb::DataAbilityPredicates* predicatesPtr = new OHOS::NativeRdb::DataAbilityPredicates(); + *predicatesPtr = predicates; + napi_value napiPredicates = dataAbilityPredicatesNewInstance_(env, predicatesPtr); + + NativeValue* nativeUri = reinterpret_cast(napiUri); + NativeValue* nativeValue = reinterpret_cast(napiValue); + NativeValue* nativePredicates = reinterpret_cast(napiPredicates); + NativeValue* argv[] = {nativeUri, nativeValue, nativePredicates}; + NativeValue* nativeResult = CallObjectMethod("update", argv, ARGC_THREE); + if (nativeResult == nullptr) { + HILOG_ERROR("%{public}s call update with return null.", __func__); + return ret; + } + + ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast(nativeResult)); + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +int JsDataShareExtAbility::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) +{ + auto ret = DataShareExtAbility::Delete(uri, predicates); + HILOG_INFO("%{public}s begin.", __func__); + if (rdbValueBucketNewInstance_ == nullptr) { + HILOG_ERROR("%{public}s invalid instance of ValuesBucket.", __func__); + return ret; + } + if (dataAbilityPredicatesNewInstance_ == nullptr) { + HILOG_ERROR("%{public}s invalid instance of DataAbilityPredicates.", __func__); + return ret; + } + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + napi_value napiUri = nullptr; + napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); + + OHOS::NativeRdb::DataAbilityPredicates* predicatesPtr = new OHOS::NativeRdb::DataAbilityPredicates(); + *predicatesPtr = predicates; + napi_value napiPredicates = dataAbilityPredicatesNewInstance_(env, predicatesPtr); + + NativeValue* nativeUri = reinterpret_cast(napiUri); + NativeValue* nativePredicates = reinterpret_cast(napiPredicates); + NativeValue* argv[] = {nativeUri, nativePredicates}; + NativeValue* nativeResult = CallObjectMethod("delete", argv, ARGC_TWO); + if (nativeResult == nullptr) { + HILOG_ERROR("%{public}s call delete with return null.", __func__); + return ret; + } + + ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast(nativeResult)); + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +std::shared_ptr JsDataShareExtAbility::Query(const Uri &uri, + std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) +{ + auto ret = DataShareExtAbility::Query(uri, columns, predicates); + HILOG_INFO("%{public}s begin.", __func__); + if (rdbValueBucketNewInstance_ == nullptr) { + HILOG_ERROR("%{public}s invalid instance of ValuesBucket.", __func__); + return ret; + } + if (dataAbilityPredicatesNewInstance_ == nullptr) { + HILOG_ERROR("%{public}s invalid instance of DataAbilityPredicates.", __func__); + return ret; + } + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + napi_value napiUri = nullptr; + napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); + + napi_value napiColumns = nullptr; + napi_create_array(env, &napiColumns); + bool isArray = false; + if (napi_is_array(env, napiColumns, &isArray) != napi_ok || !isArray) { + HILOG_ERROR("JsDataShareExtAbility create array failed"); + return ret; + } + int32_t index = 0; + for (const auto &column : columns) { + napi_value result = nullptr; + napi_create_string_utf8(env, column.c_str(), column.length(), &result); + napi_set_element(env, napiColumns, index++, result); + } + + OHOS::NativeRdb::DataAbilityPredicates* predicatesPtr = new OHOS::NativeRdb::DataAbilityPredicates(); + *predicatesPtr = predicates; + napi_value napiPredicates = dataAbilityPredicatesNewInstance_(env, predicatesPtr); + + NativeValue* nativeUri = reinterpret_cast(napiUri); + NativeValue* nativeColumns = reinterpret_cast(napiColumns); + NativeValue* nativePredicates = reinterpret_cast(napiPredicates); + NativeValue* argv[] = {nativeUri, nativeColumns, nativePredicates}; + NativeValue* nativeResult = CallObjectMethod("query", argv, ARGC_THREE); + if (nativeResult == nullptr) { + HILOG_ERROR("%{public}s call query with return null.", __func__); + return ret; + } + + auto nativeObject = rdbResultSetProxyGetNativeObject_(env, reinterpret_cast(nativeResult)); + if (nativeObject == nullptr) { + HILOG_ERROR("JsiPaEngine AbsSharedResultSet from JS to Native failed"); + return ret; + } + + ret.reset(nativeObject); + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +std::string JsDataShareExtAbility::GetType(const Uri &uri) +{ + auto ret = DataShareExtAbility::GetType(uri); + HILOG_INFO("%{public}s begin.", __func__); + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + + napi_value napiUri = nullptr; + napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, + &napiUri); + NativeValue* nativeUri = reinterpret_cast(napiUri); + NativeValue* argv[] = {nativeUri}; + NativeValue* nativeResult = CallObjectMethod("getType", argv, ARGC_ONE); + if (nativeResult == nullptr) { + HILOG_ERROR("%{public}s call getType with return null.", __func__); + return ret; + } + + ret = OHOS::AppExecFwk::UnwrapStringFromJS(env, reinterpret_cast(nativeResult)); + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +int JsDataShareExtAbility::BatchInsert(const Uri &uri, const std::vector &values) +{ + auto ret = DataShareExtAbility::BatchInsert(uri, values); + HILOG_INFO("%{public}s begin.", __func__); + if (rdbValueBucketNewInstance_ == nullptr) { + HILOG_ERROR("%{public}s invalid instance of rdb value bucket.", __func__); + return ret; + } + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + napi_value napiUri = nullptr; + napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); + + napi_value napiValues = nullptr; + napi_create_array(env, &napiValues); + bool isArray = false; + if (napi_is_array(env, napiValues, &isArray) != napi_ok || !isArray) { + HILOG_ERROR("JsDataShareExtAbility create array failed"); + return ret; + } + int32_t index = 0; + for (const auto &value : values) { + napi_value result = rdbValueBucketNewInstance_(env, const_cast(value)); + napi_set_element(env, napiValues, index++, result); + } + + NativeValue* nativeUri = reinterpret_cast(napiUri); + NativeValue* nativeValues = reinterpret_cast(napiValues); + NativeValue* argv[] = {nativeUri, nativeValues}; + NativeValue* nativeResult = CallObjectMethod("batchInsert", argv, ARGC_TWO); + if (nativeResult == nullptr) { + HILOG_ERROR("%{public}s call batchInsert with return null.", __func__); + return ret; + } + + ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast(nativeResult)); + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +bool JsDataShareExtAbility::RegisterObserver(const Uri &uri, const sptr &dataObserver) +{ + DataShareExtAbility::RegisterObserver(uri, dataObserver); + HILOG_INFO("%{public}s begin.", __func__); + HILOG_INFO("%{public}s end.", __func__); + return true; +} + +bool JsDataShareExtAbility::UnregisterObserver(const Uri &uri, const sptr &dataObserver) +{ + DataShareExtAbility::UnregisterObserver(uri, dataObserver); + HILOG_INFO("%{public}s begin.", __func__); + HILOG_INFO("%{public}s end.", __func__); + return true; +} + +bool JsDataShareExtAbility::NotifyChange(const Uri &uri) +{ + auto ret = DataShareExtAbility::NotifyChange(uri); + HILOG_INFO("%{public}s begin.", __func__); + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +Uri JsDataShareExtAbility::NormalizeUri(const Uri &uri) +{ + auto ret = DataShareExtAbility::NormalizeUri(uri); + HILOG_INFO("%{public}s begin.", __func__); + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + + napi_value napiUri = nullptr; + napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); + NativeValue* nativeUri = reinterpret_cast(napiUri); + NativeValue* argv[] = {nativeUri}; + NativeValue* nativeResult = CallObjectMethod("normalizeUri", argv, ARGC_ONE); + if (nativeResult == nullptr) { + HILOG_ERROR("%{public}s call normalizeUri with return null.", __func__); + return ret; + } + + ret = Uri(OHOS::AppExecFwk::UnwrapStringFromJS(env, reinterpret_cast(nativeResult))); + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +Uri JsDataShareExtAbility::DenormalizeUri(const Uri &uri) +{ + auto ret = DataShareExtAbility::DenormalizeUri(uri); + HILOG_INFO("%{public}s begin.", __func__); + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + + napi_value napiUri = nullptr; + napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); + NativeValue* nativeUri = reinterpret_cast(napiUri); + NativeValue* argv[] = {nativeUri}; + NativeValue* nativeResult = CallObjectMethod("denormalizeUri", argv, ARGC_ONE); + if (nativeResult == nullptr) { + HILOG_ERROR("%{public}s call denormalizeUri with return null.", __func__); + return ret; + } + + ret = Uri(OHOS::AppExecFwk::UnwrapStringFromJS(env, reinterpret_cast(nativeResult))); + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +std::vector> JsDataShareExtAbility::ExecuteBatch( + const std::vector> &operations) +{ + auto ret = DataShareExtAbility::ExecuteBatch(operations); + HILOG_INFO("%{public}s begin.", __func__); + HILOG_INFO("%{public}s end.", __func__); + return ret; +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/js_datashare_ext_ability_context.cpp b/frameworks/kits/ability/native/src/js_datashare_ext_ability_context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8315494577b340c6622b57690b1f3021cf2ab3a1 --- /dev/null +++ b/frameworks/kits/ability/native/src/js_datashare_ext_ability_context.cpp @@ -0,0 +1,61 @@ +/* + * 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 + * + * 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_datashare_ext_ability_context.h" + +#include + +#include "hilog_wrapper.h" +#include "js_extension_context.h" +#include "js_runtime.h" +#include "js_runtime_utils.h" +#include "napi/native_api.h" +#include "napi_common_want.h" +#include "napi_remote_object.h" +#include "napi_common_start_options.h" +#include "start_options.h" + +namespace OHOS { +namespace AbilityRuntime { +namespace { +class JsDataShareExtAbilityContext final { +public: + explicit JsDataShareExtAbilityContext(const std::shared_ptr& context) + : context_(context) {} + ~JsDataShareExtAbilityContext() = default; + + static void Finalizer(NativeEngine* engine, void* data, void* hint) + { + HILOG_INFO("JsAbilityContext::Finalizer is called"); + std::unique_ptr(static_cast(data)); + } +private: + std::weak_ptr context_; +}; +} // namespace + +NativeValue* CreateJsDataShareExtAbilityContext(NativeEngine& engine, + std::shared_ptr context) +{ + HILOG_INFO("CreateJsDataShareExtAbilityContext begin"); + NativeValue* objValue = CreateJsExtensionContext(engine, context); + NativeObject* object = ConvertNativeValueTo(objValue); + + std::unique_ptr jsContext = std::make_unique(context); + object->SetNativePointer(jsContext.release(), JsDataShareExtAbilityContext::Finalizer, nullptr); + return objValue; +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/js_service_extension.cpp b/frameworks/kits/ability/native/src/js_service_extension.cpp index ae325209df9c54b4ec81aa1d5f579a2ae1fb25ca..558599713d9942ae8b67f297ce9b40ea05e88e82 100755 --- a/frameworks/kits/ability/native/src/js_service_extension.cpp +++ b/frameworks/kits/ability/native/src/js_service_extension.cpp @@ -16,6 +16,7 @@ #include "js_service_extension.h" #include "ability_info.h" +#include "bytrace.h" #include "hilog_wrapper.h" #include "js_runtime.h" #include "js_runtime_utils.h" @@ -129,6 +130,7 @@ void JsServiceExtension::OnStop() sptr JsServiceExtension::OnConnect(const AAFwk::Want &want) { + BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); Extension::OnConnect(want); HILOG_INFO("%{public}s begin.", __func__); HandleScope handleScope(jsRuntime_); @@ -168,6 +170,7 @@ sptr JsServiceExtension::OnConnect(const AAFwk::Want &want) void JsServiceExtension::OnDisconnect(const AAFwk::Want &want) { + BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); Extension::OnDisconnect(want); HILOG_INFO("%{public}s begin.", __func__); HandleScope handleScope(jsRuntime_); diff --git a/frameworks/kits/ability/native/src/js_service_extension_context.cpp b/frameworks/kits/ability/native/src/js_service_extension_context.cpp index fdc124980ea35aca416b45de4adcf063f32b12e0..11827c2589a38f70dbe54ba99f04ca157c0ebdfa 100755 --- a/frameworks/kits/ability/native/src/js_service_extension_context.cpp +++ b/frameworks/kits/ability/native/src/js_service_extension_context.cpp @@ -91,7 +91,6 @@ public: } private: std::weak_ptr context_; - NativeValue* OnStartAbility(NativeEngine& engine, NativeCallbackInfo& info) { HILOG_INFO("OnStartAbility is called"); diff --git a/frameworks/kits/ability/native/src/new_ability_impl.cpp b/frameworks/kits/ability/native/src/new_ability_impl.cpp index 55638e5532d00a31bfabd569e41334c3487e1467..14408a52073b5b0236845277babf1ccee5c32bad 100644 --- a/frameworks/kits/ability/native/src/new_ability_impl.cpp +++ b/frameworks/kits/ability/native/src/new_ability_impl.cpp @@ -30,10 +30,11 @@ using AbilityManagerClient = OHOS::AAFwk::AbilityManagerClient; void NewAbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState) { APP_LOGI("NewAbilityImpl::HandleAbilityTransaction begin sourceState:%{public}d; targetState: %{public}d; " - "isNewWant: %{public}d", + "isNewWant: %{public}d, sceneFlag: %{public}d", lifecycleState_, targetState.state, - targetState.isNewWant); + targetState.isNewWant, + targetState.sceneFlag); if ((lifecycleState_ == targetState.state) && !targetState.isNewWant) { APP_LOGE("Org lifeCycleState equals to Dst lifeCycleState."); return; @@ -48,6 +49,9 @@ void NewAbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::Lif CheckAndRestore(); } + if (ability_ != nullptr) { + ability_->sceneFlag_ = targetState.sceneFlag; + } bool ret = false; ret = AbilityTransaction(want, targetState); if (ret) { diff --git a/frameworks/kits/ability/native/src/page_ability_impl.cpp b/frameworks/kits/ability/native/src/page_ability_impl.cpp index 34db10aae3b5d87250210e49ca8d738de7e9fdb5..71e13ba0334dd3e467a19029a7cb8b1bf6acdf0d 100644 --- a/frameworks/kits/ability/native/src/page_ability_impl.cpp +++ b/frameworks/kits/ability/native/src/page_ability_impl.cpp @@ -30,10 +30,11 @@ void PageAbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::Li { AbilityImpl::SetUseNewMission(targetState.useNewMission); APP_LOGI("PageAbilityImpl::HandleAbilityTransaction begin sourceState:%{public}d; targetState: %{public}d; " - "isNewWant: %{public}d", + "isNewWant: %{public}d, sceneFlag: %{public}d", lifecycleState_, targetState.state, - targetState.isNewWant); + targetState.isNewWant, + targetState.sceneFlag); if ((lifecycleState_ == targetState.state) && !targetState.isNewWant) { APP_LOGE("Org lifeCycleState equals to Dst lifeCycleState."); return; @@ -57,6 +58,9 @@ void PageAbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::Li } bool ret = false; + if (ability_ != nullptr) { + ability_->sceneFlag_ = targetState.sceneFlag; + } if (AbilityImpl::IsUseNewMission()) { ret = AbilityTransactionNew(want, targetState); } else { diff --git a/frameworks/kits/ability/native/test/BUILD.gn b/frameworks/kits/ability/native/test/BUILD.gn index 308908f88963a3bdf5e0cced6d715db3581f0010..9a13247f8399db6e6377c1acab4d1c28cea42367 100644 --- a/frameworks/kits/ability/native/test/BUILD.gn +++ b/frameworks/kits/ability/native/test/BUILD.gn @@ -105,7 +105,7 @@ ohos_unittest("ability_test") { "${INNERKITS_PATH}/base:base", "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", - "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", @@ -209,7 +209,7 @@ ohos_unittest("ability_context_for_task_dispacher_test") { deps = [ "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", - "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", @@ -480,7 +480,7 @@ ohos_unittest("ability_impl_active_test") { deps = [ "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", - "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", @@ -518,7 +518,7 @@ ohos_unittest("ability_impl_test") { "${INNERKITS_PATH}/want:want", "//base/global/i18n_standard/frameworks/intl:intl_util", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", - "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", @@ -569,7 +569,7 @@ ohos_unittest("ability_thread_test") { deps = [ "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", - "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", @@ -660,7 +660,7 @@ ohos_unittest("data_ability_impl_test") { "${INNERKITS_PATH}/base:base", "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", - "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", @@ -708,7 +708,7 @@ ohos_unittest("data_ability_impl_file_secondpart_test") { "${INNERKITS_PATH}/base:base", "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", - "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", @@ -756,7 +756,7 @@ ohos_unittest("data_ability_impl_file_test") { "${INNERKITS_PATH}/base:base", "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", - "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", @@ -805,7 +805,7 @@ ohos_unittest("ability_thread_dataability_test") { deps = [ "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", - "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", @@ -1018,7 +1018,7 @@ ohos_unittest("form_host_client_test") { deps = [ "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", - "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", @@ -1060,7 +1060,7 @@ ohos_unittest("continuation_test") { deps = [ "${INNERKITS_PATH}/want:want", "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", - "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", diff --git a/frameworks/kits/appkit/BUILD.gn b/frameworks/kits/appkit/BUILD.gn index d91dfff8a08b36379f27d1b1ad433d8da9679d28..372c6a06c4623140762b0b593ec1e119cda0cb84 100644 --- a/frameworks/kits/appkit/BUILD.gn +++ b/frameworks/kits/appkit/BUILD.gn @@ -29,6 +29,7 @@ config("appkit_config") { "${aafwk_path}/frameworks/kits/ability/native/include", "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", "//third_party/json/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", ] } @@ -148,7 +149,7 @@ ohos_shared_library("appkit_native") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ - "${aafwk_path}/common/task_dispatcher:appkit_dispatcher_td", + "${aafwk_path}/common/task_dispatcher:task_dispatcher", "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", "${aafwk_path}/frameworks/kits/appkit:app_context", "${aafwk_path}/interfaces/innerkits/ability_manager:ability_manager", @@ -218,9 +219,10 @@ ohos_shared_library("app_context") { "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", # "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", - "${aafwk_path}/common/task_dispatcher:appkit_dispatcher_td", + "${aafwk_path}/common/task_dispatcher:task_dispatcher", "${aafwk_path}/interfaces/innerkits/ability_manager:ability_manager", "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//base/hiviewdfx/hiview/adapter/utility:hiview_adapter_utility", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/multimodalinput/input/frameworks/proxy:libmmi-client", @@ -239,6 +241,7 @@ ohos_shared_library("app_context") { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "napi:ace_napi", + "resmgr_standard:resmgr_napi_core", ] part_name = "ability_runtime" diff --git a/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator.cpp b/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator.cpp index 2126710309487fe0e80ab1a48afad7f540b2ee93..471cda75eba6e0f6cb6eee630d37cf392ca58898 100644 --- a/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator.cpp +++ b/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator.cpp @@ -550,7 +550,7 @@ sptr AbilityDelegator::GetAbilityToken(const std::shared_ptrGetAbilityToken(); + return abilityContext->GetToken(); } std::optional AbilityDelegator::DoesPropertyExist(const sptr &token) diff --git a/frameworks/kits/appkit/native/ability_runtime/context/context.h b/frameworks/kits/appkit/native/ability_runtime/context/context.h index c2ae9a9b18a3f28bd11808a288f15de618f3d119..743fcecbf3cbdfcd781ae30a1d2381dd898b1557 100755 --- a/frameworks/kits/appkit/native/ability_runtime/context/context.h +++ b/frameworks/kits/appkit/native/ability_runtime/context/context.h @@ -22,8 +22,11 @@ #include "application_info.h" #include "bindable.h" #include "hap_module_info.h" +#include "foundation/communication/ipc/interfaces/innerkits/ipc_core/include/iremote_object.h" #include "resource_manager.h" +using IRemoteObject = OHOS::IRemoteObject; + namespace OHOS { namespace AbilityRuntime { class Context : public Bindable { @@ -137,6 +140,20 @@ public: */ virtual std::string GetDistributedFilesDir() = 0; + /** + * @brief Obtains token. + * + * @return Returns the token. + */ + virtual sptr GetToken() = 0; + + /** + * @brief Attachs ability's token. + * + * @param token The token represents ability. + */ + virtual void SetToken(const sptr &token) = 0; + /** * @brief Switch file area * diff --git a/frameworks/kits/appkit/native/ability_runtime/context/context_impl.cpp b/frameworks/kits/appkit/native/ability_runtime/context/context_impl.cpp index b3d253f3870c187d23e3148342aa65986ce86625..aa056ea239e6e549acbc434bcffb9452a2232902 100644 --- a/frameworks/kits/appkit/native/ability_runtime/context/context_impl.cpp +++ b/frameworks/kits/appkit/native/ability_runtime/context/context_impl.cpp @@ -15,8 +15,10 @@ #include "context_impl.h" +#include "file_util.h" #include "hilog_wrapper.h" #include "ipc_singleton.h" +#include "js_runtime_utils.h" #include "locale_config.h" #include "os_account_manager.h" #include "sys_mgr_client.h" @@ -60,6 +62,7 @@ std::string ContextImpl::GetBundleCodeDir() } else { dir = CONTEXT_DATA_STORAGE + CONTEXT_ELS[0] + CONTEXT_BUNDLE; } + CreateDirIfNotExist(dir); HILOG_DEBUG("ContextImpl::GetBundleCodeDir:%{public}s", dir.c_str()); return dir; } @@ -67,6 +70,7 @@ std::string ContextImpl::GetBundleCodeDir() std::string ContextImpl::GetCacheDir() { std::string dir = GetBaseDir() + CONTEXT_PRIVATE + CONTEXT_CACHES; + CreateDirIfNotExist(dir); HILOG_DEBUG("ContextImpl::GetCacheDir:%{public}s", dir.c_str()); return dir; } @@ -81,6 +85,7 @@ std::string ContextImpl::GetDatabaseDir() dir = CONTEXT_DATA_STORAGE + currArea_ + CONTEXT_FILE_SEPARATOR + CONTEXT_DATABASE; } dir = dir + CONTEXT_FILE_SEPARATOR + ((GetHapModuleInfo() == nullptr) ? "" : GetHapModuleInfo()->moduleName); + CreateDirIfNotExist(dir); HILOG_DEBUG("ContextImpl::GetDatabaseDir:%{public}s", dir.c_str()); return dir; } @@ -88,6 +93,7 @@ std::string ContextImpl::GetDatabaseDir() std::string ContextImpl::GetStorageDir() { std::string dir = GetBaseDir() + CONTEXT_PRIVATE + CONTEXT_STORAGE; + CreateDirIfNotExist(dir); HILOG_DEBUG("ContextImpl::GetStorageDir:%{public}s", dir.c_str()); return dir; } @@ -95,6 +101,7 @@ std::string ContextImpl::GetStorageDir() std::string ContextImpl::GetTempDir() { std::string dir = GetBaseDir() + CONTEXT_TEMP; + CreateDirIfNotExist(dir); HILOG_DEBUG("ContextImpl::GetTempDir:%{public}s", dir.c_str()); return dir; } @@ -102,6 +109,7 @@ std::string ContextImpl::GetTempDir() std::string ContextImpl::GetFilesDir() { std::string dir = GetBaseDir() + CONTEXT_FILES; + CreateDirIfNotExist(dir); HILOG_DEBUG("ContextImpl::GetFilesDir:%{public}s", dir.c_str()); return dir; } @@ -117,6 +125,7 @@ std::string ContextImpl::GetDistributedFilesDir() dir = CONTEXT_DATA_STORAGE + currArea_ + CONTEXT_FILE_SEPARATOR + CONTEXT_DISTRIBUTEDFILES + CONTEXT_FILE_SEPARATOR + ((GetHapModuleInfo() == nullptr) ? "" : GetHapModuleInfo()->moduleName); } + CreateDirIfNotExist(dir); HILOG_DEBUG("ContextImpl::GetDistributedFilesDir:%{public}s", dir.c_str()); return dir; } @@ -159,24 +168,24 @@ int ContextImpl::GetCurrentAccountId() const int ContextImpl::GetCurrentActiveAccountId() const { - std::vector osAccountInfos; - ErrCode ret = AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(osAccountInfos); + std::vector accountIds; + ErrCode ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(accountIds); if (ret != ERR_OK) { HILOG_ERROR("ContextImpl::GetCurrentActiveAccountId error."); return 0; } - if (osAccountInfos.size() == 0) { + if (accountIds.size() == 0) { HILOG_ERROR("ContextImpl::GetCurrentActiveAccountId error, no accounts."); return 0; } - if (osAccountInfos.size() > 1) { + if (accountIds.size() > 1) { HILOG_ERROR("ContextImpl::GetCurrentActiveAccountId error, no current now."); return 0; } - return osAccountInfos[0].GetLocalId(); + return accountIds[0]; } std::shared_ptr ContextImpl::CreateBundleContext(const std::string &bundleName) @@ -376,5 +385,31 @@ void ContextImpl::InitAppContext() std::lock_guard lock(Context::contextMutex_); Context::appContext_ = shared_from_this(); } + +void ContextImpl::SetToken(const sptr &token) +{ + if (token == nullptr) { + HILOG_DEBUG("ContextImpl::SetToken failed, application is nullptr"); + return; + } + token_ = token; +} + +sptr ContextImpl::GetToken() +{ + return token_; +} + +void ContextImpl::CreateDirIfNotExist(const std::string& dirPath) const +{ + HILOG_INFO("createDir: create directory if not exists."); + if (!OHOS::HiviewDFX::FileUtil::FileExists(dirPath)) { + bool createDir = OHOS::HiviewDFX::FileUtil::ForceCreateDirectory(dirPath); + if (!createDir) { + HILOG_ERROR("createDir: create dir %{public}s failed.", dirPath.c_str()); + return; + } + } +} } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_runtime/context/context_impl.h b/frameworks/kits/appkit/native/ability_runtime/context/context_impl.h index a6de5ba025b26f6606de409160b1c1e8cb7100c4..5b367f169431220c4d6357cc342d2ee60634abf8 100644 --- a/frameworks/kits/appkit/native/ability_runtime/context/context_impl.h +++ b/frameworks/kits/appkit/native/ability_runtime/context/context_impl.h @@ -181,6 +181,24 @@ public: * @brief Set application context */ void InitAppContext(); + + /** + * @brief Set the token witch the app launched. + * + * @param token The token which the is launched by app. + */ + void SetToken(const sptr &token) override; + + /** + * @brief Get the token witch the app launched. + * + * @return token The token which the is launched by app. + */ + sptr GetToken() override; + +protected: + sptr token_; + private: static const int64_t CONTEXT_CREATE_BY_SYSTEM_APP; static const std::string CONTEXT_DATA_APP; @@ -210,6 +228,7 @@ private: int GetCurrentAccountId() const; void SetFlags(int64_t flags); int GetCurrentActiveAccountId() const; + void CreateDirIfNotExist(const std::string& dirPath) const; std::shared_ptr applicationInfo_ = nullptr; std::shared_ptr parentContext_ = nullptr; diff --git a/frameworks/kits/appkit/native/ability_runtime/context/js_context_utils.cpp b/frameworks/kits/appkit/native/ability_runtime/context/js_context_utils.cpp index 08c265d7c6faae0b5110e5bd47955592c5a85e80..42e4be70c4d3b9c67e4b2d0b0e51f38c36993f49 100755 --- a/frameworks/kits/appkit/native/ability_runtime/context/js_context_utils.cpp +++ b/frameworks/kits/appkit/native/ability_runtime/context/js_context_utils.cpp @@ -36,6 +36,22 @@ public: static NativeValue* GetApplicationContext(NativeEngine* engine, NativeCallbackInfo* info); static NativeValue* SwitchArea(NativeEngine* engine, NativeCallbackInfo* info); + NativeValue* OnGetCacheDir(NativeEngine& engine, NativeCallbackInfo& info); + NativeValue* OnGetTempDir(NativeEngine& engine, NativeCallbackInfo& info); + NativeValue* OnGetFilesDir(NativeEngine& engine, NativeCallbackInfo& info); + NativeValue* OnGetDistributedFilesDir(NativeEngine& engine, NativeCallbackInfo& info); + NativeValue* OnGetDatabaseDir(NativeEngine& engine, NativeCallbackInfo& info); + NativeValue* OnGetStorageDir(NativeEngine& engine, NativeCallbackInfo& info); + NativeValue* OnGetBundleCodeDir(NativeEngine& engine, NativeCallbackInfo& info); + + static NativeValue* GetCacheDir(NativeEngine* engine, NativeCallbackInfo* info); + static NativeValue* GetTempDir(NativeEngine* engine, NativeCallbackInfo* info); + static NativeValue* GetFilesDir(NativeEngine* engine, NativeCallbackInfo* info); + static NativeValue* GetDistributedFilesDir(NativeEngine* engine, NativeCallbackInfo* info); + static NativeValue* GetDatabaseDir(NativeEngine* engine, NativeCallbackInfo* info); + static NativeValue* GetStorageDir(NativeEngine* engine, NativeCallbackInfo* info); + static NativeValue* GetBundleCodeDir(NativeEngine* engine, NativeCallbackInfo* info); + void KeepContext(std::shared_ptr context) { keepContext_ = context; @@ -100,17 +116,142 @@ NativeValue* JsBaseContext::OnSwitchArea(NativeEngine& engine, NativeCallbackInf NativeValue* thisVar = info.thisVar; NativeObject* object = ConvertNativeValueTo(thisVar); - object->SetProperty("cacheDir", CreateJsValue(engine, context->GetCacheDir())); - object->SetProperty("tempDir", CreateJsValue(engine, context->GetTempDir())); - object->SetProperty("filesDir", CreateJsValue(engine, context->GetFilesDir())); - object->SetProperty("distributedFilesDir", CreateJsValue(engine, context->GetDistributedFilesDir())); - object->SetProperty("databaseDir", CreateJsValue(engine, context->GetDatabaseDir())); - object->SetProperty("storageDir", CreateJsValue(engine, context->GetStorageDir())); - object->SetProperty("bundleCodeDir", CreateJsValue(engine, context->GetBundleCodeDir())); - + BindNativeProperty(*object, "cacheDir", GetCacheDir); + BindNativeProperty(*object, "tempDir", GetTempDir); + BindNativeProperty(*object, "filesDir", GetFilesDir); + BindNativeProperty(*object, "distributedFilesDir", GetDistributedFilesDir); + BindNativeProperty(*object, "databaseDir", GetDatabaseDir); + BindNativeProperty(*object, "storageDir", GetStorageDir); + BindNativeProperty(*object, "bundleCodeDir", GetBundleCodeDir); return engine.CreateUndefined(); } +NativeValue* JsBaseContext::GetCacheDir(NativeEngine* engine, NativeCallbackInfo* info) +{ + HILOG_INFO("JsBaseContext::SwitchArea is called"); + JsBaseContext* me = CheckParamsAndGetThis(engine, info, BASE_CONTEXT_NAME); + return me != nullptr ? me->OnGetCacheDir(*engine, *info) : nullptr; +} + +NativeValue* JsBaseContext::OnGetCacheDir(NativeEngine& engine, NativeCallbackInfo& info) +{ + auto context = context_.lock(); + if (!context) { + HILOG_WARN("context is already released"); + return engine.CreateUndefined(); + } + std::string path = context->GetTempDir(); + return engine.CreateString(path.c_str(), path.length()); +} + +NativeValue* JsBaseContext::GetTempDir(NativeEngine* engine, NativeCallbackInfo* info) +{ + HILOG_INFO("JsBaseContext::SwitchArea is called"); + JsBaseContext* me = CheckParamsAndGetThis(engine, info, BASE_CONTEXT_NAME); + return me != nullptr ? me->OnGetTempDir(*engine, *info) : nullptr; +} + +NativeValue* JsBaseContext::OnGetTempDir(NativeEngine& engine, NativeCallbackInfo& info) +{ + auto context = context_.lock(); + if (!context) { + HILOG_WARN("context is already released"); + return engine.CreateUndefined(); + } + std::string path = context->GetTempDir(); + return engine.CreateString(path.c_str(), path.length()); +} + +NativeValue* JsBaseContext::GetFilesDir(NativeEngine* engine, NativeCallbackInfo* info) +{ + HILOG_INFO("JsBaseContext::SwitchArea is called"); + JsBaseContext* me = CheckParamsAndGetThis(engine, info, BASE_CONTEXT_NAME); + return me != nullptr ? me->OnGetFilesDir(*engine, *info) : nullptr; +} + +NativeValue* JsBaseContext::OnGetFilesDir(NativeEngine& engine, NativeCallbackInfo& info) +{ + auto context = context_.lock(); + if (!context) { + HILOG_WARN("context is already released"); + return engine.CreateUndefined(); + } + std::string path = context->GetFilesDir(); + return engine.CreateString(path.c_str(), path.length()); +} + +NativeValue* JsBaseContext::GetDistributedFilesDir(NativeEngine* engine, NativeCallbackInfo* info) +{ + HILOG_INFO("JsBaseContext::SwitchArea is called"); + JsBaseContext* me = CheckParamsAndGetThis(engine, info, BASE_CONTEXT_NAME); + return me != nullptr ? me->OnGetDistributedFilesDir(*engine, *info) : nullptr; +} + +NativeValue* JsBaseContext::OnGetDistributedFilesDir(NativeEngine& engine, NativeCallbackInfo& info) +{ + auto context = context_.lock(); + if (!context) { + HILOG_WARN("context is already released"); + return engine.CreateUndefined(); + } + std::string path = context->GetDistributedFilesDir(); + return engine.CreateString(path.c_str(), path.length()); +} + +NativeValue* JsBaseContext::GetDatabaseDir(NativeEngine* engine, NativeCallbackInfo* info) +{ + HILOG_INFO("JsBaseContext::SwitchArea is called"); + JsBaseContext* me = CheckParamsAndGetThis(engine, info, BASE_CONTEXT_NAME); + return me != nullptr ? me->OnGetDatabaseDir(*engine, *info) : nullptr; +} + +NativeValue* JsBaseContext::OnGetDatabaseDir(NativeEngine& engine, NativeCallbackInfo& info) +{ + auto context = context_.lock(); + if (!context) { + HILOG_WARN("context is already released"); + return engine.CreateUndefined(); + } + std::string path = context->GetDatabaseDir(); + return engine.CreateString(path.c_str(), path.length()); +} + +NativeValue* JsBaseContext::GetStorageDir(NativeEngine* engine, NativeCallbackInfo* info) +{ + HILOG_INFO("JsBaseContext::SwitchArea is called"); + JsBaseContext* me = CheckParamsAndGetThis(engine, info, BASE_CONTEXT_NAME); + return me != nullptr ? me->OnGetStorageDir(*engine, *info) : nullptr; +} + +NativeValue* JsBaseContext::OnGetStorageDir(NativeEngine& engine, NativeCallbackInfo& info) +{ + auto context = context_.lock(); + if (!context) { + HILOG_WARN("context is already released"); + return engine.CreateUndefined(); + } + std::string path = context->GetStorageDir(); + return engine.CreateString(path.c_str(), path.length()); +} + +NativeValue* JsBaseContext::GetBundleCodeDir(NativeEngine* engine, NativeCallbackInfo* info) +{ + HILOG_INFO("JsBaseContext::SwitchArea is called"); + JsBaseContext* me = CheckParamsAndGetThis(engine, info, BASE_CONTEXT_NAME); + return me != nullptr ? me->OnGetBundleCodeDir(*engine, *info) : nullptr; +} + +NativeValue* JsBaseContext::OnGetBundleCodeDir(NativeEngine& engine, NativeCallbackInfo& info) +{ + auto context = context_.lock(); + if (!context) { + HILOG_WARN("context is already released"); + return engine.CreateUndefined(); + } + std::string path = context->GetBundleCodeDir(); + return engine.CreateString(path.c_str(), path.length()); +} + NativeValue* JsBaseContext::OnCreateBundleContext(NativeEngine& engine, NativeCallbackInfo& info) { if (info.argc == 0) { @@ -184,14 +325,14 @@ NativeValue* CreateJsBaseContext(NativeEngine& engine, std::shared_ptr if (resourceManager != nullptr) { object->SetProperty("resourceManager", CreateJsResourceManager(engine, resourceManager)); } - object->SetProperty("cacheDir", CreateJsValue(engine, context->GetCacheDir())); - object->SetProperty("tempDir", CreateJsValue(engine, context->GetTempDir())); - object->SetProperty("filesDir", CreateJsValue(engine, context->GetFilesDir())); - object->SetProperty("distributedFilesDir", CreateJsValue(engine, context->GetDistributedFilesDir())); - object->SetProperty("databaseDir", CreateJsValue(engine, context->GetDatabaseDir())); - object->SetProperty("storageDir", CreateJsValue(engine, context->GetStorageDir())); - object->SetProperty("bundleCodeDir", CreateJsValue(engine, context->GetBundleCodeDir())); + BindNativeProperty(*object, "cacheDir", JsBaseContext::GetCacheDir); + BindNativeProperty(*object, "tempDir", JsBaseContext::GetTempDir); + BindNativeProperty(*object, "filesDir", JsBaseContext::GetFilesDir); + BindNativeProperty(*object, "distributedFilesDir", JsBaseContext::GetDistributedFilesDir); + BindNativeProperty(*object, "databaseDir", JsBaseContext::GetDatabaseDir); + BindNativeProperty(*object, "storageDir", JsBaseContext::GetStorageDir); + BindNativeProperty(*object, "bundleCodeDir", JsBaseContext::GetBundleCodeDir); BindNativeFunction(engine, *object, "createBundleContext", JsBaseContext::CreateBundleContext); BindNativeFunction(engine, *object, "getApplicationContext", JsBaseContext::GetApplicationContext); BindNativeFunction(engine, *object, "switchArea", JsBaseContext::SwitchArea); diff --git a/frameworks/kits/appkit/native/ability_runtime/context/js_resource_manager_utils.cpp b/frameworks/kits/appkit/native/ability_runtime/context/js_resource_manager_utils.cpp index b75cad0dfb84a2327bed40e6f1007d94acd143c0..23f5c79be33e9729db2ecf8d1012e1925c6ab843 100644 --- a/frameworks/kits/appkit/native/ability_runtime/context/js_resource_manager_utils.cpp +++ b/frameworks/kits/appkit/native/ability_runtime/context/js_resource_manager_utils.cpp @@ -15,86 +15,17 @@ #include "js_resource_manager_utils.h" -#include "hilog_wrapper.h" #include "js_runtime_utils.h" -#include "rstate.h" +#include "resource_manager_addon.h" namespace OHOS { namespace AbilityRuntime { -namespace { -const int32_t GETSTRING_PARAM_SIZE = 1; -class JsResourceManager final { -public: - JsResourceManager(const std::shared_ptr& resourceManager) - : resourceManager_(resourceManager) {} - ~JsResourceManager() = default; - - static void Finalizer(NativeEngine* engine, void* data, void* hint) - { - HILOG_INFO("JsResourceManager::Finalizer is called"); - std::unique_ptr(static_cast(data)); - } - - static NativeValue* GetString(NativeEngine* engine, NativeCallbackInfo* info) - { - JsResourceManager* me = CheckParamsAndGetThis(engine, info); - return me != nullptr ? me->GetString(*engine, *info) : nullptr; - } - -private: - NativeValue* GetString(NativeEngine& engine, NativeCallbackInfo& info) - { - HILOG_INFO("JsResourceManager GetString is called"); - - if (info.argc == 0) { - HILOG_ERROR("Not enough params"); - return engine.CreateUndefined(); - } - - NativeNumber* number = ConvertNativeValueTo(info.argv[0]); - uint32_t param = number ? *(number) : 0; - - AsyncTask::CompleteCallback complete = - [weak = resourceManager_, resId = param](NativeEngine& engine, AsyncTask& task, int32_t status) { - auto resourceManager = weak.lock(); - if (!resourceManager) { - HILOG_INFO("JsResourceManager is released"); - task.Reject(engine, CreateJsError(engine, 1, "resourceManager is released")); - return; - } - std::string retValue; - OHOS::Global::Resource::RState errval = resourceManager->GetStringById(resId, retValue); - if (errval == OHOS::Global::Resource::RState::SUCCESS) { - HILOG_DEBUG("resourceManager GetStringById:%{public}s", retValue.c_str()); - task.Resolve(engine, engine.CreateString(retValue.c_str(), retValue.length())); - } else { - HILOG_DEBUG("resourceManager GetStringById failed"); - task.Reject(engine, CreateJsError(engine, errval, "getString failed")); - } - }; - - NativeValue* lastParam = info.argc > GETSTRING_PARAM_SIZE ? info.argv[GETSTRING_PARAM_SIZE] : nullptr; - NativeValue* result = nullptr; - AsyncTask::Schedule( - engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); - return result; - } - - std::weak_ptr resourceManager_; -}; -} // namespace - NativeValue* CreateJsResourceManager( NativeEngine& engine, std::shared_ptr resourceManager) { - NativeValue* objValue = engine.CreateObject(); - NativeObject* object = ConvertNativeValueTo(objValue); - - std::unique_ptr jsResourceManager = std::make_unique(resourceManager); - object->SetNativePointer(jsResourceManager.release(), JsResourceManager::Finalizer, nullptr); - - BindNativeFunction(engine, *object, "getString", JsResourceManager::GetString); - return objValue; + napi_env env = reinterpret_cast(&engine); + napi_value result = Global::Resource::ResourceManagerAddon::Create(env, "", resourceManager); + return reinterpret_cast(result); } } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_runtime/datashare_ext_ability_context.cpp b/frameworks/kits/appkit/native/ability_runtime/datashare_ext_ability_context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5a3683190481dc57bf19282bd98acf6048b69925 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/datashare_ext_ability_context.cpp @@ -0,0 +1,22 @@ +/* + * 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 + * + * 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 "datashare_ext_ability_context.h" + +namespace OHOS { +namespace AbilityRuntime { + DataShareExtAbilityContext::DataShareExtAbilityContext() {} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_runtime/datashare_ext_ability_context.h b/frameworks/kits/appkit/native/ability_runtime/datashare_ext_ability_context.h new file mode 100644 index 0000000000000000000000000000000000000000..53cd63c72ce659a4011c9fd544e2c24f24de7270 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/datashare_ext_ability_context.h @@ -0,0 +1,34 @@ +/* + * 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 + * + * 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 DATASHARE_EXT_ABILITY_CONTEXT_H +#define DATASHARE_EXT_ABILITY_CONTEXT_H + +#include "extension_context.h" + +namespace OHOS { +namespace AbilityRuntime { +/** + * @brief context supply for datashare + * + */ +class DataShareExtAbilityContext : public ExtensionContext { +public: + DataShareExtAbilityContext(); + virtual ~DataShareExtAbilityContext() = default; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // DATASHARE_EXT_ABILITY_CONTEXT_H \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_runtime/extension_context.cpp b/frameworks/kits/appkit/native/ability_runtime/extension_context.cpp index 1f939d4f4928006f7141de58b4b1b2b494ecced3..21343fae80daea56e77726819a3e463f95086c47 100644 --- a/frameworks/kits/appkit/native/ability_runtime/extension_context.cpp +++ b/frameworks/kits/appkit/native/ability_runtime/extension_context.cpp @@ -21,20 +21,6 @@ namespace OHOS { namespace AbilityRuntime { const size_t ExtensionContext::CONTEXT_TYPE_ID(std::hash {} ("ExtensionContext")); -void ExtensionContext::SetToken(const sptr &token) -{ - if (token == nullptr) { - HILOG_DEBUG("ExtensionContext::SetToken failed, application is nullptr"); - return; - } - token_ = token; -} - -sptr ExtensionContext::GetToken() const -{ - return token_; -} - void ExtensionContext::SetAbilityInfo(const std::shared_ptr &abilityInfo) { if (abilityInfo == nullptr) { diff --git a/frameworks/kits/appkit/native/ability_runtime/extension_context.h b/frameworks/kits/appkit/native/ability_runtime/extension_context.h index 8be6220924adfe0e3a665d03e707fc693607e02d..ebf812bd141be3784d918ffa1d32676300347bc8 100644 --- a/frameworks/kits/appkit/native/ability_runtime/extension_context.h +++ b/frameworks/kits/appkit/native/ability_runtime/extension_context.h @@ -18,7 +18,6 @@ #include "ability_info.h" #include "context_impl.h" -#include "iremote_object.h" namespace OHOS { namespace AbilityRuntime { @@ -31,20 +30,6 @@ public: ExtensionContext() = default; virtual ~ExtensionContext() = default; - /** - * @brief Set the token witch the app launched. - * - * @param token The token which the is launched by app. - */ - void SetToken(const sptr &token); - - /** - * @brief Get the token witch the app launched. - * - * @return token The token which the is launched by app. - */ - sptr GetToken() const; - /** * @brief Obtains information about the current ability. * The returned information includes the class name, bundle name, and other information about the current ability. @@ -68,7 +53,6 @@ protected: return contextTypeId == CONTEXT_TYPE_ID || Context::IsContext(contextTypeId); } - sptr token_; private: std::shared_ptr abilityInfo_; }; diff --git a/frameworks/kits/appkit/native/app/include/context.h b/frameworks/kits/appkit/native/app/include/context.h old mode 100755 new mode 100644 index 33d6614dd4c6ab9e1a8e7648aba30e08d3ce13b7..d250982db14b1aa97c4e624a9a56461b220b4fb6 --- a/frameworks/kits/appkit/native/app/include/context.h +++ b/frameworks/kits/appkit/native/app/include/context.h @@ -52,6 +52,7 @@ using AbilityStartSetting = AAFwk::AbilityStartSetting; constexpr int INVALID_RESOURCE_VALUE = -1; // GetColor() Failed return Value class DataAbilityHelper; +class DataShareHelper; class ContinuationConnector; class IAbilityManager; class TaskDispatcher; @@ -717,6 +718,7 @@ public: virtual void SetShowOnLockScreen(bool isAllow) = 0; friend DataAbilityHelper; + friend DataShareHelper; friend ContinuationConnector; protected: diff --git a/frameworks/kits/appkit/native/app/src/main_thread.cpp b/frameworks/kits/appkit/native/app/src/main_thread.cpp index 30cd950a89cae2bd96cbe1099fbd6eed76fdbd98..ca063d08e5f49f2d3f75e17e02cdf803003f087c 100644 --- a/frameworks/kits/appkit/native/app/src/main_thread.cpp +++ b/frameworks/kits/appkit/native/app/src/main_thread.cpp @@ -27,6 +27,7 @@ #include "bytrace.h" #include "context_deal.h" #include "context_impl.h" +#include "datashare_ext_ability.h" #include "extension_module_loader.h" #include "form_extension.h" #include "if_system_ability_manager.h" @@ -837,7 +838,7 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con moduelJson = bundleInfo.hapModuleInfos.back().isModuleJson; isStageBased = bundleInfo.hapModuleInfos.back().isStageBasedModel; } - APP_LOGI("stageBased:%{public}d moduelJson:%{public}d size:%{public}d", + APP_LOGI("stageBased:%{public}d moduleJson:%{public}d size:%{public}d", isStageBased, moduelJson, (int32_t)bundleInfo.hapModuleInfos.size()); if (isStageBased) { // Create runtime @@ -868,6 +869,8 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con }); LoadAndRegisterExtension("system/lib/libservice_extension_module.z.so", "ServiceExtension", application_->GetRuntime()); + LoadAndRegisterExtension("system/lib/libdatashare_ext_ability_module.z.so", "DataShareExtAbility", + application_->GetRuntime()); } contextDeal->initResourceManager(resourceManager); diff --git a/frameworks/kits/appkit/native/test/BUILD.gn b/frameworks/kits/appkit/native/test/BUILD.gn index 2131b281709d9fde0495e08aa6c936e237a7520f..57f7dfff787b73ad055f37965402e20d8af186d0 100755 --- a/frameworks/kits/appkit/native/test/BUILD.gn +++ b/frameworks/kits/appkit/native/test/BUILD.gn @@ -124,7 +124,7 @@ ohos_unittest("application_test") { "${ABILITY_INNERKITS_PATH}/want:want", "${aafwk_path}/frameworks/kits/appkit:app_context", "${aafwk_path}/frameworks/kits/appkit:appkit_native", - "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", @@ -164,7 +164,7 @@ ohos_unittest("context_container_test") { deps = [ "${ABILITY_INNERKITS_PATH}/want:want", "${aafwk_path}/frameworks/kits/appkit:appkit_native", - "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/appexecfwk/standard/common:libappexecfwk_common", @@ -191,7 +191,7 @@ ohos_unittest("application_context_for_task_dispacher_test") { deps = [ "${ABILITY_INNERKITS_PATH}/want:want", "${aafwk_path}/frameworks/kits/appkit:appkit_native", - "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/appexecfwk/standard/common:libappexecfwk_common", @@ -217,7 +217,7 @@ ohos_unittest("context_deal_for_task_dispacher_test") { deps = [ "${ABILITY_INNERKITS_PATH}/want:want", "${aafwk_path}/frameworks/kits/appkit:appkit_native", - "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/appexecfwk/standard/common:libappexecfwk_common", @@ -251,7 +251,7 @@ ohos_unittest("context_deal_test") { deps = [ "${ABILITY_INNERKITS_PATH}/want:want", "${aafwk_path}/frameworks/kits/appkit:appkit_native", - "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/appexecfwk/standard/common:libappexecfwk_common", @@ -285,7 +285,7 @@ ohos_unittest("application_impl_test") { deps = [ "${ABILITY_INNERKITS_PATH}/want:want", "${aafwk_path}/frameworks/kits/appkit:appkit_native", - "//foundation/aafwk/standard/common/task_dispatcher:appkit_dispatcher_td", + "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", diff --git a/frameworks/kits/fmskit/native/src/form_host_client.cpp b/frameworks/kits/fmskit/native/src/form_host_client.cpp index 959601777ec673d8eff700f08da7605b85eddfcc..91f89bf67deaacaced634ce599de2394ebe104e7 100755 --- a/frameworks/kits/fmskit/native/src/form_host_client.cpp +++ b/frameworks/kits/fmskit/native/src/form_host_client.cpp @@ -157,6 +157,7 @@ bool FormHostClient::ContainsForm(int64_t formId) void FormHostClient::OnAcquired(const FormJsInfo &formJsInfo) { APP_LOGI("%{public}s called.", __func__); + APP_LOGI("Imamge number is %{public}zu.", formJsInfo.imageDataMap.size()); int64_t formId = formJsInfo.formId; if (formId < 0) { APP_LOGE("%{public}s error, the passed form id can't be negative.", __func__); diff --git a/frameworks/kits/runtime/native/js_runtime_utils.cpp b/frameworks/kits/runtime/native/js_runtime_utils.cpp index 27cd714063db2ca4a05be4027f9afc414f15e2bf..11dabff975aa79ba35fe3857bc39899e712b8bce 100644 --- a/frameworks/kits/runtime/native/js_runtime_utils.cpp +++ b/frameworks/kits/runtime/native/js_runtime_utils.cpp @@ -48,6 +48,20 @@ void BindNativeFunction(NativeEngine& engine, NativeObject& object, const char* object.SetProperty(name, engine.CreateFunction(name, strlen(name), func, nullptr)); } +void BindNativeProperty(NativeObject& object, const char* name, NativeCallback getter) +{ + NativePropertyDescriptor property; + property.utf8name = name; + property.name = nullptr; + property.method = nullptr; + property.getter = getter; + property.setter = nullptr; + property.value = nullptr; + property.attributes = napi_default; + property.data = nullptr; + object.DefineProperty(property); +} + void* GetNativePointerFromCallbackInfo(NativeEngine* engine, NativeCallbackInfo* info, const char* name) { if (engine == nullptr || info == nullptr) { diff --git a/interfaces/innerkits/ability_manager/BUILD.gn b/interfaces/innerkits/ability_manager/BUILD.gn index 17865d3150ec9e87e8cb85c14d4364cd084109e2..54b64109bfd3d91173a8ebb7e27bdbf0d7425489 100644 --- a/interfaces/innerkits/ability_manager/BUILD.gn +++ b/interfaces/innerkits/ability_manager/BUILD.gn @@ -74,7 +74,9 @@ ohos_shared_library("ability_manager") { "${services_path}/abilitymgr/src/start_options.cpp", "${services_path}/abilitymgr/src/stop_user_callback_proxy.cpp", "${services_path}/abilitymgr/src/stop_user_callback_stub.cpp", + "${services_path}/abilitymgr/src/want_receiver_stub.cpp", "${services_path}/abilitymgr/src/want_sender_info.cpp", + "${services_path}/abilitymgr/src/want_sender_proxy.cpp", "${services_path}/abilitymgr/src/want_sender_stub.cpp", "${services_path}/abilitymgr/src/wants_info.cpp", "//foundation/aafwk/standard/frameworks/kits/ability/native/src/data_ability_operation.cpp", diff --git a/interfaces/innerkits/ability_manager/include/ability_manager_interface.h b/interfaces/innerkits/ability_manager/include/ability_manager_interface.h index 1039ee270dc986fce37b1011fd82fc639ef0e670..3ea0921851a50ed054f30970559b58f40fe139a0 100644 --- a/interfaces/innerkits/ability_manager/include/ability_manager_interface.h +++ b/interfaces/innerkits/ability_manager/include/ability_manager_interface.h @@ -668,6 +668,24 @@ public: * @return Returns ERR_OK on success, others on failure. */ virtual int DelegatorDoAbilityBackground(const sptr &token) = 0; + + /** + * Calls this interface to move the ability to the foreground. + * + * @param token, ability's token. + * @param flag, use for lock or unlock flag and so on. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DoAbilityForeground(const sptr &token, uint32_t flag) = 0; + + /** + * Calls this interface to move the ability to the background. + * + * @param token, ability's token. + * @param flag, use for lock or unlock flag and so on. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DoAbilityBackground(const sptr &token, uint32_t flag) = 0; /** * Send not response process ID to ability manager service. @@ -836,6 +854,12 @@ public: // ipc id for set mission label (53) SET_MISSION_LABEL, + // ipc id for ability foreground (54) + DO_ABILITY_FOREGROUND, + + // ipc id for ability background (55) + DO_ABILITY_BACKGROUND, + // ipc id 1001-2000 for DMS // ipc id for starting ability (1001) START_ABILITY = 1001, diff --git a/interfaces/innerkits/ability_manager/include/lifecycle_state_info.h b/interfaces/innerkits/ability_manager/include/lifecycle_state_info.h index df11ed76f4aca73ab1994efd935726720a0ce2b8..e77bbbb968bcead5216f1997b133f6ae3bed628d 100644 --- a/interfaces/innerkits/ability_manager/include/lifecycle_state_info.h +++ b/interfaces/innerkits/ability_manager/include/lifecycle_state_info.h @@ -54,6 +54,7 @@ struct LifeCycleStateInfo : public Parcelable { std::shared_ptr setting = nullptr; LaunchParam launchParam; bool useNewMission = false; + uint32_t sceneFlag = 0; bool ReadFromParcel(Parcel &parcel); virtual bool Marshalling(Parcel &parcel) const override; diff --git a/interfaces/innerkits/form_manager/BUILD.gn b/interfaces/innerkits/form_manager/BUILD.gn index 73d6404cc3ec3d18192628863b833f8fd068f5bd..37ce56ecbcb8f82f016396845a0cc8dfbf85409a 100644 --- a/interfaces/innerkits/form_manager/BUILD.gn +++ b/interfaces/innerkits/form_manager/BUILD.gn @@ -25,6 +25,7 @@ config("formmgr_sdk_config") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", "//foundation/appexecfwk/standard/common/log/include", + "//foundation/aafwk/standard/services/common/include", ] cflags = [] if (target_cpu == "arm") { diff --git a/interfaces/innerkits/form_manager/include/form_js_info.h b/interfaces/innerkits/form_manager/include/form_js_info.h index 68fe090331db8f5586118bdbdc872d4ab124ffee..016edcc91f3d9a190ea3b720c59d671f8da3194f 100644 --- a/interfaces/innerkits/form_manager/include/form_js_info.h +++ b/interfaces/innerkits/form_manager/include/form_js_info.h @@ -16,7 +16,6 @@ #ifndef FOUNDATION_APPEXECFWK_OHOS_FORM_JS_INFO_H #define FOUNDATION_APPEXECFWK_OHOS_FORM_JS_INFO_H - #include #include "form_provider_data.h" #include "form_info_base.h" @@ -29,6 +28,7 @@ namespace AppExecFwk { * Defines form js info. */ struct FormJsInfo : public Parcelable { + static constexpr int IMAGE_DATA_THRESHOLD = 128; int64_t formId; std::string formName; std::string bundleName; @@ -36,6 +36,7 @@ struct FormJsInfo : public Parcelable { bool formTempFlg = false; std::string jsFormCodePath; std::string formData; + std::map> imageDataMap; FormProviderData formProviderData; std::string htmlPath; @@ -52,6 +53,8 @@ struct FormJsInfo : public Parcelable { bool ReadFromParcel(Parcel &parcel); virtual bool Marshalling(Parcel &parcel) const override; static FormJsInfo *Unmarshalling(Parcel &parcel); + bool WriteImageData(Parcel &parcel) const; + void ReadImageData(Parcel &parcel); }; } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/form_manager/include/form_provider_data.h b/interfaces/innerkits/form_manager/include/form_provider_data.h index 4ca3c98964632d39e82d337b552ede76f8ed8469..598ccf6bd875a49adc9ffccc2ef14bc8adfa8cbd 100644 --- a/interfaces/innerkits/form_manager/include/form_provider_data.h +++ b/interfaces/innerkits/form_manager/include/form_provider_data.h @@ -76,7 +76,14 @@ public: * @param picName Indicates the name of the image to add. * @param data Indicates the binary data of the image content. */ - void AddImageData(std::string picName, char *data); + void AddImageData(std::string picName, char *data, int32_t size); + + /** + * @brief Adds an image to this {@code FormProviderData} instance. + * @param picName Indicates the name of the image to add. + * @param fd Indicates the file descriptor of the image content. + */ + void AddImageData(std::string picName, int fd); /** * @brief Removes data of an image with the specified {@code picName} from this {@code FormProviderData} instance. @@ -88,7 +95,7 @@ public: * @brief Obtains the add/remove state stored in this {@code FormProviderData} object. * @return Returns the add/remove state of shared image data. */ - int32_t GetImageDataState(); + int32_t GetImageDataState() const; /** * @brief Updates imageDataState in this {@code FormProviderData} object. @@ -100,7 +107,7 @@ public: * @brief Obtains the imageDataMap stored in this {@code FormProviderData} object. * @return Returns the map that contains shared image data. */ - std::map, int32_t>> GetImageDataMap(); + std::map, int32_t>> GetImageDataMap() const; /** * @brief Updates imageDataMap in this {@code FormProviderData} object. @@ -149,13 +156,18 @@ public: */ void ClearData(); +public: + static constexpr int IMAGE_DATA_STATE_REMOVED = -1; + static constexpr int IMAGE_DATA_STATE_NO_OPERATION = 0; + static constexpr int IMAGE_DATA_STATE_ADDED = 1; + private: - bool WriteImageDataToParcel(Parcel &parcel, std::string picName, char *data) const; + bool WriteImageDataToParcel(Parcel &parcel, std::string picName, char *data, int32_t size) const; private: nlohmann::json jsonFormProviderData_; std::map, int32_t>> imageDataMap_; - std::map rawImageBytesMap_; + std::map> rawImageBytesMap_; int32_t imageDataState_ = 0; }; } // namespace AppExecFwk diff --git a/interfaces/innerkits/form_manager/src/form_js_info.cpp b/interfaces/innerkits/form_manager/src/form_js_info.cpp index 14fa30ff8ced8400bab4f2faa4d5490fe76e778c..ce244ed531e59823806d00ec48370b675bcc293e 100644 --- a/interfaces/innerkits/form_manager/src/form_js_info.cpp +++ b/interfaces/innerkits/form_manager/src/form_js_info.cpp @@ -14,6 +14,7 @@ */ #include "form_js_info.h" +#include "hilog_wrapper.h" #include "string_ex.h" namespace OHOS { @@ -43,6 +44,8 @@ bool FormJsInfo::ReadFromParcel(Parcel &parcel) return false; } formProviderData = *bindingData; + + ReadImageData(parcel); return true; } @@ -123,7 +126,90 @@ bool FormJsInfo::Marshalling(Parcel &parcel) const return false; } + if (!WriteImageData(parcel)) { + return false; + } + return true; +} + +bool FormJsInfo::WriteImageData(Parcel &parcel) const +{ + HILOG_INFO("%{public}s called", __func__); + auto imageDateState = formProviderData.GetImageDataState(); + if (!parcel.WriteInt32(imageDateState)) { + return false; + } + HILOG_INFO("%{public}s imageDateState is %{public}d", __func__, imageDateState); + switch (imageDateState) { + case FormProviderData::IMAGE_DATA_STATE_ADDED: { + auto sharedImageMap = formProviderData.GetImageDataMap(); + auto size = sharedImageMap.size(); + if (!parcel.WriteInt32(size)) { + return false; + } + if (size > IMAGE_DATA_THRESHOLD) { + HILOG_INFO("%{public}s unexpected image number %{public}zu", __func__, size); + break; + } + auto messageParcel = static_cast(&parcel); + for (auto entry : sharedImageMap) { + if (!messageParcel->WriteAshmem(entry.second.first)) { + return false; + } + if (parcel.WriteString16(Str8ToStr16(entry.first))) { + return false; + } + } + break; + } + case FormProviderData::IMAGE_DATA_STATE_NO_OPERATION: + break; + case FormProviderData::IMAGE_DATA_STATE_REMOVED: + break; + default: { + HILOG_INFO("%{public}s unexpected imageDateState %{public}d", __func__, imageDateState); + break; + } + } + HILOG_INFO("%{public}s end", __func__); return true; } + +void FormJsInfo::ReadImageData(Parcel &parcel) +{ + HILOG_INFO("%{public}s called", __func__); + auto imageDateState = parcel.ReadInt32(); + HILOG_INFO("%{public}s imageDateState is %{public}d", __func__, imageDateState); + switch (imageDateState) { + case FormProviderData::IMAGE_DATA_STATE_ADDED: { + auto size = parcel.ReadInt32(); + HILOG_INFO("%{public}s image numer is %{public}d", __func__, size); + if (size > IMAGE_DATA_THRESHOLD) { + HILOG_WARN("%{public}s unexpected image number %{public}d", __func__, size); + break; + } + auto messageParcel = static_cast(&parcel); + for (auto i = 0; i < size; i++) { + auto fd = messageParcel->ReadFileDescriptor(); + auto len = parcel.ReadInt32(); + auto picName = Str16ToStr8(parcel.ReadString16()); + HILOG_INFO("picName: %{public}s, fd: %{public}d, size: %{public}d", picName.c_str(), fd, len); + std::pair imageDataPair = std::make_pair(fd, len); + imageDataMap.emplace(picName, imageDataPair); + } + break; + } + case FormProviderData::IMAGE_DATA_STATE_NO_OPERATION: + break; + case FormProviderData::IMAGE_DATA_STATE_REMOVED: + break; + default: { + HILOG_WARN("%{public}s unexpected imageDateState %{public}d", __func__, imageDateState); + break; + } + } + HILOG_INFO("%{public}s end", __func__); + return; +} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/form_manager/src/form_provider_data.cpp b/interfaces/innerkits/form_manager/src/form_provider_data.cpp index 40d5b20312207811300db613864cceaa74d9f95c..fa5d0a85d5d50f89963c5e59fe10c2862558a4ae 100644 --- a/interfaces/innerkits/form_manager/src/form_provider_data.cpp +++ b/interfaces/innerkits/form_manager/src/form_provider_data.cpp @@ -16,17 +16,15 @@ #include #include #include +#include -#include "app_log_wrapper.h" #include "form_provider_data.h" +#include "hilog_wrapper.h" #include "message_parcel.h" #include "string_ex.h" namespace OHOS { namespace AppExecFwk { -const int IMAGE_DATA_STATE_REMOVED = -1; -const int IMAGE_DATA_STATE_NO_OPERATION = 0; -const int IMAGE_DATA_STATE_ADDED = 1; const std::string JSON_EMPTY_STRING = "{}"; /** @@ -84,9 +82,9 @@ nlohmann::json FormProviderData::GetData() const */ std::string FormProviderData::GetDataString() const { - APP_LOGI("%{public}s called", __func__); + HILOG_INFO("%{public}s called", __func__); std::string dataStr = jsonFormProviderData_.empty() ? "" : jsonFormProviderData_.dump(); - APP_LOGI("%{public}s, data: %{public}s", __func__, dataStr.c_str()); + HILOG_INFO("%{public}s, data: %{public}s", __func__, dataStr.c_str()); return dataStr; } @@ -95,18 +93,58 @@ std::string FormProviderData::GetDataString() const * @param picName Indicates the name of the image to add. * @param data Indicates the binary data of the image content. */ -void FormProviderData::AddImageData(std::string picName, char *data) +void FormProviderData::AddImageData(std::string picName, char *data, int32_t size) { if ((picName.length() == 0) || (sizeof(data) == 0)) { - APP_LOGE("input param is NULL!"); + HILOG_ERROR("input param is NULL!"); return; } - rawImageBytesMap_[picName] = data; + rawImageBytesMap_[picName] = std::make_pair(data, size); imageDataState_ = IMAGE_DATA_STATE_ADDED; } +/** + * @brief Adds an image to this {@code FormProviderData} instance. + * @param picName Indicates the name of the image to add. + * @param data Indicates the binary data of the image content. + */ +void FormProviderData::AddImageData(std::string picName, int fd) +{ + HILOG_INFO("%{public}s called", __func__); + if (fd <= 0) { + return; + } + std::string fdPath = "/proc/self/fd/" + std::to_string(fd); + char fileName[PATH_MAX + 1] = {0}; + int ret = readlink(fdPath.c_str(), fileName, PATH_MAX); + if (ret < 0 || ret > PATH_MAX) { + HILOG_ERROR("Get fileName failed, ret is: %{public}d!", ret); + return; + } + fileName[ret] = '\0'; + + std::ifstream file(fileName, std::ios::in | std::ios::binary | std::ios::ate); + if (!file.is_open()) { + HILOG_INFO("open failed"); + return; + } + + file.seekg(0, std::ios::end); + int32_t size = file.tellg(); + HILOG_INFO("File size %{public}d", size); + if (size < 0) { + return; + } + file.seekg(0, std::ios::beg); + char *data = new char[size]; + file.read(data, size); + file.close(); + AddImageData(picName, data, size); + HILOG_INFO("%{public}s called end.", __func__); +} + /** * @brief Removes data of an image with the specified {@code picName} from this {@code FormProviderData} instance. * @param picName Indicates the name of the image to remove. @@ -122,7 +160,7 @@ void FormProviderData::RemoveImageData(std::string picName) */ void FormProviderData::SetDataString(std::string &jsonDataString) { - APP_LOGI("%{public}s called", __func__); + HILOG_INFO("%{public}s called", __func__); if (jsonDataString.empty()) { jsonDataString = JSON_EMPTY_STRING; } @@ -134,7 +172,7 @@ void FormProviderData::SetDataString(std::string &jsonDataString) */ void FormProviderData::MergeData(nlohmann::json &addJsonData) { - APP_LOGI("%{public}s called", __func__); + HILOG_INFO("%{public}s called", __func__); if (addJsonData.empty()) { return; } @@ -153,7 +191,7 @@ void FormProviderData::MergeData(nlohmann::json &addJsonData) * @brief Obtains the imageDataMap stored in this {@code FormProviderData} object. * @return Returns the map that contains shared image data. */ -std::map, int32_t>> FormProviderData::GetImageDataMap() +std::map, int32_t>> FormProviderData::GetImageDataMap() const { return imageDataMap_; } @@ -162,7 +200,7 @@ std::map, int32_t>> FormProviderData::GetIma * @brief Obtains the add/remove state stored in this {@code FormProviderData} object. * @return Returns the add/remove state of shared image data. */ -int32_t FormProviderData::GetImageDataState() +int32_t FormProviderData::GetImageDataState() const { return imageDataState_; } @@ -195,6 +233,7 @@ bool FormProviderData::ReadFromParcel(Parcel &parcel) jsonFormProviderData_ = nlohmann::json::parse(Str16ToStr8(parcel.ReadString16())); imageDataState_ = parcel.ReadInt32(); + HILOG_INFO("%{public}s imageDateState is %{public}d", __func__, imageDataState_); switch (imageDataState_) { case IMAGE_DATA_STATE_ADDED: { int32_t imageDataNum = parcel.ReadInt32(); @@ -202,7 +241,7 @@ bool FormProviderData::ReadFromParcel(Parcel &parcel) MessageParcel* messageParcel = (MessageParcel*)&parcel; sptr ashmem = messageParcel->ReadAshmem(); if (ashmem == nullptr) { - APP_LOGE("%{public}s failed, ashmem is nullptr", __func__); + HILOG_ERROR("%{public}s failed, ashmem is nullptr", __func__); return false; } @@ -216,7 +255,7 @@ bool FormProviderData::ReadFromParcel(Parcel &parcel) case IMAGE_DATA_STATE_REMOVED: break; default: - APP_LOGW("%{public}s failed, unexpected imageDataState_ %{public}d", __func__, imageDataState_); + HILOG_WARN("%{public}s failed, unexpected imageDataState_ %{public}d", __func__, imageDataState_); break; } return true; @@ -229,22 +268,19 @@ bool FormProviderData::ReadFromParcel(Parcel &parcel) */ bool FormProviderData::Marshalling(Parcel &parcel) const { - APP_LOGI("%{public}s called, jsonFormProviderData_: %{public}s", __func__, jsonFormProviderData_.dump().c_str()); + HILOG_INFO("%{public}s called, jsonFormProviderData_: %{public}s", __func__, jsonFormProviderData_.dump().c_str()); if (!parcel.WriteString16(Str8ToStr16(jsonFormProviderData_.empty() ? JSON_EMPTY_STRING : jsonFormProviderData_.dump()))) { return false; } parcel.WriteInt32(imageDataState_); + HILOG_INFO("%{public}s imageDateState is %{public}d", __func__, imageDataState_); switch (imageDataState_) { case IMAGE_DATA_STATE_ADDED: { - if (rawImageBytesMap_.size() == 0) { - APP_LOGE("%{public}s failed, rawImageBytesMap_ is empty", __func__); - return false; - } parcel.WriteInt32(rawImageBytesMap_.size()); // firstly write the number of shared image to add for (auto &entry : rawImageBytesMap_) { - if (!WriteImageDataToParcel(parcel, entry.first, entry.second)) { - APP_LOGE("%{public}s failed, the picture name is %{public}s", __func__, entry.first.c_str()); + if (!WriteImageDataToParcel(parcel, entry.first, entry.second.first, entry.second.second)) { + HILOG_ERROR("%{public}s failed, the picture name is %{public}s", __func__, entry.first.c_str()); return false; } parcel.WriteInt32(sizeof(entry.second)); @@ -256,7 +292,7 @@ bool FormProviderData::Marshalling(Parcel &parcel) const case IMAGE_DATA_STATE_REMOVED: break; default: - APP_LOGW("%{public}s failed, unexpected imageDataState_ %{public}d", __func__, imageDataState_); + HILOG_WARN("%{public}s failed, unexpected imageDataState_ %{public}d", __func__, imageDataState_); break; } return true; @@ -284,23 +320,23 @@ void FormProviderData::ClearData() jsonFormProviderData_.clear(); } -bool FormProviderData::WriteImageDataToParcel(Parcel &parcel, std::string picName, char *data) const +bool FormProviderData::WriteImageDataToParcel(Parcel &parcel, std::string picName, char *data, int32_t size) const { - sptr ashmem = Ashmem::CreateAshmem(picName.c_str(), sizeof(data)); + sptr ashmem = Ashmem::CreateAshmem(picName.c_str(), size); if (ashmem == nullptr) { - APP_LOGE("create shared memory fail"); + HILOG_ERROR("create shared memory fail"); return false; } bool ret = ashmem->MapReadAndWriteAshmem(); if (!ret) { - APP_LOGE("map shared memory fail"); + HILOG_ERROR("map shared memory fail"); return false; } - ret = ashmem->WriteToAshmem(data, sizeof(data), 0); + ret = ashmem->WriteToAshmem(data, size, 0); if (!ret) { - APP_LOGE("write image data to shared memory fail"); + HILOG_ERROR("write image data to shared memory fail"); return false; } @@ -311,7 +347,7 @@ bool FormProviderData::WriteImageDataToParcel(Parcel &parcel, std::string picNam ashmem->CloseAshmem(); // close ashmem after writeAshmem because writeAshmem will dup fd if (!ret) { - APP_LOGE("writeAshmem fail, the picture name is %{public}s", picName.c_str()); + HILOG_ERROR("writeAshmem fail, the picture name is %{public}s", picName.c_str()); return false; } diff --git a/interfaces/innerkits/napi_base_context/src/napi_base_context.cpp b/interfaces/innerkits/napi_base_context/src/napi_base_context.cpp index e386b3c6eefaf5594ca99c3ed189189d7766d0fe..47b3f9d34ff8109d3b1d8fdf795e556158444235 100644 --- a/interfaces/innerkits/napi_base_context/src/napi_base_context.cpp +++ b/interfaces/innerkits/napi_base_context/src/napi_base_context.cpp @@ -25,33 +25,6 @@ namespace OHOS { namespace AbilityRuntime { -namespace { -napi_status GetStageModeContextClassObject(napi_env env, napi_value& classObject) -{ - static thread_local napi_ref contextClassObjectRef = {0}; - - napi_status ret = napi_get_reference_value(env, contextClassObjectRef, &classObject); - if (ret == napi_ok) { - return napi_ok; - } - - napi_value global; - OHOS_CALL_NAPI_RETURN(napi_get_global(env, &global)); - - napi_value requireNapi; - OHOS_CALL_NAPI_RETURN(napi_get_named_property(env, global, "requireNapi", &requireNapi)); - - napi_value className; - OHOS_CALL_NAPI_RETURN(napi_create_string_utf8(env, "application.Context", NAPI_AUTO_LENGTH, &className)); - - OHOS_CALL_NAPI_RETURN(napi_call_function(env, global, requireNapi, 1, &className, &classObject)); - - // Ignore return value - napi_create_reference(env, classObject, 1, &contextClassObjectRef); - return napi_ok; -} -} // namespace - napi_value* GetFAModeContextClassObject() { static thread_local napi_value contextClassObject = {0}; @@ -66,23 +39,6 @@ napi_status IsStageContext(napi_env env, napi_value object, bool& stageMode) bool value = false; OHOS_CALL_NAPI_RETURN(napi_get_value_bool(env, boolValue, &value)); - napi_value classObject; - if (value) { - OHOS_CALL_NAPI_RETURN(GetStageModeContextClassObject(env, classObject)); - } else { - napi_value* clsObjPtr = GetFAModeContextClassObject(); - if (clsObjPtr == nullptr) { - return napi_generic_failure; - } - classObject = *clsObjPtr; - } - - bool result = false; - OHOS_CALL_NAPI_RETURN(napi_instanceof(env, object, classObject, &result)); - if (!result) { - return napi_generic_failure; - } - stageMode = value; return napi_ok; } diff --git a/interfaces/innerkits/runtime/include/js_runtime_utils.h b/interfaces/innerkits/runtime/include/js_runtime_utils.h index 991f0b0c965c46968e0d6fde6e4e4d18d076451e..d5bb304d80e52d2b6c4d8aa997c6489a8a08acd2 100644 --- a/interfaces/innerkits/runtime/include/js_runtime_utils.h +++ b/interfaces/innerkits/runtime/include/js_runtime_utils.h @@ -109,6 +109,7 @@ NativeValue* CreateNativeArray(NativeEngine& engine, const std::vector& data) NativeValue* CreateJsError(NativeEngine& engine, int32_t errCode, const std::string& message = std::string()); void BindNativeFunction(NativeEngine& engine, NativeObject& object, const char* name, NativeCallback func); +void BindNativeProperty(NativeObject& object, const char* name, NativeCallback getter); void* GetNativePointerFromCallbackInfo(NativeEngine* engine, NativeCallbackInfo* info, const char* name); void SetNamedNativePointer( diff --git a/interfaces/kits/js/@ohos.application.DataShareExtAbility.d.ts b/interfaces/kits/js/@ohos.application.DataShareExtAbility.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e9c950410bf29f6b5a263a2799e4e08ce27ab9d --- /dev/null +++ b/interfaces/kits/js/@ohos.application.DataShareExtAbility.d.ts @@ -0,0 +1,192 @@ +/* + * 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 + * + * 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 { AsyncCallback } from "./basic"; +import { ResultSet } from './data/rdb/resultSet'; +import ExtensionContext from "./application/ExtensionContext"; +import Want from './@ohos.application.Want'; +import dataAbility from './@ohos.data.dataAbility'; +import rdb from './@ohos.data.rdb'; +/** + * class of datashare extension ability. + * + * @since 8 + * @sysCap AAFwk + * @devices phone, tablet, tv, wearable, car + * @systemapi hide for inner use. + */ +export default class DataShareExtAbility { + /** + * Indicates datashare extension ability context. + * + * @since 8 + * @sysCap AAFwk + * @systemapi hide for inner use. + */ + context?: ExtensionContext; + + /** + * Called back when a datashare extension ability is started for initialization. + * + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk + * @param want Indicates connection information about the datashare extension ability. + * @systemapi hide for inner use. + * @return - + */ + onCreate?(want: Want): void; + + /** + * Obtains the MIME type of files. This method should be implemented by a data share. + * + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk + * @param uri Indicates the path of the files to obtain. + * @param mimeTypeFilter Indicates the MIME type of the files to obtain. This parameter cannot be set to {@code + * null}. + *

1. "*/*": Obtains all types supported by a data share. + *

2. "image/*": Obtains files whose main type is image of any subtype. + *

3. "*/jpg": Obtains files whose subtype is JPG of any main type. + * @return Returns the MIME type of the matched files; returns null if there is no type that matches the Data + */ + getFileTypes?(uri: string, mimeTypeFilter:string, callback: AsyncCallback>): void; + + /** + * Opens a file. This method should be implemented by a data share. + * + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk + * @param uri Indicates the path of the file to open. + * @param mode Indicates the open mode, which can be "r" for read-only access, "w" for write-only access (erasing + * whatever data is currently in the file), "wt" for write access that truncates any existing file, + * "wa" for write-only access to append to any existing data, "rw" for read and write access on any + * existing data, or "rwt" for read and write access that truncates any existing file. + * @return Returns the file descriptor. + */ + openFile?(uri: string, mode: string, callback: AsyncCallback): void; + + /** + * Inserts a data record into the database. This method should be implemented by a data share. + * + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk + * @param uri Indicates the position where the data is to insert. + * @param valueBucket Indicates the data to insert. + * @return Returns the index of the newly inserted data record. + */ + insert?(uri: string, values: rdb.ValuesBucket, callback: AsyncCallback): void; + + /** + * Updates one or more data records in the database. This method should be implemented by a data share. + * + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk + * @param uri Indicates the database table storing the data to update. + * @param valueBucket Indicates the data to update. This parameter can be null. + * @param predicates Indicates filter criteria. If this parameter is null, all data records will be updated by + * default. + * @return Returns the number of data records updated. + * @return - + */ + update?(uri: string, values: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, + callback: AsyncCallback): void; + + /** + * Deletes one or more data records. This method should be implemented by a data share. + * + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk + * @param uri Indicates the database table storing the data to delete. + * @param predicates Indicates filter criteria. If this parameter is null, all data records will be deleted by + * default. + * @return Returns the number of data records deleted. + */ + delete?(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback): void; + + /** + * Queries one or more data records in the database. This method should be implemented by a data share. + * + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk + * @param uri Indicates the database table storing the data to query. + * @param columns Indicates the columns to be queried, in array, for example, {"name","age"}. You should define + * the processing logic when this parameter is null. + * @param predicates Indicates filter criteria. If this parameter is null, all data records will be queried by + * default. + * @return Returns the queried data. + */ + query?(uri: string, columns: Array, predicates: dataAbility.DataAbilityPredicates, + callback: AsyncCallback): void; + + /** + * Obtains the MIME type matching the data specified by the uri of the data share. This method should be + * implemented by a data share. + * + *

Data abilities supports general data types, including text, HTML, and JPEG.

+ * + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk + * @param uri Indicates the uri of the data. + * @return Returns the MIME type that matches the data specified by {@code uri}. + */ + getType?(uri: string, callback: AsyncCallback): void; + + /** + * Inserts multiple data records into the database. This method should be implemented by a data share. + * + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk + * @param uri Indicates the position where the data is to insert. + * @param valueBuckets Indicates the data to insert. + * @return Returns the number of data records inserted. + */ + batchInsert?(uri: string, values: Array, callback: AsyncCallback): void; + + /** + * Converts the given {@code uri} that refer to the data share into a normalized uri. A normalized uri can be + * used across devices, persisted, backed up, and restored. It can refer to the same item in the data share + * even if the context has changed. + * + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk + * @param uri Indicates the uri to normalize. + * @return Returns the normalized uri if the data share supports uri normalization; + */ + normalizeUri?(uri: string, callback: AsyncCallback): void; + + /** + * Converts the given normalized {@code uri} generated by {@link #normalizeUri(uri)} into a denormalized one. + * The default implementation of this method returns the original uri passed to it. + * + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk + * @param uri Indicates the uri to denormalize. + * @return Returns the denormalized {@code uri} object if the denormalization is successful; returns the original + * {@code uri} passed to this method if there is nothing to do; returns {@code null} if the data identified by + * the original {@code uri} cannot be found in the current environment. + */ + denormalizeUri?(uri: string, callback: AsyncCallback): void; +} \ No newline at end of file diff --git a/interfaces/kits/napi/BUILD.gn b/interfaces/kits/napi/BUILD.gn index 56167c6d2addf26c81fa85ec9ee9b09786ac5bb6..7b6352c80b77ca610458b4d635a725ec3944737b 100644 --- a/interfaces/kits/napi/BUILD.gn +++ b/interfaces/kits/napi/BUILD.gn @@ -28,7 +28,10 @@ group("napi_packages") { "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/app/test_runner:testrunner_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/callee:callee_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/caller:caller_napi", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/dataShare:datashare", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/dataUriUtils:datauriutils", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/datashare_ext_ability:datashareextability_napi", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/datashare_ext_ability_context:datashareextabilitycontext_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/extensioncontext:extensioncontext_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility:featureability", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", diff --git a/interfaces/kits/napi/aafwk/ability_context/ability_context.js b/interfaces/kits/napi/aafwk/ability_context/ability_context.js index 7922079eeaaa6a0c0c615a57a16d828d290a6fb2..c053519cd7c01bddf99987417eef145dd577b4dd 100755 --- a/interfaces/kits/napi/aafwk/ability_context/ability_context.js +++ b/interfaces/kits/napi/aafwk/ability_context/ability_context.js @@ -36,13 +36,13 @@ class AbilityContext extends Context { return this.__context_impl__.startAbilityWithAccount(want, accountId, options, callback) } - startAbilityByCall(want) { + async startAbilityByCall(want) { if (typeof want !== 'object' || want == null) { console.log("AbilityContext::startAbilityByCall input param error"); return null; } - let callee = this.__context_impl__.startAbilityByCall(want); + let callee = await this.__context_impl__.startAbilityByCall(want); if (typeof callee === 'object' && callee != null) { console.log("AbilityContext::startAbilityByCall"); return new Caller(callee); diff --git a/interfaces/kits/napi/aafwk/caller/caller.js b/interfaces/kits/napi/aafwk/caller/caller.js index 1cf63fb8ceb2d8d7f2b4d3ec6d7de5b4e1ddb625..102bf466adb485276d13f1d1d2a8dfd9af2d9fc2 100644 --- a/interfaces/kits/napi/aafwk/caller/caller.js +++ b/interfaces/kits/napi/aafwk/caller/caller.js @@ -22,7 +22,7 @@ class Caller { constructor(obj) { console.log("Caller::constructor obj is " + typeof obj); this.__call_obj__ = obj; - this.releaseCallback = null; + this.releaseCall = false; } async call(method, data) { @@ -33,6 +33,12 @@ class Caller { return; } + if (this.releaseCall) { + console.log("Caller call this.callee release"); + throw new Error("Function inner object error"); + return; + } + if (this.__call_obj__.callee == null) { console.log("Caller call this.callee is nullptr"); throw new Error("Function inner object error"); @@ -47,7 +53,7 @@ class Caller { let status = await this.__call_obj__.callee.sendRequest(EVENT_CALL_NOTIFY, msgData, msgReply, option); if (!status) { - console.log("Caller call return data " + status); + console.log("Caller call return status " + status); throw new Error("Function execution exception"); return ; } @@ -55,7 +61,7 @@ class Caller { let retval = msgReply.readInt(); let str = msgReply.readString(); if (retval === REQUEST_SUCCESS && str === 'object') { - console.log("Caller call return data " + str); + console.log("Caller call return str " + str); } else { console.log("Caller call retval is [" + retval + "], str [" + str + "]"); msgData.reclaim(); @@ -73,6 +79,12 @@ class Caller { return undefined; } + if (this.releaseCall) { + console.log("Caller callWithResult this.callee release"); + throw new Error("Function inner object error"); + return; + } + if (this.__call_obj__.callee == null) { console.log("Caller callWithResult this.callee is nullptr"); return undefined; @@ -107,6 +119,19 @@ class Caller { release() { console.log("Caller release js called."); + if (this.releaseCall == true) { + console.log("Caller release remoteObj releaseState is true"); + throw new Error("Caller release call remoteObj is released"); + return; + } + + if (this.__call_obj__.callee == null) { + console.log("Caller release call remoteObj is released"); + throw new Error("Caller release call remoteObj is released"); + return; + } + + this.releaseCall = true; this.__call_obj__.release(); } @@ -118,6 +143,12 @@ class Caller { return; } + if (this.releaseCall == true) { + console.log("Caller onRelease remoteObj releaseState is true"); + throw new Error("Caller onRelease call remoteObj is released"); + return; + } + this.__call_obj__.onRelease(callback); } } diff --git a/interfaces/kits/napi/aafwk/datashare_ext_ability/BUILD.gn b/interfaces/kits/napi/aafwk/datashare_ext_ability/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d2dac83fb47137ddb2b0eb2781d1e454d7be0fc9 --- /dev/null +++ b/interfaces/kits/napi/aafwk/datashare_ext_ability/BUILD.gn @@ -0,0 +1,50 @@ +# 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 +# +# 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("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") + +ts2abc_gen_abc("gen_datashare_ext_ability_abc") { + src_js = rebase_path("datashare_ext_ability.js") + dst_file = rebase_path(target_out_dir + "/datashare_ext_ability.abc") + in_puts = [ "datashare_ext_ability.js" ] + out_puts = [ target_out_dir + "/datashare_ext_ability.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("datashare_ext_ability_js") { + input = "datashare_ext_ability.js" + output = target_out_dir + "/datashare_ext_ability.o" +} + +gen_js_obj("datashare_ext_ability_abc") { + input = get_label_info(":gen_datashare_ext_ability_abc", "target_out_dir") + + "/datashare_ext_ability.abc" + output = target_out_dir + "/datashare_ext_ability_abc.o" + dep = ":gen_datashare_ext_ability_abc" +} + +ohos_shared_library("datashareextability_napi") { + sources = [ "datashare_ext_ability_module.cpp" ] + + deps = [ + ":datashare_ext_ability_abc", + ":datashare_ext_ability_js", + ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module/application" + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/kits/napi/aafwk/datashare_ext_ability/datashare_ext_ability.js b/interfaces/kits/napi/aafwk/datashare_ext_ability/datashare_ext_ability.js new file mode 100644 index 0000000000000000000000000000000000000000..a9217854ec838a95cf62a17ef93ab93c63448586 --- /dev/null +++ b/interfaces/kits/napi/aafwk/datashare_ext_ability/datashare_ext_ability.js @@ -0,0 +1,66 @@ +/* + * 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 + * + * 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. + */ + +class DataShareExtAbility { + onCreate(want) { + console.log('onCreate, want:' + want.abilityName); + } + + getFileTypes(uri, mimeTypeFilter) { + console.log('getFileTypes, uri:' + uri); + } + + openFile(uri, mode) { + console.log('openFile, uri:' + uri); + } + + openRawFile(uri, mode) { + console.log('openRawFile, uri:' + uri); + } + + insert(uri, value) { + console.log('insert, uri:' + uri); + } + + update(uri, value, predicates) { + console.log('update, uri:' + uri); + } + + delete(uri, predicates) { + console.log('delete, uri:' + uri); + } + + query(uri, columns, predicates) { + console.log('query, uri:' + uri); + } + + getType(uri) { + console.log('getType, uri:' + uri); + } + + batchInsert(uri, values) { + console.log('batchInsert, uri:' + uri); + } + + normalizeUri(uri) { + console.log('normalizeUri, uri:' + uri); + } + + denormalizeUri(uri) { + console.log('denormalizeUri, uri:' + uri); + } +} + +export default DataShareExtAbility \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/datashare_ext_ability/datashare_ext_ability_module.cpp b/interfaces/kits/napi/aafwk/datashare_ext_ability/datashare_ext_ability_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a481dbf8ba6dcaa0666939fec65461b782cce961 --- /dev/null +++ b/interfaces/kits/napi/aafwk/datashare_ext_ability/datashare_ext_ability_module.cpp @@ -0,0 +1,57 @@ +/* + * 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 + * + * 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" + +extern const char _binary_datashare_ext_ability_js_start[]; +extern const char _binary_datashare_ext_ability_js_end[]; +extern const char _binary_datashare_ext_ability_abc_start[]; +extern const char _binary_datashare_ext_ability_abc_end[]; + +extern "C" __attribute__((constructor)) +void NAPI_application_DataShareExtAbility_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.DataShareExtAbility", + .fileName = "application/libdatashareextability_napi.so/DataShareExtAbility.js", + }; + + moduleManager->Register(&newModuleInfo); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_application_DataShareExtAbility_GetJSCode(const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_datashare_ext_ability_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_datashare_ext_ability_js_end - _binary_datashare_ext_ability_js_start; + } +} + +// datashare_ext_ability JS register +extern "C" __attribute__((visibility("default"))) +void NAPI_application_DataShareExtAbility_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_datashare_ext_ability_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_datashare_ext_ability_abc_end - _binary_datashare_ext_ability_abc_start; + } +} \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/datashare_ext_ability_context/BUILD.gn b/interfaces/kits/napi/aafwk/datashare_ext_ability_context/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..fea405b54aa8c4bc6e72dcba756f2d2e6a65a50c --- /dev/null +++ b/interfaces/kits/napi/aafwk/datashare_ext_ability_context/BUILD.gn @@ -0,0 +1,51 @@ +# 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 +# +# 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("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") + +ts2abc_gen_abc("gen_datashare_ext_ability_context_abc") { + src_js = rebase_path("datashare_ext_ability_context.js") + dst_file = rebase_path(target_out_dir + "/datashare_ext_ability_context.abc") + in_puts = [ "datashare_ext_ability_context.js" ] + out_puts = [ target_out_dir + "/datashare_ext_ability_context.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("datashare_ext_ability_context_js") { + input = "datashare_ext_ability_context.js" + output = target_out_dir + "/datashare_ext_ability_context.o" +} + +gen_js_obj("datashare_ext_ability_context_abc") { + input = + get_label_info(":gen_datashare_ext_ability_context_abc", + "target_out_dir") + "/datashare_ext_ability_context.abc" + output = target_out_dir + "/datashare_ext_ability_context_abc.o" + dep = ":gen_datashare_ext_ability_context_abc" +} + +ohos_shared_library("datashareextabilitycontext_napi") { + sources = [ "datashare_ext_ability_context_module.cpp" ] + + deps = [ + ":datashare_ext_ability_context_abc", + ":datashare_ext_ability_context_js", + ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module/application" + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/kits/napi/aafwk/datashare_ext_ability_context/datashare_ext_ability_context.js b/interfaces/kits/napi/aafwk/datashare_ext_ability_context/datashare_ext_ability_context.js new file mode 100644 index 0000000000000000000000000000000000000000..9da9778d8cb91df032218462b418eb1da487ec92 --- /dev/null +++ b/interfaces/kits/napi/aafwk/datashare_ext_ability_context/datashare_ext_ability_context.js @@ -0,0 +1,24 @@ +/* + * 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 + * + * 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. + */ + +var ExtensionContext = requireNapi("application.ExtensionContext") + +class DataShareExtAbilityContext extends ExtensionContext { + constructor(obj) { + super(obj); + } +} + +export default DataShareExtAbilityContext \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/datashare_ext_ability_context/datashare_ext_ability_context_module.cpp b/interfaces/kits/napi/aafwk/datashare_ext_ability_context/datashare_ext_ability_context_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a5cf65bb9ed7ae3558322af937f6d201a58e2cac --- /dev/null +++ b/interfaces/kits/napi/aafwk/datashare_ext_ability_context/datashare_ext_ability_context_module.cpp @@ -0,0 +1,57 @@ +/* + * 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 + * + * 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" + +extern const char _binary_datashare_ext_ability_context_js_start[]; +extern const char _binary_datashare_ext_ability_context_js_end[]; +extern const char _binary_datashare_ext_ability_context_abc_start[]; +extern const char _binary_datashare_ext_ability_context_abc_end[]; + +extern "C" __attribute__((constructor)) +void NAPI_application_DataShareExtAbilityContext_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.DataShareExtAbilityContext", + .fileName = "application/libdatashareextabilitycontext_napi.so/DataShareExtAbilityContext.js", + }; + + moduleManager->Register(&newModuleInfo); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_application_DataShareExtAbilityContext_GetJSCode(const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_datashare_ext_ability_context_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_datashare_ext_ability_context_js_end - _binary_datashare_ext_ability_context_js_start; + } +} + +// ability_context JS register +extern "C" __attribute__((visibility("default"))) +void NAPI_application_DataShareExtAbilityContext_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_datashare_ext_ability_context_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_datashare_ext_ability_context_abc_end - _binary_datashare_ext_ability_context_abc_start; + } +} diff --git a/interfaces/kits/napi/aafwk/featureAbility/BUILD.gn b/interfaces/kits/napi/aafwk/featureAbility/BUILD.gn index 9c89997fc34495f54a619db5469ce74116e9cbaa..aba4e97bab37c9690808522133e976bbc3157e82 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/BUILD.gn +++ b/interfaces/kits/napi/aafwk/featureAbility/BUILD.gn @@ -56,6 +56,7 @@ ohos_shared_library("featureability") { external_deps = [ "ability_runtime:ability_manager", "ability_runtime:app_manager", + "ability_runtime:napi_base_context", "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", diff --git a/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp b/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp index 2223343c1a152cb59c07c94517dfd9efa7d5761a..2c4f15aafefcc5a29ca60cffe3ab83b9c6afc440 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp +++ b/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp @@ -1281,7 +1281,7 @@ void GetDataAbilityHelperAsyncCompleteCB(napi_env env, napi_status status, void NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, dataAbilityHelperCB->uri, &uri)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, dataAbilityHelperCB->cbBase.cbInfo.callback, &callback)); NAPI_CALL_RETURN_VOID( - env, napi_new_instance(env, *(GetGlobalDataAbilityHelper()), 1, &uri, &dataAbilityHelperCB->result)); + env, napi_new_instance(env, GetGlobalDataAbilityHelper(env), 1, &uri, &dataAbilityHelperCB->result)); if (IsTypeForNapiValue(env, dataAbilityHelperCB->result, napi_object)) { result[PARAM1] = dataAbilityHelperCB->result; } else { @@ -1308,7 +1308,7 @@ void GetDataAbilityHelperPromiseCompleteCB(napi_env env, napi_status status, voi napi_value result = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, dataAbilityHelperCB->uri, &uri)); NAPI_CALL_RETURN_VOID( - env, napi_new_instance(env, *(GetGlobalDataAbilityHelper()), 1, &uri, &dataAbilityHelperCB->result)); + env, napi_new_instance(env, GetGlobalDataAbilityHelper(env), 1, &uri, &dataAbilityHelperCB->result)); if (IsTypeForNapiValue(env, dataAbilityHelperCB->result, napi_object)) { result = dataAbilityHelperCB->result; NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, dataAbilityHelperCB->cbBase.deferred, result)); diff --git a/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp b/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp index 9de7d8016eb84eba9c6484bdc6394e2428d999df..3e6eee3d2647b240b6ada64f5c56f2f37db3f25d 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp +++ b/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp @@ -27,6 +27,7 @@ #include "data_ability_result.h" #include "hilog_wrapper.h" #include "message_parcel.h" +#include "napi_base_context.h" #include "napi_data_ability_operation.h" #include "napi_data_ability_predicates.h" #include "napi_rdb_predicates.h" @@ -68,6 +69,8 @@ napi_value DataAbilityHelperInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("release", NAPI_Release), DECLARE_NAPI_FUNCTION("executeBatch", NAPI_ExecuteBatch), }; + + napi_value constructor; NAPI_CALL(env, napi_define_class(env, "dataAbilityHelper", @@ -76,7 +79,8 @@ napi_value DataAbilityHelperInit(napi_env env, napi_value exports) nullptr, sizeof(properties) / sizeof(*properties), properties, - GetGlobalDataAbilityHelper())); + &constructor)); + NAPI_CALL(env, SaveGlobalDataAbilityHelper(env, constructor)); g_dataAbilityHelperList.clear(); return exports; } @@ -84,27 +88,49 @@ napi_value DataAbilityHelperInit(napi_env env, napi_value exports) napi_value DataAbilityHelperConstructor(napi_env env, napi_callback_info info) { HILOG_INFO("%{public}s,called", __func__); - size_t argc = 1; - napi_value argv[1] = {nullptr}; + size_t argc = ARGS_TWO; + napi_value argv[ARGS_TWO] = {nullptr}; napi_value thisVar = nullptr; auto& dataAbilityHelperStatus = GetDataAbilityHelperStatus(); NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); NAPI_ASSERT(env, argc > 0, "Wrong number of arguments"); - std::string strUri = NapiValueToStringUtf8(env, argv[0]); - - napi_value global = nullptr; - NAPI_CALL(env, napi_get_global(env, &global)); - napi_value abilityObj = nullptr; - NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); + std::shared_ptr dataAbilityHelper = nullptr; + bool stageMode = false; + napi_status status = OHOS::AbilityRuntime::IsStageContext(env, argv[0], stageMode); + if (status != napi_ok) { + HILOG_INFO("argv[0] is not a context"); + auto ability = OHOS::AbilityRuntime::GetCurrentAbility(env); + if (ability == nullptr) { + HILOG_ERROR("Failed to get native context instance"); + return nullptr; + } + std::string strUri = NapiValueToStringUtf8(env, argv[0]); + HILOG_INFO("FA Model: ability = %{public}p strUri = %{public}s", ability, strUri.c_str()); + dataAbilityHelper = DataAbilityHelper::Creator(ability->GetContext(), std::make_shared(strUri)); + } else { + HILOG_INFO("argv[0] is a context"); + if (stageMode) { + auto context = OHOS::AbilityRuntime::GetStageModeContext(env, argv[0]); + if (context == nullptr) { + HILOG_ERROR("Failed to get native context instance"); + return nullptr; + } + std::string strUri = NapiValueToStringUtf8(env, argv[PARAM1]); + HILOG_INFO("Stage Model: context = %{public}p strUri = %{public}s", context.get(), strUri.c_str()); + dataAbilityHelper = DataAbilityHelper::Creator(context, std::make_shared(strUri)); + } else { + auto ability = OHOS::AbilityRuntime::GetCurrentAbility(env); + if (ability == nullptr) { + HILOG_ERROR("Failed to get native context instance"); + return nullptr; + } + std::string strUri = NapiValueToStringUtf8(env, argv[PARAM1]); + HILOG_INFO("FA Model: ability = %{public}p strUri = %{public}s", ability, strUri.c_str()); + dataAbilityHelper = DataAbilityHelper::Creator(ability->GetContext(), std::make_shared(strUri)); + } + } - Ability *ability = nullptr; - NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); - - HILOG_INFO("ability = %{public}p strUri = %{public}s", ability, strUri.c_str()); - HILOG_INFO("dataAbilityHelperList.size = %{public}zu", g_dataAbilityHelperList.size()); - std::shared_ptr dataAbilityHelper = - DataAbilityHelper::Creator(ability->GetContext(), std::make_shared(strUri)); if (dataAbilityHelper == nullptr) { HILOG_INFO("%{public}s, dataAbilityHelper is nullptr", __func__); dataAbilityHelperStatus = false; diff --git a/interfaces/kits/napi/aafwk/form_binding_data/form_binding_data.cpp b/interfaces/kits/napi/aafwk/form_binding_data/form_binding_data.cpp index 81866acdc5a238ea91cd54a69b0d447c1537e4bb..e4abf671e7d39562b774487772a13effb0b3389b 100644 --- a/interfaces/kits/napi/aafwk/form_binding_data/form_binding_data.cpp +++ b/interfaces/kits/napi/aafwk/form_binding_data/form_binding_data.cpp @@ -39,9 +39,16 @@ public: return (me != nullptr) ? me->OnCreateFormBindingData(*engine, *info) : nullptr; } + static NativeValue* AddFormBindingImage(NativeEngine* engine, NativeCallbackInfo* info) + { + HILOG_INFO("%{public}s called.", __func__); + FormBindingData* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnAddFormBindingImage(*engine, *info) : nullptr; + } private: NativeValue* OnCreateFormBindingData(NativeEngine& engine, NativeCallbackInfo& info); std::shared_ptr formProviderData_; + NativeValue* OnAddFormBindingImage(NativeEngine& engine, NativeCallbackInfo& info); }; NativeValue* FormBindingData::OnCreateFormBindingData(NativeEngine& engine, NativeCallbackInfo& info) @@ -89,6 +96,22 @@ NativeValue* FormBindingData::OnCreateFormBindingData(NativeEngine& engine, Nati HILOG_INFO("%{public}s called end.", __func__); return objValue; } + +NativeValue* FormBindingData::OnAddFormBindingImage(NativeEngine& engine, NativeCallbackInfo& info) +{ + HILOG_INFO("%{public}s called.", __func__); + if (info.argc == 0) { + HILOG_ERROR("%{public}s, not enough params", __func__); + return engine.CreateUndefined(); + } + + NativeValue* objValue = info.argv[1]; + NativeObject* object = ConvertNativeValueTo(objValue); + + object->SetProperty("image", info.argv[0]); + HILOG_INFO("%{public}s called end.", __func__); + return objValue; +} } NativeValue* FormBindingDataInit(NativeEngine* engine, NativeValue* exportObj) @@ -110,6 +133,7 @@ NativeValue* FormBindingDataInit(NativeEngine* engine, NativeValue* exportObj) object->SetNativePointer(formBindingData.release(), FormBindingData::Finalizer, nullptr); BindNativeFunction(*engine, *object, "createFormBindingData", FormBindingData::CreateFormBindingData); + BindNativeFunction(*engine, *object, "addFormBindingImage", FormBindingData::AddFormBindingImage); HILOG_INFO("%{public}s called end.", __func__); return exportObj; diff --git a/interfaces/kits/napi/aafwk/form_binding_data/form_binding_data.js b/interfaces/kits/napi/aafwk/form_binding_data/form_binding_data.js index 0580fa49db2bdf13ae93c2aef68fcaab659a21c4..b372d1077b9bb4fd683edc15aad08f00124c987e 100644 --- a/interfaces/kits/napi/aafwk/form_binding_data/form_binding_data.js +++ b/interfaces/kits/napi/aafwk/form_binding_data/form_binding_data.js @@ -17,6 +17,9 @@ class FormBindingData { createFormBindingData(obj) { this.data = obj; } + addFormBindingImage(image, obj) { + obj.image = image; + } } export default FormBindingData diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp index 13da15752555ca0e4e9a484864219297266a38c7..71d51480c3887c7cb8230f16a2dc033f858265b8 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp @@ -27,8 +27,9 @@ namespace OHOS { namespace AppExecFwk { -napi_value thread_local g_dataAbilityHelper; +napi_ref thread_local g_dataAbilityHelper; bool thread_local g_dataAbilityHelperStatus = false; + using NAPICreateJsRemoteObject = napi_value (*)(napi_env env, const sptr target); napi_value *GetGlobalClassContext(void) @@ -36,9 +37,16 @@ napi_value *GetGlobalClassContext(void) return AbilityRuntime::GetFAModeContextClassObject(); } -napi_value *GetGlobalDataAbilityHelper(void) +napi_status SaveGlobalDataAbilityHelper(napi_env env, napi_value constructor) +{ + return napi_create_reference(env, constructor, 1, &g_dataAbilityHelper); +} + +napi_value GetGlobalDataAbilityHelper(napi_env env) { - return &g_dataAbilityHelper; + napi_value constructor; + NAPI_CALL(env, napi_get_reference_value(env, g_dataAbilityHelper, &constructor)); + return constructor; } bool& GetDataAbilityHelperStatus() @@ -2330,6 +2338,14 @@ void StartAbilityExecuteCB(napi_env env, void *data) return; } + // inherit split mode + auto windowMode = asyncCallbackInfo->ability->GetCurrentWindowMode(); + if (windowMode == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY || + windowMode == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_SECONDARY) { + asyncCallbackInfo->param.want.SetParam(Want::PARAM_RESV_WINDOW_MODE, windowMode); + } + HILOG_INFO("window mode is %{public}d", windowMode); + ErrCode ret = ERR_OK; if (asyncCallbackInfo->param.setting == nullptr) { HILOG_INFO("%{public}s param.setting == nullptr call StartAbility.", __func__); @@ -3383,23 +3399,8 @@ napi_value NAPI_AcquireDataAbilityHelperCommon(napi_env env, napi_callback_info return WrapVoidToJS(env); } - napi_value global = nullptr; - napi_get_global(env, &global); - napi_value abilityObj = nullptr; - napi_get_named_property(env, global, "ability", &abilityObj); - Ability *ability = nullptr; - napi_get_value_external(env, abilityObj, (void **)&ability); - if (ability == nullptr) { - HILOG_ERROR("%{public}s, ability == nullptr", __func__); - if (dataAbilityHelperCB != nullptr) { - delete dataAbilityHelperCB; - dataAbilityHelperCB = nullptr; - } - return WrapVoidToJS(env); - } - dataAbilityHelperCB->cbBase.cbInfo.env = env; - dataAbilityHelperCB->cbBase.ability = ability; + dataAbilityHelperCB->cbBase.ability = nullptr; // temporary value assignment dataAbilityHelperCB->cbBase.errCode = NAPI_ERR_NO_ERROR; dataAbilityHelperCB->cbBase.abilityType = abilityType; napi_value ret = AcquireDataAbilityHelperWrap(env, info, dataAbilityHelperCB); @@ -3431,30 +3432,49 @@ napi_value AcquireDataAbilityHelperWrap(napi_env env, napi_callback_info info, D return nullptr; } - size_t requireArgc = ARGS_ONE; - size_t argc = ARGS_ONE; - napi_value args[ARGS_ONE] = {nullptr}; + size_t requireArgc = ARGS_TWO; + size_t argc = ARGS_TWO; + napi_value args[ARGS_TWO] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); if (argc > requireArgc) { HILOG_ERROR("%{public}s, Wrong argument count.", __func__); return nullptr; } + size_t uriIndex = PARAM0; + bool stageMode = false; + napi_status status = OHOS::AbilityRuntime::IsStageContext(env, args[0], stageMode); + if (status != napi_ok) { + HILOG_INFO("argv[0] is not a context, FA Model"); + } else { + uriIndex = PARAM1; + HILOG_INFO("argv[0] is a context, Stage Model: %{public}d", stageMode); + } + + if (!stageMode) { + auto ability = OHOS::AbilityRuntime::GetCurrentAbility(env); + if (ability == nullptr) { + HILOG_ERROR("Failed to get native context instance"); + return nullptr; + } + dataAbilityHelperCB->cbBase.ability = ability; + + if (!CheckAbilityType(&dataAbilityHelperCB->cbBase)) { + dataAbilityHelperCB->cbBase.errCode = NAPI_ERR_ABILITY_TYPE_INVALID; + HILOG_ERROR("%{public}s ability type invalid.", __func__); + return nullptr; + } + } + napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + NAPI_CALL(env, napi_typeof(env, args[uriIndex], &valuetype)); if (valuetype != napi_string) { HILOG_ERROR("%{public}s, Wrong argument type.", __func__); return nullptr; } - if (!CheckAbilityType(&dataAbilityHelperCB->cbBase)) { - dataAbilityHelperCB->cbBase.errCode = NAPI_ERR_ABILITY_TYPE_INVALID; - HILOG_ERROR("%{public}s ability type invalid.", __func__); - return nullptr; - } - napi_value result = nullptr; - NAPI_CALL(env, napi_new_instance(env, *(GetGlobalDataAbilityHelper()), 1, &args[PARAM0], &result)); + NAPI_CALL(env, napi_new_instance(env, GetGlobalDataAbilityHelper(env), uriIndex + 1, &args[PARAM0], &result)); if (!IsTypeForNapiValue(env, result, napi_object)) { HILOG_ERROR("%{public}s, IsTypeForNapiValue isn`t object", __func__); diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h index 963241e98ad7911f462aa19cb9ed7c881eb94dbb..293bf2024146ca05df5f83b876d0294ebecf9d18 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h @@ -25,8 +25,11 @@ namespace AppExecFwk { const std::int32_t STR_MAX_SIZE = 128; napi_value *GetGlobalClassContext(void); -napi_value *GetGlobalDataAbilityHelper(void); + +napi_status SaveGlobalDataAbilityHelper(napi_env env, napi_value constructor); +napi_value GetGlobalDataAbilityHelper(napi_env env); bool& GetDataAbilityHelperStatus(); + void SaveAppInfo(AppInfo_ &appInfo, const ApplicationInfo &appInfoOrg); napi_value WrapAppInfo(napi_env env, const AppInfo_ &appInfo); diff --git a/interfaces/kits/napi/aafwk/particleAbility/BUILD.gn b/interfaces/kits/napi/aafwk/particleAbility/BUILD.gn index f84c7f39300841b82ba3ce7952abe4846a19a675..e740320e542e53fa88349319d74f9c82bf7154fe 100644 --- a/interfaces/kits/napi/aafwk/particleAbility/BUILD.gn +++ b/interfaces/kits/napi/aafwk/particleAbility/BUILD.gn @@ -55,6 +55,7 @@ ohos_shared_library("particleability") { external_deps = [ "ability_runtime:ability_manager", "ability_runtime:app_manager", + "ability_runtime:napi_base_context", "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", diff --git a/ohos.build b/ohos.build old mode 100755 new mode 100644 index c21ef63994e899d8bbc70ec2cd1e1b5878dced80..3aee6a65440edb0762aef1a67ac6cd09df6121d3 --- a/ohos.build +++ b/ohos.build @@ -4,6 +4,7 @@ "module_list": [ "//foundation/aafwk/standard/services:services_target", "//foundation/aafwk/standard/interfaces/innerkits:innerkits_target", + "//foundation/aafwk/standard/frameworks/kits/ability/native:datashare_ext_ability_module", "//foundation/aafwk/standard/frameworks/kits/ability/native:static_subscriber_ipc", "//foundation/aafwk/standard/frameworks/kits/ability/native:service_extension_module", "//foundation/aafwk/standard/sa_profile:aafwk_sa_profile", @@ -138,12 +139,12 @@ "header_base": "//foundation/aafwk/standard/common/task_dispatcher/include", "header_files": [ "dispatcher/parallel_task_dispatcher.h", - "dispatcher/task_dispatcher_context", + "dispatcher/task_dispatcher_context.h", "threading/runnable.h", "task/task.h" ] }, - "name": "//foundation/aafwk/standard/common:common_target" + "name": "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher" } ], "test_list": [ @@ -172,16 +173,6 @@ "//foundation/aafwk/standard/tools/test:unittest" ] }, - "zidl": { - "module_list": [ - "//foundation/aafwk/standard/zidl/test/native:zidl_client_test", - "//foundation/aafwk/standard/zidl/test/native:zidl_server_test" - ], - "inner_kits": [ - ], - "test_list": [ - ] - }, "form_runtime": { "module_list": [ "//foundation/aafwk/standard/sa_profile:form_sa_profile", diff --git a/services/abilitymgr/include/ability_connect_manager.h b/services/abilitymgr/include/ability_connect_manager.h index 1c070cc165022d97b28f9c0f44f91f084ec1666e..09313891463febe0d19c531ddc500935ac805494 100644 --- a/services/abilitymgr/include/ability_connect_manager.h +++ b/services/abilitymgr/include/ability_connect_manager.h @@ -316,6 +316,7 @@ private: void HandleStartTimeoutTask(const std::shared_ptr &abilityRecord, int resultCode); void HandleStopTimeoutTask(const std::shared_ptr &abilityRecord); void HandleDisconnectTask(const ConnectListType &connectlist); + void HandleTerminateDisconnectTask(const ConnectListType& connectlist); /** * IsAbilityConnected. diff --git a/services/abilitymgr/include/ability_manager_proxy.h b/services/abilitymgr/include/ability_manager_proxy.h index 75819fbc38fec7368ba827dfc67d83d2ac0a43ce..e4b7cebeb9e8e423cc400c61e033334291b98236 100644 --- a/services/abilitymgr/include/ability_manager_proxy.h +++ b/services/abilitymgr/include/ability_manager_proxy.h @@ -630,6 +630,24 @@ public: * @return Returns ERR_OK on success, others on failure. */ virtual int DelegatorDoAbilityBackground(const sptr &token) override; + + /** + * Calls this interface to move the ability to the foreground. + * + * @param token, ability's token. + * @param flag, use for lock or unlock flag and so on. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DoAbilityForeground(const sptr &token, uint32_t flag) override; + + /** + * Calls this interface to move the ability to the background. + * + * @param token, ability's token. + * @param flag, use for lock or unlock flag and so on. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DoAbilityBackground(const sptr &token, uint32_t flag) override; /** * Send not response process ID to ability manager service. diff --git a/services/abilitymgr/include/ability_manager_service.h b/services/abilitymgr/include/ability_manager_service.h index a2c40fc3d196f824c423fc6b0d904cf0b3fc2159..836680271205b8852ff3dad687e20c38d3cdaae4 100644 --- a/services/abilitymgr/include/ability_manager_service.h +++ b/services/abilitymgr/include/ability_manager_service.h @@ -821,6 +821,24 @@ public: */ virtual int DelegatorDoAbilityBackground(const sptr &token) override; + /** + * Calls this interface to move the ability to the foreground. + * + * @param token, ability's token. + * @param flag, use for lock or unlock flag and so on. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DoAbilityForeground(const sptr &token, uint32_t flag) override; + + /** + * Calls this interface to move the ability to the background. + * + * @param token, ability's token. + * @param flag, use for lock or unlock flag and so on. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DoAbilityBackground(const sptr &token, uint32_t flag) override; + bool IsAbilityControllerStart(const Want &want, const std::string &bundleName); bool IsAbilityControllerForeground(const std::string &bundleName); @@ -845,7 +863,7 @@ public: static constexpr uint32_t INACTIVE_TIMEOUT = 500; // ms static constexpr uint32_t BACKGROUND_TIMEOUT = 10000; // ms static constexpr uint32_t TERMINATE_TIMEOUT = 10000; // ms - static constexpr uint32_t CONNECT_TIMEOUT = 500; // ms + static constexpr uint32_t CONNECT_TIMEOUT = 3000; // ms static constexpr uint32_t DISCONNECT_TIMEOUT = 500; // ms static constexpr uint32_t COMMAND_TIMEOUT = 5000; // ms static constexpr uint32_t SYSTEM_UI_TIMEOUT = 5000; // ms diff --git a/services/abilitymgr/include/ability_manager_stub.h b/services/abilitymgr/include/ability_manager_stub.h index ee41214b1539c09fd7673d8dfc00633e0c2a3960..08bacb824caa2785704e9e4b3c9a011d17086494 100644 --- a/services/abilitymgr/include/ability_manager_stub.h +++ b/services/abilitymgr/include/ability_manager_stub.h @@ -36,6 +36,23 @@ public: virtual int OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + /** + * Calls this interface to move the ability to the foreground. + * + * @param token, ability's token. + * @param flag, use for lock or unlock flag and so on. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DoAbilityForeground(const sptr &token, uint32_t flag) override; + + /** + * Calls this interface to move the ability to the background. + * + * @param token, ability's token. + * @param flag, use for lock or unlock flag and so on. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DoAbilityBackground(const sptr &token, uint32_t flag) override; private: void FirstStepInit(); void SecondStepInit(); @@ -149,6 +166,8 @@ private: int GetCurrentTopAbilityInner(MessageParcel &data, MessageParcel &reply); int DelegatorDoAbilityForegroundInner(MessageParcel &data, MessageParcel &reply); int DelegatorDoAbilityBackgroundInner(MessageParcel &data, MessageParcel &reply); + int DoAbilityForegroundInner(MessageParcel &data, MessageParcel &reply); + int DoAbilityBackgroundInner(MessageParcel &data, MessageParcel &reply); int IsRunningInStabilityTestInner(MessageParcel &data, MessageParcel &reply); diff --git a/services/abilitymgr/include/ability_record.h b/services/abilitymgr/include/ability_record.h index f885b143ed440ea43d85778d65a710916f35eb3c..57ac8aad3af1e875508a2390404a1cbfe53979b7 100644 --- a/services/abilitymgr/include/ability_record.h +++ b/services/abilitymgr/include/ability_record.h @@ -781,6 +781,7 @@ public: void SetSpecifiedFlag(const std::string &flag); std::string GetSpecifiedFlag() const; + LifeCycleStateInfo lifeCycleStateInfo_; // target life state info protected: void SendEvent(uint32_t msg, uint32_t timeOut); @@ -789,7 +790,6 @@ protected: std::unique_ptr lifecycleDeal_ = {}; // life manager used to schedule life AbilityState currentState_ = AbilityState::INITIAL; // current life state Want want_ = {}; // want to start this ability - LifeCycleStateInfo lifeCycleStateInfo_; // target life state info static int64_t g_abilityRecordEventId_; int64_t eventId_ = 0; // post event id diff --git a/services/abilitymgr/include/mission_list_manager.h b/services/abilitymgr/include/mission_list_manager.h index a1d351aeeca864fc0bd37013e75ea3fb4ccbfc28..1c00aa59840770be50ec001a499f9431d29b1f90 100644 --- a/services/abilitymgr/include/mission_list_manager.h +++ b/services/abilitymgr/include/mission_list_manager.h @@ -68,6 +68,8 @@ public: int MoveMissionToFront(int32_t missionId); + int MoveMissionToFront(int32_t missionId, bool isCallerFromLauncher); + /** * OnAbilityRequestDone, app manager service call this interface after ability request done. * @@ -324,7 +326,6 @@ private: const std::shared_ptr &callerAbility, const AbilityRequest &abilityRequest); int StartAbility(const std::shared_ptr ¤tTopAbility, const std::shared_ptr &callerAbility, const AbilityRequest &abilityRequest); - int MoveMissionToFront(int32_t missionId, bool isCallerFromLauncher); int MinimizeAbilityLocked(const std::shared_ptr &abilityRecord); std::shared_ptr GetCurrentTopAbilityLocked() const; std::shared_ptr GetTargetMissionList( diff --git a/services/abilitymgr/src/ability_connect_callback_stub.cpp b/services/abilitymgr/src/ability_connect_callback_stub.cpp index df6f851bec165cd5a783de8cbf4f656fc18322a0..783df6ab6e98b4a15ad19860678af28b58161bb1 100644 --- a/services/abilitymgr/src/ability_connect_callback_stub.cpp +++ b/services/abilitymgr/src/ability_connect_callback_stub.cpp @@ -72,7 +72,7 @@ void AbilityConnectionProxy::OnAbilityDisconnectDone(const AppExecFwk::ElementNa int error; MessageParcel data; MessageParcel reply; - MessageOption option; + MessageOption option(MessageOption::TF_ASYNC); if (!WriteInterfaceToken(data)) { return; diff --git a/services/abilitymgr/src/ability_connect_manager.cpp b/services/abilitymgr/src/ability_connect_manager.cpp index c07fb13c8d325905698d0d81076f9879bc0478fc..fde024bf6d8f2286ecfc3a6d554ceb4873026e68 100755 --- a/services/abilitymgr/src/ability_connect_manager.cpp +++ b/services/abilitymgr/src/ability_connect_manager.cpp @@ -136,18 +136,18 @@ int AbilityConnectManager::TerminateAbilityLocked(const sptr &tok return ERR_OK; } - if (abilityRecord->GetConnectRecordList().empty()) { - HILOG_INFO("Service ability has no any connection, and not started , need terminate."); - auto timeoutTask = [abilityRecord, connectManager = shared_from_this()]() { - HILOG_WARN("Disconnect ability terminate timeout."); - connectManager->HandleStopTimeoutTask(abilityRecord); - }; - abilityRecord->Terminate(timeoutTask); - } else { - HILOG_WARN("Target service has been connected. It cannot be stopped."); - return TERMINATE_SERVICE_IS_CONNECTED; + if (!abilityRecord->GetConnectRecordList().empty()) { + HILOG_INFO("Target service has been connected. Post disconnect task."); + auto connectRecordList = abilityRecord->GetConnectRecordList(); + HandleTerminateDisconnectTask(connectRecordList); } + auto timeoutTask = [abilityRecord, connectManager = shared_from_this()]() { + HILOG_WARN("Disconnect ability terminate timeout."); + connectManager->HandleStopTimeoutTask(abilityRecord); + }; + abilityRecord->Terminate(timeoutTask); + return ERR_OK; } @@ -182,18 +182,18 @@ int AbilityConnectManager::StopServiceAbilityLocked(const AbilityRequest &abilit return ERR_OK; } - if (abilityRecord->GetConnectRecordList().empty()) { - HILOG_INFO("Service ability has no any connection, and no started , need terminate."); - auto timeoutTask = [abilityRecord, connectManager = shared_from_this()]() { - HILOG_WARN("Disconnect ability terminate timeout."); - connectManager->HandleStopTimeoutTask(abilityRecord); - }; - abilityRecord->Terminate(timeoutTask); - } else { - HILOG_WARN("Target service has been connected. It cannot be stopped."); - return TERMINATE_SERVICE_IS_CONNECTED; + if (!abilityRecord->GetConnectRecordList().empty()) { + HILOG_INFO("Target service has been connected. Post disconnect task."); + auto connectRecordList = abilityRecord->GetConnectRecordList(); + HandleTerminateDisconnectTask(connectRecordList); } + auto timeoutTask = [abilityRecord, connectManager = shared_from_this()]() { + HILOG_WARN("Disconnect ability terminate timeout."); + connectManager->HandleStopTimeoutTask(abilityRecord); + }; + abilityRecord->Terminate(timeoutTask); + return ERR_OK; } @@ -673,6 +673,24 @@ void AbilityConnectManager::HandleDisconnectTask(const ConnectListType &connectl } } +void AbilityConnectManager::HandleTerminateDisconnectTask(const ConnectListType& connectlist) +{ + HILOG_DEBUG("Disconnect ability when terminate."); + std::lock_guard guard(Lock_); + for (auto& connectRecord : connectlist) { + if (!connectRecord) { + continue; + } + auto targetService = connectRecord->GetAbilityRecord(); + if (targetService) { + HILOG_WARN("This record complete disconnect directly. recordId:%{public}d", connectRecord->GetRecordId()); + connectRecord->CompleteDisconnect(ERR_OK, false); + targetService->RemoveConnectRecordFromList(connectRecord); + RemoveConnectionRecordFromMap(connectRecord); + }; + } +} + int AbilityConnectManager::DispatchInactive(const std::shared_ptr &abilityRecord, int state) { CHECK_POINTER_AND_RETURN(eventHandler_, ERR_INVALID_VALUE); diff --git a/services/abilitymgr/src/ability_manager_proxy.cpp b/services/abilitymgr/src/ability_manager_proxy.cpp index 11095952104e1426545e4db5c7a559b695fb3183..2741f8101b9442961cb428c0ed41d6bfad797738 100644 --- a/services/abilitymgr/src/ability_manager_proxy.cpp +++ b/services/abilitymgr/src/ability_manager_proxy.cpp @@ -2493,6 +2493,64 @@ int AbilityManagerProxy::DelegatorDoAbilityBackground(const sptr return reply.ReadInt32(); } +int AbilityManagerProxy::DoAbilityForeground(const sptr &token, uint32_t flag) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + + if (!data.WriteParcelable(token)) { + HILOG_ERROR("data write failed."); + return ERR_INVALID_VALUE; + } + + if (!data.WriteUint32(flag)) { + HILOG_ERROR("flag write failed."); + return ERR_INVALID_VALUE; + } + + auto error = Remote()->SendRequest(IAbilityManager::DO_ABILITY_FOREGROUND, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("Send request error: %{public}d", error); + return error; + } + + return reply.ReadInt32(); +} + +int AbilityManagerProxy::DoAbilityBackground(const sptr &token, uint32_t flag) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + + if (!data.WriteParcelable(token)) { + HILOG_ERROR("data write failed."); + return ERR_INVALID_VALUE; + } + + if (!data.WriteUint32(flag)) { + HILOG_ERROR("flag write failed."); + return ERR_INVALID_VALUE; + } + + auto error = Remote()->SendRequest(IAbilityManager::DO_ABILITY_BACKGROUND, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("Send request error: %{public}d", error); + return error; + } + + return reply.ReadInt32(); +} + bool AbilityManagerProxy::SendANRProcessID(int pid) { int error; diff --git a/services/abilitymgr/src/ability_manager_service.cpp b/services/abilitymgr/src/ability_manager_service.cpp index 552d089a9d5cfe9b1b1de3c6dc97a9465b964bee..489943e79ad8122e1c02d87078325adfa80e34d0 100755 --- a/services/abilitymgr/src/ability_manager_service.cpp +++ b/services/abilitymgr/src/ability_manager_service.cpp @@ -59,12 +59,14 @@ const int32_t U0_USER_ID = 0; static const int EXPERIENCE_MEM_THRESHOLD = 20; constexpr auto DATA_ABILITY_START_TIMEOUT = 5s; constexpr int32_t NON_ANONYMIZE_LENGTH = 6; +constexpr uint32_t SCENE_FLAG_NORMAL = 0; const int32_t EXTENSION_SUPPORT_API_VERSION = 8; const int32_t MAX_NUMBER_OF_DISTRIBUTED_MISSIONS = 20; const int32_t MAX_NUMBER_OF_CONNECT_BMS = 15; const std::string EMPTY_DEVICE_ID = ""; const std::string PKG_NAME = "ohos.distributedhardware.devicemanager"; const std::string ACTION_CHOOSE = "ohos.want.action.select"; +const std::string PERMISSION_SET_ABILITY_CONTROLLER = "ohos.permission.SET_ABILITY_CONTROLLER"; const std::map AbilityManagerService::dumpMap = { std::map::value_type("--all", KEY_DUMP_ALL), std::map::value_type("-a", KEY_DUMP_ALL), @@ -2390,7 +2392,9 @@ int AbilityManagerService::GenerateAbilityRequest( } } - request.appInfo = request.abilityInfo.applicationInfo; + auto appName = request.abilityInfo.applicationInfo.name; + auto appFlag = AppExecFwk::ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMISSION; + bms->GetApplicationInfo(appName, appFlag, userId, request.appInfo); if (request.appInfo.name.empty() || request.appInfo.bundleName.empty()) { HILOG_ERROR("Get app info failed."); return RESOLVE_APP_ERR; @@ -3853,9 +3857,23 @@ int AbilityManagerService::SetAbilityController(const sptr & bool imAStabilityTest) { HILOG_DEBUG("%{public}s, imAStabilityTest: %{public}d", __func__, imAStabilityTest); + auto bms = GetBundleManager(); + if (bms == nullptr) { + HILOG_ERROR("bms nullptr"); + return ERR_INVALID_VALUE; + } + std::string bundleName; + int uid = IPCSkeleton::GetCallingUid(); + bms->GetBundleNameForUid(uid, bundleName); + HILOG_INFO("%{public}s, bundleName: %{public}s, uid = %{public}d", __func__, bundleName.c_str(), uid); + if (bms->CheckPermission(bundleName, PERMISSION_SET_ABILITY_CONTROLLER) == 0) { + HILOG_ERROR("PERMISSION_SET_ABILITY_CONTROLLER check failed"); + return CHECK_PERMISSION_FAILED; + } std::lock_guard guard(globalLock_); abilityController_ = abilityController; controllerIsAStabilityTest_ = imAStabilityTest; + HILOG_DEBUG("%{public}s, end", __func__); return ERR_OK; } @@ -3928,7 +3946,6 @@ int32_t AbilityManagerService::InitAbilityInfoFromExtension(AppExecFwk::Extensio abilityInfo.writePermission = extensionInfo.writePermission; abilityInfo.extensionAbilityType = extensionInfo.type; abilityInfo.visible = extensionInfo.visible; - abilityInfo.applicationInfo = extensionInfo.applicationInfo; abilityInfo.resourcePath = extensionInfo.resourcePath; abilityInfo.enabled = extensionInfo.enabled; abilityInfo.isModuleJson = true; @@ -3945,7 +3962,8 @@ int32_t AbilityManagerService::GetAbilityInfoFromExtension(const Want &want, App std::string abilityName = elementName.GetAbilityName(); AppExecFwk::BundleMgrClient bundleClient; AppExecFwk::BundleInfo bundleInfo; - if (!bundleClient.GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO, bundleInfo)) { + if (!bundleClient.GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO, bundleInfo, + GetUserId())) { HILOG_ERROR("Failed to get bundle info when generate ability request."); return RESOLVE_APP_ERR; } @@ -3958,6 +3976,7 @@ int32_t AbilityManagerService::GetAbilityInfoFromExtension(const Want &want, App found = true; HILOG_DEBUG("GetExtensionAbilityInfo, extension ability info found, name=%{public}s", abilityName.c_str()); abilityInfo.applicationName = bundleInfo.applicationInfo.name; + abilityInfo.applicationInfo = bundleInfo.applicationInfo; InitAbilityInfoFromExtension(extensionInfo, abilityInfo); break; } @@ -4059,6 +4078,37 @@ int AbilityManagerService::DelegatorDoAbilityBackground(const sptr &token, uint32_t flag) +{ + HILOG_DEBUG("DoAbilityForeground, sceneFlag:%{public}d", flag); + CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE); + + auto abilityRecord = Token::GetAbilityRecordByToken(token); + CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); + + auto missionId = GetMissionIdByAbilityToken(token); + CHECK_POINTER_AND_RETURN(currentMissionListManager_, ERR_NO_INIT); + + abilityRecord->lifeCycleStateInfo_.sceneFlag = flag; + int ret = currentMissionListManager_->MoveMissionToFront(missionId, false); + abilityRecord->lifeCycleStateInfo_.sceneFlag = SCENE_FLAG_NORMAL; + return ret; +} + +int AbilityManagerService::DoAbilityBackground(const sptr &token, uint32_t flag) +{ + HILOG_DEBUG("DoAbilityBackground, sceneFlag:%{public}d", flag); + CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE); + + auto abilityRecord = Token::GetAbilityRecordByToken(token); + CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); + + abilityRecord->lifeCycleStateInfo_.sceneFlag = flag; + int ret = MinimizeAbility(token); + abilityRecord->lifeCycleStateInfo_.sceneFlag = SCENE_FLAG_NORMAL; + return ret; +} + int AbilityManagerService::DelegatorMoveMissionToFront(int32_t missionId) { HILOG_INFO("enter missionId : %{public}d", missionId); diff --git a/services/abilitymgr/src/ability_manager_stub.cpp b/services/abilitymgr/src/ability_manager_stub.cpp index d9c23205e6e99b831d49e561d1bab9e4b095837a..756fe0cc7fd519e3b0b57a4481a3abc6c62e6739 100644 --- a/services/abilitymgr/src/ability_manager_stub.cpp +++ b/services/abilitymgr/src/ability_manager_stub.cpp @@ -146,6 +146,8 @@ void AbilityManagerStub::ThirdStepInit() requestFuncMap_[GET_CURRENT_TOP_ABILITY] = &AbilityManagerStub::GetCurrentTopAbilityInner; requestFuncMap_[DELEGATOR_DO_ABILITY_FOREGROUND] = &AbilityManagerStub::DelegatorDoAbilityForegroundInner; requestFuncMap_[DELEGATOR_DO_ABILITY_BACKGROUND] = &AbilityManagerStub::DelegatorDoAbilityBackgroundInner; + requestFuncMap_[DO_ABILITY_FOREGROUND] = &AbilityManagerStub::DoAbilityForegroundInner; + requestFuncMap_[DO_ABILITY_BACKGROUND] = &AbilityManagerStub::DoAbilityBackgroundInner; } int AbilityManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -1447,6 +1449,35 @@ int AbilityManagerStub::DelegatorDoAbilityBackgroundInner(MessageParcel &data, M return NO_ERROR; } +int AbilityManagerStub::DoAbilityForeground(const sptr &token, uint32_t flag) +{ + return 0; +} + +int AbilityManagerStub::DoAbilityBackground(const sptr &token, uint32_t flag) +{ + return 0; +} + +int AbilityManagerStub::DoAbilityForegroundInner(MessageParcel &data, MessageParcel &reply) +{ + sptr token = data.ReadParcelable(); + int32_t flag = data.ReadUint32(); + auto result = DoAbilityForeground(token, flag); + reply.WriteInt32(result); + + return NO_ERROR; +} + +int AbilityManagerStub::DoAbilityBackgroundInner(MessageParcel &data, MessageParcel &reply) +{ + sptr token = data.ReadParcelable(); + int32_t flag = data.ReadUint32(); + auto result = DoAbilityBackground(token, flag); + reply.WriteInt32(result); + return NO_ERROR; +} + int AbilityManagerStub::SendANRProcessIDInner(MessageParcel &data, MessageParcel &reply) { int32_t pid = data.ReadInt32(); diff --git a/services/abilitymgr/src/lifecycle_state_info.cpp b/services/abilitymgr/src/lifecycle_state_info.cpp index 62df134bd64976720b4829cf1abb93fa90342c47..b82b49f54f7e3a96f3d81e518c68e9c0e68f8bf3 100644 --- a/services/abilitymgr/src/lifecycle_state_info.cpp +++ b/services/abilitymgr/src/lifecycle_state_info.cpp @@ -44,6 +44,7 @@ bool LifeCycleStateInfo::ReadFromParcel(Parcel &parcel) } launchParam = *launchInfo; useNewMission = parcel.ReadBool(); + sceneFlag = parcel.ReadUint32(); return true; } @@ -95,6 +96,9 @@ bool LifeCycleStateInfo::Marshalling(Parcel &parcel) const if (!parcel.WriteBool(useNewMission)) { return false; } + if (!parcel.WriteUint32(sceneFlag)) { + return false; + } return true; } } // namespace AAFwk diff --git a/services/abilitymgr/src/mission_list_manager.cpp b/services/abilitymgr/src/mission_list_manager.cpp index 48f7dfc62f33b3ad94c996ddca9259a229d16acc..218a3cd70a9127c49e8f2467c0db2bfc6f6f6441 100644 --- a/services/abilitymgr/src/mission_list_manager.cpp +++ b/services/abilitymgr/src/mission_list_manager.cpp @@ -75,11 +75,6 @@ int MissionListManager::StartAbility(const AbilityRequest &abilityRequest) auto state = callerAbility->GetAbilityState(); HILOG_DEBUG("callerAbility is: %{public}s, state: %{public}s", element.c_str(), AbilityRecord::ConvertAbilityState(state).c_str()); - if (state != FOREGROUND_NEW) { - HILOG_INFO("caller ability is not foreground, so enqueue ability for waiting."); - EnqueueWaittingAbility(abilityRequest); - return START_ABILITY_WAITING; - } } return StartAbility(currentTopAbility, callerAbility, abilityRequest); diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/ability_manager_stub_mock.h b/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/ability_manager_stub_mock.h index d2f2f50f272e0c61202559cf6bf64af3d7e1f0c8..13b4ea9b19322baabadec6b257728531d955a465 100644 --- a/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/ability_manager_stub_mock.h +++ b/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/ability_manager_stub_mock.h @@ -441,6 +441,16 @@ public: { return 0; } + + virtual int DoAbilityForeground(const sptr &token, uint32_t flag) override + { + return 0; + } + + virtual int DoAbilityBackground(const sptr &token, uint32_t flag) override + { + return 0; + } }; } // namespace AAFwk } // namespace OHOS diff --git a/services/formmgr/src/form_mgr_adapter.cpp b/services/formmgr/src/form_mgr_adapter.cpp index 66abcf4432a6b089efa563c9a66821f7701eb468..3d9477f1af05bd5bb62a0b8b7ba48d2ca8b1ee4e 100644 --- a/services/formmgr/src/form_mgr_adapter.cpp +++ b/services/formmgr/src/form_mgr_adapter.cpp @@ -730,6 +730,10 @@ ErrCode FormMgrAdapter::GetFormConfigInfo(const Want &want, FormItemInfo &formCo APP_LOGE("addForm can not find target form info"); return errCode; } + if (!formInfo.IsValid()) { + APP_LOGE("The form info is invalid"); + return ERR_APPEXECFWK_FORM_GET_INFO_FAILED; + } errCode = GetFormItemInfo(want, bundleInfo, formInfo, formConfigInfo); if (errCode != ERR_OK) { diff --git a/services/formmgr/test/mock/include/mock_ability_manager.h b/services/formmgr/test/mock/include/mock_ability_manager.h index 4fe0fa5f41913f25a0915d618b05dd1813b3ef3f..d1983711bb753e7967857bc098f6998fee57617d 100644 --- a/services/formmgr/test/mock/include/mock_ability_manager.h +++ b/services/formmgr/test/mock/include/mock_ability_manager.h @@ -361,6 +361,16 @@ public: { return 0; } + + virtual int DoAbilityForeground(const sptr &token, uint32_t flag) override + { + return 0; + } + + virtual int DoAbilityBackground(const sptr &token, uint32_t flag) override + { + return 0; + } }; class MockAbilityMgrStub : public IRemoteStub { @@ -857,6 +867,16 @@ public: { return 0; } + + virtual int DoAbilityForeground(const sptr &token, uint32_t flag) override + { + return 0; + } + + virtual int DoAbilityBackground(const sptr &token, uint32_t flag) override + { + return 0; + } private: Semaphore sem_; }; diff --git a/services/test/mock/include/appmgr/mock_ability_mgr_host.h b/services/test/mock/include/appmgr/mock_ability_mgr_host.h index 208285131c4c1cc5a76e9b679b597521b4fd6e92..81bdeac7b6a99c70f2f7ba3c901c35cc67dbb63d 100644 --- a/services/test/mock/include/appmgr/mock_ability_mgr_host.h +++ b/services/test/mock/include/appmgr/mock_ability_mgr_host.h @@ -393,6 +393,14 @@ public: { return 0; } + virtual int DoAbilityForeground(const sptr &token, uint32_t flag) override + { + return 0; + } + virtual int DoAbilityBackground(const sptr &token, uint32_t flag) override + { + return 0; + } }; } // namespace AppExecFwk } // namespace OHOS diff --git a/services/test/mock/include/mock_context.h b/services/test/mock/include/mock_context.h index 9ccf7227c5eaefa9f93568961b605302b1543eb3..0cf1c77870358c474fa2cbabba9ae1d6a04da02b 100644 --- a/services/test/mock/include/mock_context.h +++ b/services/test/mock/include/mock_context.h @@ -92,6 +92,7 @@ public: const std::string &name, const TaskPriority &priority) = 0; virtual std::shared_ptr GetGlobalTaskDispatcher(const TaskPriority &priority) = 0; friend DataAbilityHelper; + friend DataShareHelper; friend ContinuationConnector; protected: virtual sptr GetToken() = 0; diff --git a/tools/aa/src/ability_command.cpp b/tools/aa/src/ability_command.cpp index a241a63ec4b8583c91ae3071bc58b8ec76c26319..b08e0b38bef21056a1499384e31421e655fbc544 100644 --- a/tools/aa/src/ability_command.cpp +++ b/tools/aa/src/ability_command.cpp @@ -133,7 +133,7 @@ ErrCode AbilityManagerShellCommand::CreateMessageMap() }, { START_ABILITY_WAITING, - "error: start ability waiting.", + "start ability successfully. waiting...", }, { TERMINATE_LAUNCHER_DENIED, @@ -508,8 +508,9 @@ ErrCode AbilityManagerShellCommand::RunAsStartAbility() resultReceiver_ = STRING_START_ABILITY_OK + "\n"; } else { HILOG_INFO("%{public}s result = %{public}d", STRING_START_ABILITY_NG.c_str(), result); - resultReceiver_ = STRING_START_ABILITY_NG + "\n"; - + if (result != START_ABILITY_WAITING) { + resultReceiver_ = STRING_START_ABILITY_NG + "\n"; + } resultReceiver_.append(GetMessageFromCode(result)); } } else { diff --git a/zidl/bundle.json b/zidl/bundle.json index 5152547cc088f0c6bd4885e60a8aef3c9ba33613..5127a051270eadcfa02b16b87ed6df6283e59b82 100644 --- a/zidl/bundle.json +++ b/zidl/bundle.json @@ -1,6 +1,6 @@ { "name": "@ohos/zidl", - "description": "提供自动生成Extension Js服务端及客户端接口文件的能力", + "description": "提供自动生成Extension 服务端及客户端接口文件的能力", "version": "3.1", "license": "Apache License 2.0", "publishAs": "code-segment", @@ -29,10 +29,7 @@ "third_party": [] }, "build": { - "sub_component": [ - "//foundation/aafwk/standard/zidl/test/native:zidl_client_test", - "//foundation/aafwk/standard/zidl/test/native:zidl_server_test" - ], + "sub_component": [], "inner_kits": [], "test": [] }