diff --git a/OAT.xml b/OAT.xml index 96b39662a64dc3b78a7dd784ee9ea8bb2effc280..d4ec02817f580dfb0507ccf12901279d6a74d7df 100644 --- a/OAT.xml +++ b/OAT.xml @@ -62,7 +62,9 @@ Note:If the text contains special characters, please escape them according to th - + + + diff --git a/bundle.json b/bundle.json index b0357886a0f337a6e44c20b3910c2c7e3b77365b..7eeed0eb69d6aa39c5f3428bf365f65dac8f3bcf 100644 --- a/bundle.json +++ b/bundle.json @@ -24,7 +24,6 @@ "appspawn", "bytrace_standard", "ces_standard", - "ces_standard", "device_manager_base", "distributeddatamgr_appdatamgr", "distributedschedule_dms_fwk", @@ -59,47 +58,30 @@ "//foundation/aafwk/standard/sa_profile:aafwk_sa_profile", "//foundation/aafwk/standard/interfaces/kits/napi:napi_packages", "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native", + "//foundation/aafwk/standard/common:common_target", "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", - "//foundation/aafwk/standard/frameworks/kits/appkit:appexec" + "//foundation/aafwk/standard/frameworks/kits/appkit:appexec", + "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits" ], "inner_kits": [ { "header": { - "header_base": "//foundation/aafwk/standard/interfaces/innerkits/base/include/", - "header_files": [ - "ohos/aafwk/base/array_wrapper.h", - "ohos/aafwk/base/base_def.h", - "ohos/aafwk/base/base_interfaces.h", - "ohos/aafwk/base/base_object.h", - "ohos/aafwk/base/base_types.h", - "ohos/aafwk/base/bool_wrapper.h", - "ohos/aafwk/base/byte_wrapper.h", - "ohos/aafwk/base/double_wrapper.h", - "ohos/aafwk/base/float_wrapper.h", - "ohos/aafwk/base/int_wrapper.h", - "ohos/aafwk/base/light_refbase.h", - "ohos/aafwk/base/long_wrapper.h", - "ohos/aafwk/base/short_wrapper.h", - "ohos/aafwk/base/string_wrapper.h" - ] - }, - "name": "//foundation/aafwk/standard/interfaces/innerkits/base:base" - }, - { - "header": { - "header_base": "//foundation/aafwk/standard/interfaces/innerkits/want/include/", + "header_base": "//foundation/aafwk/standard/interfaces/innerkits/wantagent/include/", "header_files": [ - "ohos/aafwk/content/want.h", - "ohos/aafwk/content/skills.h", - "ohos/aafwk/content/want_params.h", - "ohos/aafwk/content/match_type.h", - "ohos/aafwk/content/operation.h", - "ohos/aafwk/content/patterns_matcher.h", - "ohos/aafwk/content/pac_map.h" + "cancel_listener.h", + "completed_callback.h", + "completed_dispatcher.h", + "pending_want.h", + "trigger_info.h", + "want_agent_constant.h", + "want_agent_helper.h", + "want_agent_info.h", + "want_agent_log_wrapper.h", + "want_agent.h" ] }, - "name": "//foundation/aafwk/standard/interfaces/innerkits/want:want" + "name": "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits" }, { "header": { @@ -197,6 +179,7 @@ "test": [ "//foundation/aafwk/standard/frameworks/kits/content/cpp/test:unittest", "//foundation/aafwk/standard/frameworks/kits/ability/native/test:unittest", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/dataShare/test:unittest", "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test:moduletest", "//foundation/aafwk/standard/frameworks/kits/test:moduletest", "//foundation/aafwk/standard/services/test:moduletest", @@ -205,8 +188,9 @@ "//foundation/aafwk/standard/common/test:moduletest", "//foundation/aafwk/standard/frameworks/kits/appkit/native/test:unittest", "//foundation/aafwk/standard/frameworks/kits/appkit/test:moduletest", + "//foundation/aafwk/standard/frameworks/kits/wantagent/test/:unittest", "//foundation/aafwk/standard/services/appmgr/test:unittest" ] } } -} \ No newline at end of file +} diff --git a/frameworks/kits/ability/ability_runtime/BUILD.gn b/frameworks/kits/ability/ability_runtime/BUILD.gn old mode 100644 new mode 100755 index 8926749f510e9fb05c1f2b57416768bf36efc28d..df3fc506d82ba6271f02811e83ef7c43570351f2 --- a/frameworks/kits/ability/ability_runtime/BUILD.gn +++ b/frameworks/kits/ability/ability_runtime/BUILD.gn @@ -22,6 +22,7 @@ config("ability_context_public_config") { "${SO_DIR}/include", "${APPKIT_DIR}/appkit/native/ability_runtime", "${APPKIT_DIR}/appkit/native/ability_runtime/context", + "//base/hiviewdfx/hichecker/interfaces/native/innerkits/include", ] cflags = [] @@ -46,6 +47,7 @@ ohos_shared_library("ability_context_native") { "${APPKIT_DIR}/appkit:app_context", "${INNERKITS_DIR}/ability_manager:ability_manager", "${INNERKITS_DIR}/want:want", + "//base/hiviewdfx/faultloggerd/interfaces/innerkits/dump_catcher:lib_dfx_dump_catcher", "//foundation/ace/napi:ace_napi", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", ] @@ -54,6 +56,7 @@ ohos_shared_library("ability_context_native") { "ability_runtime:app_manager", "ability_runtime:runtime", "bytrace_standard:bytrace_core", + "hichecker_native:libhichecker", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "utils_base:utils", diff --git a/frameworks/kits/ability/ability_runtime/include/ability_context.h b/frameworks/kits/ability/ability_runtime/include/ability_context.h index 1f4e4d8af369c54dc9fdadd3c5da34330015b86d..570dc6319c7fad29ea3ef792bcc4a891779d8830 100644 --- a/frameworks/kits/ability/ability_runtime/include/ability_context.h +++ b/frameworks/kits/ability/ability_runtime/include/ability_context.h @@ -32,6 +32,7 @@ namespace OHOS { namespace AbilityRuntime { using RuntimeTask = std::function; using PermissionRequestTask = std::function&, const std::vector&)>; +class LocalCallContainer; class AbilityContext : public Context { public: virtual ~AbilityContext() = default; @@ -165,6 +166,8 @@ public: virtual ErrCode TerminateSelf() = 0; + virtual ErrCode CloseAbility() = 0; + /** * @brief Requests certain permissions from the system. * This method is called for permission request. This is an asynchronous method. When it is executed, @@ -227,9 +230,14 @@ public: */ virtual ErrCode SetMissionLabel(const std::string &label) = 0; - virtual void SetConfiguration(const std::shared_ptr &config) = 0; + /** + * @brief Get LocalCallContainer. + * + * @return Returns the LocalCallContainer. + */ + virtual sptr GetLocalCallContainer() = 0; - virtual std::shared_ptr GetConfiguration() const = 0; + virtual void SetConfiguration(const std::shared_ptr &config) = 0; virtual void RegisterAbilityCallback(std::weak_ptr abilityCallback) = 0; 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 c240fa64c418957608b18ecc75e8526306404b0d..a648d32b426f41b13367c6466e5b6447cff7f4f1 100644 --- a/frameworks/kits/ability/ability_runtime/include/ability_context_impl.h +++ b/frameworks/kits/ability/ability_runtime/include/ability_context_impl.h @@ -69,6 +69,8 @@ public: ErrCode TerminateSelf() override; + ErrCode CloseAbility() override; + sptr GetToken() override; void RequestPermissionsFromUser(const std::vector &permissions, @@ -115,6 +117,16 @@ public: return contentStorage_; } + /** + * @brief Get LocalCallContainer. + * + * @return Returns the LocalCallContainer. + */ + sptr GetLocalCallContainer() override + { + return localCallContainer_; + } + void SetConfiguration(const std::shared_ptr &config) override; std::shared_ptr GetConfiguration() const override; diff --git a/frameworks/kits/ability/ability_runtime/include/connection_manager.h b/frameworks/kits/ability/ability_runtime/include/connection_manager.h index 21ea3c693a406e3ec03952f01a314c488947731b..878a48e51186dfb7c1d16a60fc0a9387ecc33bd9 100755 --- a/frameworks/kits/ability/ability_runtime/include/connection_manager.h +++ b/frameworks/kits/ability/ability_runtime/include/connection_manager.h @@ -122,6 +122,14 @@ public: * @return Returns whether the ability connection of receiver is disconnect. */ bool DisconnectReceiver(const AppExecFwk::ElementName &connectReceiver); + + /** + * @brief Report the ability connection leak event. + * + * @param pid The process id. + * @param tid The thread id. + */ + void ReportConnectionLeakEvent(const int pid, const int tid); private: ConnectionManager() = default; bool IsConnectCallerEqual(const sptr &connectCaller, const sptr &connectCallerOther); diff --git a/frameworks/kits/ability/ability_runtime/include/js_extension_context.h b/frameworks/kits/ability/ability_runtime/include/js_extension_context.h index 9a3e868cec84c880ca02015b77131ec25f8149bf..3681dfd5d589b655c894cd0bdb7dee78f78f8157 100644 --- a/frameworks/kits/ability/ability_runtime/include/js_extension_context.h +++ b/frameworks/kits/ability/ability_runtime/include/js_extension_context.h @@ -21,10 +21,23 @@ #include "extension_context.h" class NativeEngine; +class NativeReference; class NativeValue; namespace OHOS { namespace AbilityRuntime { +class JsExtensionContext final { +public: + JsExtensionContext(const std::shared_ptr& context) : context_(context) {} + ~JsExtensionContext() = default; + + static void ConfigurationUpdated(NativeEngine* engine, std::shared_ptr &jsContext, + const std::shared_ptr &config); + +private: + std::weak_ptr context_; +}; + NativeValue* CreateJsExtensionContext(NativeEngine& engine, std::shared_ptr context); } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/kits/ability/ability_runtime/include/local_call_container.h b/frameworks/kits/ability/ability_runtime/include/local_call_container.h index 02659ff295302c712ba07fc4dfcf80847ae09420..ecc2fbe4e44995d38e8fa119063fce4efd788a9f 100644 --- a/frameworks/kits/ability/ability_runtime/include/local_call_container.h +++ b/frameworks/kits/ability/ability_runtime/include/local_call_container.h @@ -45,6 +45,7 @@ public: private: bool GetCallLocalreocrd( const AppExecFwk::ElementName &elementName, std::shared_ptr &localCallRecord); + void OnCallStubDied(const wptr &remote); private: std::map> callProxyRecords_; diff --git a/frameworks/kits/ability/ability_runtime/include/local_call_record.h b/frameworks/kits/ability/ability_runtime/include/local_call_record.h index 4fb8ae25b232867c3d264ea50c4aad35055ef91e..639a31d435d39d1aa600b9b54842e18c7eabcd39 100644 --- a/frameworks/kits/ability/ability_runtime/include/local_call_record.h +++ b/frameworks/kits/ability/ability_runtime/include/local_call_record.h @@ -32,6 +32,7 @@ public: virtual ~LocalCallRecord(); void SetRemoteObject(const sptr &call); + void SetRemoteObject(const sptr &call, sptr callRecipient); void AddCaller(const std::shared_ptr &callback); bool RemoveCaller(const std::shared_ptr &callback); void OnCallStubDied(const wptr &remote); @@ -39,6 +40,9 @@ public: void InvokeCallBack() const; AppExecFwk::ElementName GetElementName() const; bool IsExistCallBack() const; + int GetRecordId(); + std::vector> GetCallers(); + bool IsSameObject(const sptr &remote); private: static int64_t callRecordId; diff --git a/frameworks/kits/ability/ability_runtime/src/ability_connection.cpp b/frameworks/kits/ability/ability_runtime/src/ability_connection.cpp index a42fa5133f072267f4e678cde98a8df9d6fa85d6..d9ca5ee0f40495b9e69e83d8ce5fdb7b75ea5748 100755 --- a/frameworks/kits/ability/ability_runtime/src/ability_connection.cpp +++ b/frameworks/kits/ability/ability_runtime/src/ability_connection.cpp @@ -14,6 +14,9 @@ */ #include "ability_connection.h" + +#include + #include "connection_manager.h" #include "hilog_wrapper.h" @@ -49,6 +52,7 @@ void AbilityConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &e if (resultCode == DIED) { bool ret = ConnectionManager::GetInstance().DisconnectReceiver(element); if (ret) { + ConnectionManager::GetInstance().ReportConnectionLeakEvent(getpid(), gettid()); HILOG_INFO("The service connection is not disconnected."); } abilityConnectCallback_->OnAbilityDisconnectDone(element, DIED + 1); 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 8dbbd60696f33567f43b67a125fcd9953daf6abc..f66d7cdb33ca366e41ec92ed0d2fe6edb4398c54 100644 --- a/frameworks/kits/ability/ability_runtime/src/ability_context_impl.cpp +++ b/frameworks/kits/ability/ability_runtime/src/ability_context_impl.cpp @@ -164,8 +164,13 @@ ErrCode AbilityContextImpl::TerminateAbilityWithResult(const AAFwk::Want &want, void AbilityContextImpl::OnAbilityResult(int requestCode, int resultCode, const AAFwk::Want &resultData) { HILOG_DEBUG("%{public}s. Start calling OnAbilityResult.", __func__); - resultCallbacks_[requestCode](resultCode, resultData); - resultCallbacks_.erase(requestCode); + auto callback = resultCallbacks_.find(requestCode); + if (callback != resultCallbacks_.end()) { + if (callback->second) { + callback->second(resultCode, resultData); + } + resultCallbacks_.erase(requestCode); + } HILOG_INFO("%{public}s. End calling OnAbilityResult.", __func__); } @@ -278,6 +283,17 @@ ErrCode AbilityContextImpl::TerminateSelf() return err; } +ErrCode AbilityContextImpl::CloseAbility() +{ + HILOG_DEBUG("%{public}s begin.", __func__); + AAFwk::Want resultWant; + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->CloseAbility(token_, -1, &resultWant); + if (err != ERR_OK) { + HILOG_ERROR("CloseAbility failed: %{public}d", err); + } + return err; +} + sptr AbilityContextImpl::GetToken() { return token_; diff --git a/frameworks/kits/ability/ability_runtime/src/connection_manager.cpp b/frameworks/kits/ability/ability_runtime/src/connection_manager.cpp index 6c35e04942128e71c41a8e54d53119796253c70d..288de043ecb46895157380550013023202db0d5b 100755 --- a/frameworks/kits/ability/ability_runtime/src/connection_manager.cpp +++ b/frameworks/kits/ability/ability_runtime/src/connection_manager.cpp @@ -17,10 +17,13 @@ #include "ability_connection.h" #include "ability_context.h" #include "ability_manager_client.h" +#include "dfx_dump_catcher.h" +#include "hichecker.h" #include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { +using namespace OHOS::HiviewDFX; ConnectionManager& ConnectionManager::GetInstance() { static ConnectionManager connectionManager; @@ -238,6 +241,26 @@ bool ConnectionManager::DisconnectReceiver(const AppExecFwk::ElementName &connec return isDisconnect; } +void ConnectionManager::ReportConnectionLeakEvent(const int pid, const int tid) +{ + HILOG_DEBUG("%{public}s begin, pid:%{public}d, tid:%{public}d.", __func__, pid, tid); + if (HiChecker::Contains(Rule::RULE_CHECK_ABILITY_CONNECTION_LEAK)) { + DfxDumpCatcher dumplog; + std::string stackTrace; + bool ret = dumplog.DumpCatch(pid, tid, stackTrace); + if (ret) { + std::string cautionMsg = "TriggerRule:RULE_CHECK_ABILITY_CONNECTION_LEAK-pid=" + + std::to_string(pid) + "-tid=" + std::to_string(tid) + ", has leaked connection" + + ", Are you missing a call to DisconnectAbility()"; + HILOG_DEBUG("%{public}s cautionMsg:%{public}s.", __func__, cautionMsg.c_str()); + Caution caution(Rule::RULE_CHECK_ABILITY_CONNECTION_LEAK, cautionMsg, stackTrace); + HiChecker::NotifyAbilityConnectionLeak(caution); + } else { + HILOG_ERROR("%{public}s dumpCatch stackTrace failed.", __func__); + } + } +} + bool ConnectionManager::IsConnectCallerEqual(const sptr &connectCaller, const sptr &connectCallerOther) { diff --git a/frameworks/kits/ability/ability_runtime/src/js_extension_context.cpp b/frameworks/kits/ability/ability_runtime/src/js_extension_context.cpp index a9cdf1dd4a633f6f1fd113d532ae80d705195797..8441812852d01299a31d8b95aea5e21c00a5b6a7 100644 --- a/frameworks/kits/ability/ability_runtime/src/js_extension_context.cpp +++ b/frameworks/kits/ability/ability_runtime/src/js_extension_context.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,15 +19,50 @@ #include "hilog_wrapper.h" #include "js_context_utils.h" +#include "js_data_struct_converter.h" #include "js_runtime.h" #include "js_runtime_utils.h" namespace OHOS { namespace AbilityRuntime { +void JsExtensionContext::ConfigurationUpdated(NativeEngine* engine, std::shared_ptr &jsContext, + const std::shared_ptr &config) +{ + HILOG_INFO("%{public}s called.", __func__); + if ((!jsContext) || (!config)) { + HILOG_INFO("jsContext or config is nullptr."); + return; + } + + NativeValue* value = jsContext->Get(); + NativeObject* object = ConvertNativeValueTo(value); + if (!object) { + HILOG_INFO("object is nullptr."); + return; + } + + NativeValue* method = object->GetProperty("onUpdateConfiguration"); + if (!method) { + HILOG_ERROR("Failed to get onUpdateConfiguration from object"); + return; + } + + HILOG_INFO("JsExtensionContext call onUpdateConfiguration."); + NativeValue* argv[] = {CreateJsConfiguration(*engine, *config)}; + engine->CallFunction(value, method, argv, 1); +} + NativeValue* CreateJsExtensionContext(NativeEngine& engine, std::shared_ptr context) { HILOG_INFO("CreateJsExtensionContext begin"); NativeValue* objValue = CreateJsBaseContext(engine, context); + NativeObject* object = ConvertNativeValueTo(objValue); + + auto configuration = context->GetConfiguration(); + if (configuration) { + object->SetProperty("config", CreateJsConfiguration(engine, *configuration)); + } + return objValue; } } // namespace AbilityRuntime 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 13ed5205b1c666bd6775fc2628088cd028216297..55edc32bedaa6aa9e82ecedd917e2699062a866a 100644 --- a/frameworks/kits/ability/ability_runtime/src/local_call_container.cpp +++ b/frameworks/kits/ability/ability_runtime/src/local_call_container.cpp @@ -119,6 +119,31 @@ int LocalCallContainer::Release(const std::shared_ptr& callback) void LocalCallContainer::DumpCalls(std::vector &info) const { HILOG_DEBUG("LocalCallContainer::DumpCalls called."); + info.emplace_back(" caller connections:"); + for (auto iter = callProxyRecords_.begin(); iter != callProxyRecords_.end(); iter++) { + std::string tempstr = " LocalCallRecord"; + tempstr += " ID #" + std::to_string (iter->second->GetRecordId()) + "\n"; + tempstr += " callee"; + tempstr += " uri[" + iter->first + "]" + "\n"; + tempstr += " callers #" + std::to_string (iter->second->GetCallers().size()); + bool flag = true; + for (auto &callBack:iter->second->GetCallers()) { + if (callBack && !callBack->IsCallBack()) { + HILOG_INFO("%{public}s call back is not called.", __func__); + flag = false; + break; + } + } + if (flag) { + HILOG_INFO("%{public}s state is REQUESTEND.", __func__); + tempstr += " state #REQUESTEND"; + } else { + HILOG_INFO("%{public}s state is REQUESTING.", __func__); + tempstr += " state #REQUESTING"; + } + info.emplace_back(tempstr); + } + return; } void LocalCallContainer::OnAbilityConnectDone( @@ -130,7 +155,9 @@ void LocalCallContainer::OnAbilityConnectDone( } std::shared_ptr localCallRecord; if (GetCallLocalreocrd(element, localCallRecord)) { - localCallRecord->SetRemoteObject(remoteObject); + auto callRecipient = new (std::nothrow) CallRecipient( + std::bind(&LocalCallContainer::OnCallStubDied, this, std::placeholders::_1)); + localCallRecord->SetRemoteObject(remoteObject, callRecipient); } if (localCallRecord) { @@ -138,7 +165,6 @@ void LocalCallContainer::OnAbilityConnectDone( } HILOG_DEBUG("LocalCallContainer::OnAbilityConnectDone end."); - return; } @@ -157,5 +183,23 @@ bool LocalCallContainer::GetCallLocalreocrd( return false; } + +void LocalCallContainer::OnCallStubDied(const wptr &remote) +{ + auto diedRemote = remote.promote(); + auto isExist = [&diedRemote](auto &record) { + return record.second->IsSameObject(diedRemote); + }; + + auto iter = std::find_if(callProxyRecords_.begin(), callProxyRecords_.end(), isExist); + if (iter == callProxyRecords_.end()) { + HILOG_ERROR("StubDied object not found from localcallrecord."); + return; + } + + iter->second->OnCallStubDied(remote); + callProxyRecords_.erase(iter); + HILOG_DEBUG("LocalCallContainer::OnCallStubDied end."); +} } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/ability_runtime/src/local_call_record.cpp b/frameworks/kits/ability/ability_runtime/src/local_call_record.cpp index d2c30b86491f756d8cbabf5632cea57ff93b373b..4626f8400c8e54686db3e4b34938c796589ab3b0 100644 --- a/frameworks/kits/ability/ability_runtime/src/local_call_record.cpp +++ b/frameworks/kits/ability/ability_runtime/src/local_call_record.cpp @@ -50,6 +50,21 @@ void LocalCallRecord::SetRemoteObject(const sptr &call) HILOG_DEBUG("SetRemoteObject complete."); } +void LocalCallRecord::SetRemoteObject(const sptr &call, + sptr callRecipient) +{ + if (!call) { + HILOG_ERROR("remote object is nullptr"); + return; + } + + remoteObject_ = call; + callRecipient_ = callRecipient; + + remoteObject_->AddDeathRecipient(callRecipient_); + HILOG_DEBUG("SetRemoteObject2 complete."); +} + void LocalCallRecord::AddCaller(const std::shared_ptr &callback) { callers_.emplace_back(callback); @@ -113,5 +128,28 @@ bool LocalCallRecord::IsExistCallBack() const { return (callers_.size() > 0); } + +int LocalCallRecord::GetRecordId() +{ + return recordId_; +} + +std::vector> LocalCallRecord::GetCallers() +{ + return callers_; +} + +bool LocalCallRecord::IsSameObject(const sptr &remote) +{ + if (remote == nullptr) { + HILOG_ERROR("input remote object is nullptr"); + return false; + } + + bool retval = remoteObject_ == remote; + HILOG_DEBUG("LocalCallRecord::%{public}s the input object same as local object is %{public}s.", + __func__, retval ? "true" : "false"); + return retval; +} } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.h b/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.h index fb6a3059f83231995beaae402548ef8beaa4540a..a028c817425e14237658366f339a8216ebdb1aca 100644 --- a/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.h +++ b/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.h @@ -56,6 +56,11 @@ public: int TerminateAbility( const sptr &token, int resultCode = -1, const Want *resultWant = nullptr) override; + virtual int CloseAbility(const sptr &token, int resultCode = DEFAULT_INVAL_VALUE, + const Want *resultWant = nullptr) override + { + return 0; + } int MinimizeAbility(const sptr &token, bool fromUser) override { return 0; @@ -117,7 +122,7 @@ public: MOCK_METHOD1(GetPendinTerminateAbilityTestgRequestWant, void(int id)); MOCK_METHOD1(GetSystemMemoryAttr, void(AppExecFwk::SystemMemoryAttr &memoryInfo)); MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); - MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result)); + MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, int32_t result)); MOCK_METHOD1(LockMissionForCleanup, int(int32_t missionId)); MOCK_METHOD1(UnlockMissionForCleanup, int(int32_t missionId)); @@ -134,6 +139,7 @@ public: MOCK_METHOD1(CleanMission, int(int32_t missionId)); MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); + MOCK_METHOD2(MoveMissionToFront, int(int32_t missionId, const StartOptions &startOptions)); MOCK_METHOD2(GetWantSenderInfo, int(const sptr &target, std::shared_ptr &info)); @@ -272,9 +278,9 @@ public: return true; } - bool SendANRProcessID(int pid) override + int SendANRProcessID(int pid) override { - return true; + return 0; } int RegisterSnapshotHandler(const sptr& handler) override diff --git a/frameworks/kits/ability/native/BUILD.gn b/frameworks/kits/ability/native/BUILD.gn index 6053ad90c7787b0e4c61373cbe500c2fd4b142c3..db347c3f52816cbfb2845df20117151e1e7a4e28 100644 --- a/frameworks/kits/ability/native/BUILD.gn +++ b/frameworks/kits/ability/native/BUILD.gn @@ -76,6 +76,7 @@ config("ability_public_config") { "//third_party/libuv/include", "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/context", "//foundation/aafwk/standard/interfaces/innerkits/base/include/ohos/aafwk/base", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", "//foundation/aafwk/standard/frameworks/kits/ability/native/include/continuation/remote_register_service", "//foundation/aafwk/standard/frameworks/kits/ability/native/include/continuation/distributed", "//foundation/aafwk/standard/frameworks/kits/ability/native/include/distributed_ability_runtime", @@ -109,7 +110,7 @@ ohos_shared_library("static_subscriber_ipc") { ] external_deps = [ - "ability_runtime:want", + "ability_base:want", "ces_standard:cesfwk_innerkits", "ipc:ipc_core", ] @@ -124,6 +125,7 @@ ohos_shared_library("abilitykit_native") { "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/common/include", "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_dataability/include", "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_resultset/include", + "//foundation/distributeddatamgr/objectstore/interfaces/innerkits/", "//base/global/i18n_standard/frameworks/intl/include", ] @@ -167,6 +169,7 @@ 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/form_runtime/js_form_extension_util.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", @@ -232,6 +235,7 @@ ohos_shared_library("abilitykit_native") { public_configs = [ ":ability_public_config", "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_public_config", + "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits_public_config", ] deps = [ @@ -242,6 +246,8 @@ ohos_shared_library("abilitykit_native") { "//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/frameworks/kits/appkit:appkit_delegator", + "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/interfaces/innerkits/dataobs_manager:dataobs_manager", @@ -252,16 +258,20 @@ ohos_shared_library("abilitykit_native") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/multimodalinput/input/frameworks/proxy:libmmi-common", + "//foundation/resourceschedule/background_task_mgr/interfaces/innerkits:bgtaskmgr_innerkits", "//third_party/icu/icu4c:shared_icuuc", ] external_deps = [ + "ability_base:configuration", "ability_runtime:ability_context_native", "ability_runtime:app_manager", "ability_runtime:napi_base_context", "ability_runtime:runtime", + "access_token:libaccesstoken_sdk", "bytrace_standard:bytrace_core", "ces_standard:cesfwk_innerkits", + "distributeddataobject:distributeddataobject_impl", "form_runtime:fmskit_native", "form_runtime:form_manager", "ipc:ipc_core", @@ -280,6 +290,8 @@ ohos_shared_library("abilitykit_native") { "//foundation/ace/napi:ace_napi", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/graphic/standard:libwmclient", + "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", + "//foundation/windowmanager/dm:libdm", "//foundation/windowmanager/interfaces/kits/napi/window_runtime:windowstage_kit", "//foundation/windowmanager/wm:libwm", ] diff --git a/frameworks/kits/ability/native/include/ability.h b/frameworks/kits/ability/native/include/ability.h index 55b6f88512d06c6b7b8b07a5a346a41e34ac2a8b..6557de4057181367440eb59d6208fd2c53c91e4f 100755 --- a/frameworks/kits/ability/native/include/ability.h +++ b/frameworks/kits/ability/native/include/ability.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -30,6 +30,7 @@ #include "context.h" #include "continuation_handler.h" #include "continuation_state.h" +#include "display_manager.h" #include "dummy_ability_package.h" #include "dummy_component_container.h" #include "dummy_notification_request.h" @@ -44,6 +45,7 @@ #include "iremote_object.h" #include "pac_map.h" #include "want.h" +#include "want_agent.h" #include "window_option.h" #include "window_scene.h" #include "wm_common.h" @@ -78,7 +80,8 @@ class Ability : public IAbilityEvent, public FormCallbackInterface, public IAbilityContinuation, public IAbilityCallback, - public std::enable_shared_from_this { + public std::enable_shared_from_this, + public OHOS::Rosen::DisplayManager::IDisplayListener { public: friend class PageAbilityImpl; friend class NewAbilityImpl; @@ -493,6 +496,12 @@ public: */ void OnConfigurationUpdatedNotify(const Configuration &configuration); + /** + * @brief Update context.config when configuration is updated. + * + */ + virtual void UpdateContextConfiguration() {}; + /** * @brief Called when the system configuration is updated. * @@ -671,6 +680,14 @@ public: */ virtual void Dump(const std::string &extra); + /** + * @brief dump ability info + * + * @param params dump params that indicate different dump targets + * @param info dump ability info + */ + virtual void Dump(const std::vector ¶ms, std::vector &info); + /** * @brief Keeps this Service ability in the background and displays a notification bar. * To use this method, you need to request the ohos.permission.KEEP_BACKGROUND_RUNNING permission from the system. @@ -1006,6 +1023,21 @@ public: */ bool DeleteForm(const int64_t formId); + /** + * @brief Keep this Service ability in the background and displays a notification bar. + * + * @param wantAgent Indicates which ability to start when user click the notification bar. + * @return the method result code, 0 means succeed + */ + virtual int StartBackgroundRunning(const AbilityRuntime::WantAgent::WantAgent &wantAgent) final; + + /** + * @brief Cancel background running of this ability to free up system memory. + * + * @return the method result code, 0 means succeed + */ + virtual int StopBackgroundRunning() final; + /** * @brief The form callback. */ @@ -1425,6 +1457,13 @@ protected: */ virtual void DoOnForeground(const Want& want); + /** + * @brief requeset focus for current window. + * + * You can override this function to implement your own processing logic + */ + virtual void RequsetFocus(const Want &want); + /** * @brief Acquire the window option. * @return window option. @@ -1437,6 +1476,13 @@ protected: */ bool IsRestoredInContinuation() const; + /** + * @brief wait for distributed object to complete sync + * + * @param want the want param. + */ + void WaitingDistributedObjectSyncComplete(const Want& want); + /** * @brief Notify continuation * @@ -1445,6 +1491,15 @@ protected: */ void NotityContinuationResult(const Want& want, bool success); + /** + * @brief override Rosen::DisplayManager::IDisplayListener virtual callback function + * + * @param displayId displayId + */ + void OnCreate(Rosen::DisplayId displayId) override; + void OnDestroy(Rosen::DisplayId displayId) override; + void OnChange(Rosen::DisplayId displayId, Rosen::DisplayChangeEvent changeEvent) override; + protected: std::shared_ptr abilityContext_ = nullptr; std::shared_ptr scene_ = nullptr; diff --git a/frameworks/kits/ability/native/include/ability_context.h b/frameworks/kits/ability/native/include/ability_context.h index 02466e25abe71992a4ed1bab08380d5794069ea7..7c4ffcf967cd15afa0640ee1f7a5eb0d09c0c5d3 100644 --- a/frameworks/kits/ability/native/include/ability_context.h +++ b/frameworks/kits/ability/native/include/ability_context.h @@ -368,15 +368,15 @@ public: * @brief Creates a Context object for an application with the given bundle name. * * @param bundleName Indicates the bundle name of the application. - * * @param flag Indicates the flag for creating a Context object. It can be 0, any of * the following values, or any combination of the following values: CONTEXT_IGNORE_SECURITY, * CONTEXT_INCLUDE_CODE, and CONTEXT_RESTRICTED. The value 0 indicates that there is no restriction * on creating contexts for applications. + * @param accountId Indicates the account Id. * * @return Returns a Context object created for the specified application. */ - std::shared_ptr CreateBundleContext(std::string bundleName, int flag); + std::shared_ptr CreateBundleContext(std::string bundleName, int flag, int accountId = DEFAULT_ACCOUNT_ID); /** * @brief Obtains a resource manager. diff --git a/frameworks/kits/ability/native/include/ability_impl.h b/frameworks/kits/ability/native/include/ability_impl.h index cf2afeb8a7be214080708c16877ed46f0aef3014..00b69e0cc1f48f5caf457db558d1a5f97ce01aa9 100755 --- a/frameworks/kits/ability/native/include/ability_impl.h +++ b/frameworks/kits/ability/native/include/ability_impl.h @@ -51,14 +51,14 @@ public: * * @param useNewMission new mission flag. */ - static void SetUseNewMission(bool useNewMission); + static void SetUseNewMission(bool useNewMission); /** * @brief Get if use new mission. * * @return return true if use new mission. */ - static bool IsUseNewMission(); + static bool IsUseNewMission(); /** * @brief Connect the ability. and Calling information back to Ability. @@ -222,7 +222,8 @@ public: * * @return Returns the number of data records updated. */ - virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates); + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, + const NativeRdb::DataAbilityPredicates &predicates); /** * @brief Deletes one or more data records from the database. @@ -331,7 +332,8 @@ public: */ std::shared_ptr CreatePostEventTimeouter(std::string taskstr); - virtual std::vector> ExecuteBatch(const std::vector> &operations); + virtual std::vector> ExecuteBatch( + const std::vector> &operations); /** * @brief continue ability to target device. @@ -349,7 +351,7 @@ public: * * @return */ - virtual void NotifyContinuationResult(const int32_t result); + virtual void NotifyContinuationResult(int32_t result); bool IsStageBasedModel() const; diff --git a/frameworks/kits/ability/native/include/ability_local_record.h b/frameworks/kits/ability/native/include/ability_local_record.h index aedd0e9222ff6ee0384eb50fdd2fe869d9edb4ee..42acc4f4cbeb697df544693546d582c6a013a655 100644 --- a/frameworks/kits/ability/native/include/ability_local_record.h +++ b/frameworks/kits/ability/native/include/ability_local_record.h @@ -23,6 +23,8 @@ #include "ability_info.h" #include "application_info.h" #include "refbase.h" +#include "want.h" + namespace OHOS { namespace AppExecFwk { class AbilityThread; @@ -123,6 +125,10 @@ public: * @return None. */ void SetCompatibleVersion(int compatibleVersion); + + void SetWant(const std::shared_ptr &want); + + const std::shared_ptr &GetWant(); private: std::shared_ptr abilityInfo_ = nullptr; sptr token_; @@ -131,6 +137,7 @@ private: std::shared_ptr abilityImpl_ = nullptr; // store abilityImpl sptr abilityThread_; int compatibleVersion_ = 0; + std::shared_ptr want_ = nullptr; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/include/ability_runtime/js_ability.h b/frameworks/kits/ability/native/include/ability_runtime/js_ability.h index 59db15887636c01c21f82e3bc06e5fdc1d0fc712..989495a67579ef4c723e0fcb4f6e5ca04309ef37 100755 --- a/frameworks/kits/ability/native/include/ability_runtime/js_ability.h +++ b/frameworks/kits/ability/native/include/ability_runtime/js_ability.h @@ -17,6 +17,7 @@ #define ABILITY_RUNTIME_JS_ABILITY_H #include "ability.h" +#include "ability_delegator_infos.h" class NativeReference; class NativeValue; @@ -54,6 +55,7 @@ public: void OnBackground() override; bool OnContinue(WantParams &wantParams) override; void OnConfigurationUpdated(const Configuration &configuration) override; + void UpdateContextConfiguration() override; void OnNewWant(const Want &want) override; void OnAbilityResult(int requestCode, int resultCode, const Want &resultData) override; @@ -64,11 +66,13 @@ public: protected: void DoOnForeground(const Want &want) override; + void RequsetFocus(const Want &want) override; private: void CallObjectMethod(const char *name, NativeValue *const *argv = nullptr, size_t argc = 0); std::unique_ptr CreateAppWindowStage(); void GetPageStackFromWant(const Want &want, std::string &pageStack); + std::shared_ptr CreateADelegatorAbilityProperty(); JsRuntime &jsRuntime_; std::shared_ptr shellContextRef_; diff --git a/frameworks/kits/ability/native/include/ability_thread.h b/frameworks/kits/ability/native/include/ability_thread.h index 2b870321f205bc52bf9e4ba1571d8da954edc34a..5c35b3392cc9ae348ee10293ae4c2845769b1aff 100644 --- a/frameworks/kits/ability/native/include/ability_thread.h +++ b/frameworks/kits/ability/native/include/ability_thread.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -230,7 +230,8 @@ public: * * @return Returns the number of data records updated. */ - int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates); + int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, + const NativeRdb::DataAbilityPredicates &predicates); /** * @brief Deletes one or more data records from the database. @@ -313,7 +314,7 @@ public: * * @param result: Continuation result */ - void NotifyContinuationResult(const int32_t result); + void NotifyContinuationResult(int32_t result); /** * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used @@ -394,16 +395,16 @@ public: * @return Returns true on success, others on failure. */ bool CheckObsPermission(); - + /** * @brief Dump ability runner info. * * @param runnerInfo ability runner info. */ - void DumpAbilityInfo(std::vector &info); + void DumpAbilityInfo(const std::vector ¶ms, std::vector &info); sptr CallRequest(); - + std::vector> ExecuteBatch( const std::vector> &operations); private: @@ -505,6 +506,13 @@ private: */ void HandleUpdateConfiguration(const Configuration &config); + /** + * @brief Handle the scheduling update configuration of extension. + * + * @param config Configuration + */ + void HandleExtensionUpdateConfiguration(const Configuration &config); + std::shared_ptr BuildAbilityContext( const std::shared_ptr &abilityInfo, const std::shared_ptr &application, const sptr &token, const std::shared_ptr &stageContext); diff --git a/frameworks/kits/ability/native/include/datashare_helper.h b/frameworks/kits/ability/native/include/datashare_helper.h index 39cb1935acea396869e28e72de8bf2f7f1732525..29f15ba6204ae3db567c35b5a7cca94538170eec 100644 --- a/frameworks/kits/ability/native/include/datashare_helper.h +++ b/frameworks/kits/ability/native/include/datashare_helper.h @@ -264,7 +264,6 @@ private: 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_; diff --git a/frameworks/kits/ability/native/include/distributed_ability_runtime/distributed_client.h b/frameworks/kits/ability/native/include/distributed_ability_runtime/distributed_client.h index f0223d26a40ba8da62e71098202f19cd62078dfe..f931e17ee99613f02c29201f15f589ac75c14b86 100644 --- a/frameworks/kits/ability/native/include/distributed_ability_runtime/distributed_client.h +++ b/frameworks/kits/ability/native/include/distributed_ability_runtime/distributed_client.h @@ -31,14 +31,15 @@ class DistributedClient { public: DistributedClient() = default; virtual ~DistributedClient() = default; - int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, int32_t callerUid, int32_t requestCode); + int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, int32_t callerUid, int32_t requestCode, + uint32_t accessToken); int32_t ContinueMission(const std::string& srcDeviceId, const std::string& dstDeviceId, int32_t missionId, const sptr& callback, const OHOS::AAFwk::WantParams& wantParams); int32_t StartContinuation(const OHOS::AAFwk::Want& want, int32_t missionId, int32_t callerUid, - int32_t status); + int32_t status, uint32_t accessToken); int32_t NotifyCompleteContinuation(const std::u16string &devId, int32_t sessionId, bool isSuccess); - int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want, - const sptr& connect, int32_t callerUid, int32_t callerPid); + int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want, const sptr& connect, + int32_t callerUid, int32_t callerPid, uint32_t accessToken); int32_t DisconnectRemoteAbility(const sptr& connect); int32_t StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag); int32_t StopSyncRemoteMissions(const std::string& devId); @@ -48,6 +49,9 @@ public: std::vector& missionInfos); int32_t GetRemoteMissionSnapshotInfo(const std::string& deviceId, int32_t missionId, std::unique_ptr& missionSnapshot); + int32_t StartRemoteAbilityByCall(const OHOS::AAFwk::Want& want, const sptr& connect, + int32_t callerUid, int32_t callerPid, uint32_t tokenCaller); + int32_t ReleaseRemoteAbility(const sptr& connect, const AppExecFwk::ElementName &element); enum { START_REMOTE_ABILITY = 1, CONNECT_REMOTE_ABILITY = 6, @@ -61,6 +65,8 @@ public: START_SYNC_MISSIONS = 92, STOP_SYNC_MISSIONS = 98, GET_REMOTE_MISSION_SNAPSHOT_INFO = 99, + START_REMOTE_ABILITY_BY_CALL = 150, + RELEASE_REMOTE_ABILITY = 151, }; private: sptr GetDmsProxy(); diff --git a/frameworks/kits/ability/native/include/extension.h b/frameworks/kits/ability/native/include/extension.h index fd6a17f88ecacbbb1841e27db184c8e239a60bdd..c49d6b7187692ac6ec37604b8321dd4b5a4a2ef5 100644 --- a/frameworks/kits/ability/native/include/extension.h +++ b/frameworks/kits/ability/native/include/extension.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -27,6 +27,7 @@ struct AbilityInfo; class OHOSApplication; class AbilityHandler; class AbilityLocalRecord; +class Configuration; } namespace AbilityRuntime { using Want = OHOS::AAFwk::Want; @@ -115,6 +116,13 @@ public: */ virtual void OnStop(); + /** + * @brief Called when the system configuration is updated. + * + * @param configuration Indicates the updated configuration information. + */ + virtual void OnConfigurationUpdated(const AppExecFwk::Configuration& configuration); + std::shared_ptr abilityInfo_ = nullptr; private: std::shared_ptr handler_ = nullptr; diff --git a/frameworks/kits/ability/native/include/extension_base.inl b/frameworks/kits/ability/native/include/extension_base.inl index 02d1f12e186e33558f435bce72e9738e153c168e..6102eaae157834f4bd7c32b4655ab2a9087f0595 100644 --- a/frameworks/kits/ability/native/include/extension_base.inl +++ b/frameworks/kits/ability/native/include/extension_base.inl @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -49,6 +49,7 @@ std::shared_ptr ExtensionBase::CreateAndInitContext(const std::shared_ptr< auto abilityInfo = record->GetAbilityInfo(); context->SetAbilityInfo(abilityInfo); context->InitHapModuleInfo(abilityInfo); + context->SetConfiguration(appContext->GetConfiguration()); return context; } diff --git a/frameworks/kits/ability/native/include/extension_impl.h b/frameworks/kits/ability/native/include/extension_impl.h index 1cbcca05e1a6fdd079f1443acd89a3327a4c9280..773cd918e15867ab7f4916606bdb6e9a5630a563 100644 --- a/frameworks/kits/ability/native/include/extension_impl.h +++ b/frameworks/kits/ability/native/include/extension_impl.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,6 +17,7 @@ #define FOUNDATION_ABILITYRUNTIME_OHOS_EXTENSION_IMPL_H #include "extension.h" +#include "lifecycle_state_info.h" namespace OHOS { class IRemoteObject; @@ -61,6 +62,13 @@ public: */ virtual void HandleExtensionTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState); + /** + * @brief scheduling update configuration of extension. + * + * @param config Configuration + */ + void ScheduleUpdateConfiguration(const AppExecFwk::Configuration &config); + /** * @brief Connect the Extension. and Calling information back to Extension. * 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 179cda869d87b53f1669e4927d282c6528abf3e9..1bdcf41a9101220911e2a878e562377861ef35b2 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 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,9 +16,9 @@ #ifndef FOUNDATION_APPEXECFWK_OHOS_JS_FORM_EXTENSION_H #define FOUNDATION_APPEXECFWK_OHOS_JS_FORM_EXTENSION_H +#include "configuration.h" #include "form_extension.h" -class NativeEngine; class NativeReference; class NativeValue; @@ -54,16 +54,18 @@ public: void OnVisibilityChange(const std::map& formEventsMap) override; sptr OnConnect(const OHOS::AAFwk::Want& want) override; + + void OnConfigurationUpdated(const AppExecFwk::Configuration& configuration) 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_; sptr providerRemoteObject_ = nullptr; + std::shared_ptr shellContextRef_ = nullptr; }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/interfaces/kits/js/bundle/shortcutinfo1.d.ts b/frameworks/kits/ability/native/include/form_runtime/js_form_extension_util.h similarity index 56% rename from interfaces/kits/js/bundle/shortcutinfo1.d.ts rename to frameworks/kits/ability/native/include/form_runtime/js_form_extension_util.h index 1e6ce78bf9df84fa496e9faa5397d1b52ad1961e..bc897a1e240e734443621df12de3c32c945ff8f3 100644 --- a/interfaces/kits/js/bundle/shortcutinfo1.d.ts +++ b/frameworks/kits/ability/native/include/form_runtime/js_form_extension_util.h @@ -1,31 +1,28 @@ -/* - * 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. - */ -export interface ShortcutIntent{ - readonly targetBundle: string; - readonly targetClass: string; -} - -export interface ShortcutInfo { - readonly id: string; - readonly bundleName: string; - readonly hostAbility: string; - readonly icon: string; - readonly label: string; - readonly disableMessage: string; - readonly intents: Array; - readonly isStatic?: boolean - readonly isHomeShortcut?: boolean; - readonly isEnabled?: boolean; -} \ No newline at end of file +/* + * 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 OHOS_ABILITY_RUNTIME_JS_FORM_EXTENSION_UTILS_H +#define OHOS_ABILITY_RUNTIME_JS_FORM_EXTENSION_UTILS_H + +#include "native_engine/native_engine.h" + +#include + +namespace OHOS { +namespace AbilityRuntime { +bool UnwrapRawImageDataMap(NativeEngine& engine, NativeValue* argv, std::map& rawImageDataMap); +} // namespace AbilityRuntime +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_JS_FORM_EXTENSION_UTILS_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/iability_callback.h b/frameworks/kits/ability/native/include/iability_callback.h index a62753795d5072be4f603e408ca9f91fb6c4a1fc..7a4f8195fb735b16484c707afbdf86c200710baf 100644 --- a/frameworks/kits/ability/native/include/iability_callback.h +++ b/frameworks/kits/ability/native/include/iability_callback.h @@ -20,6 +20,9 @@ namespace OHOS { namespace AppExecFwk { class IAbilityCallback { public: + IAbilityCallback() = default; + virtual ~IAbilityCallback() = default; + /** * @brief Called back at ability context. */ diff --git a/frameworks/kits/ability/native/include/js_datashare_ext_ability.h b/frameworks/kits/ability/native/include/js_datashare_ext_ability.h index ce8d41ec9c1a0fba94cf55e0c41db53536ef3f4c..192faa091c745382ab626c8992c65136cdd2bc44 100644 --- a/frameworks/kits/ability/native/include/js_datashare_ext_ability.h +++ b/frameworks/kits/ability/native/include/js_datashare_ext_ability.h @@ -247,6 +247,7 @@ private: void GetSrcPath(std::string &srcPath); void LoadLibrary(); void UnloadLibrary(); + bool CheckCallingPermission(const std::string &permission); JsRuntime& jsRuntime_; std::unique_ptr jsObj_; diff --git a/frameworks/kits/ability/native/include/js_service_extension.h b/frameworks/kits/ability/native/include/js_service_extension.h index 036fe803236e59ca22f60abc7c92800f63609e73..d8967bafe15e92520ff2c962ef02e2544782064c 100644 --- a/frameworks/kits/ability/native/include/js_service_extension.h +++ b/frameworks/kits/ability/native/include/js_service_extension.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,6 +16,7 @@ #ifndef FOUNDATION_ABILITYRUNTIME_OHOS_JS_SERVICE_EXTENSION_H #define FOUNDATION_ABILITYRUNTIME_OHOS_JS_SERVICE_EXTENSION_H +#include "configuration.h" #include "service_extension.h" class NativeReference; @@ -104,6 +105,14 @@ public: * You can override this function to implement your own processing logic. */ virtual void OnStop() override; + + /** + * @brief Called when the system configuration is updated. + * + * @param configuration Indicates the updated configuration information. + */ + void OnConfigurationUpdated(const AppExecFwk::Configuration& configuration) override; + private: NativeValue* CallObjectMethod(const char* name, NativeValue* const* argv = nullptr, size_t argc = 0); @@ -111,6 +120,7 @@ private: JsRuntime& jsRuntime_; std::unique_ptr jsObj_; + std::shared_ptr shellContextRef_ = nullptr; }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/kits/ability/native/include/page_ability_impl.h b/frameworks/kits/ability/native/include/page_ability_impl.h index 2ddaee18949d03123139760940c3209273c52957..912bc784039278776f27e0eccf1d74eb562ccfad 100644 --- a/frameworks/kits/ability/native/include/page_ability_impl.h +++ b/frameworks/kits/ability/native/include/page_ability_impl.h @@ -67,7 +67,7 @@ public: * @return return true if the lifecycle transaction successfully, otherwise return false. * */ - bool AbilityTransactionNew(const Want &want, const AAFwk::LifeCycleStateInfo &targetState); + bool AbilityTransactionNew(const Want &want, const AAFwk::LifeCycleStateInfo &targetState); /** * @brief Execution the KeyDown callback of the ability diff --git a/frameworks/kits/ability/native/src/ability.cpp b/frameworks/kits/ability/native/src/ability.cpp index 78046a8c561b05256d5041200682682af6f555fb..96b450aa285740268c5ced4931186f00f4ce19ab 100755 --- a/frameworks/kits/ability/native/src/ability.cpp +++ b/frameworks/kits/ability/native/src/ability.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -24,17 +24,21 @@ #include "ability_runtime/js_ability.h" #include "abs_shared_result_set.h" #include "app_log_wrapper.h" +#include "background_task_mgr_helper.h" #include "bytrace.h" +#include "configuration_convertor.h" #include "connection_manager.h" #include "context_impl.h" #include "continuation_manager.h" #include "continuation_register_manager.h" #include "continuation_register_manager_proxy.h" +#include "continuous_task_param.h" #include "data_ability_operation.h" #include "data_ability_predicates.h" #include "data_ability_result.h" #include "data_uri_utils.h" #include "display_type.h" +#include "distributed_objectstore.h" #include "form_host_client.h" #include "form_mgr.h" #include "form_provider_client.h" @@ -78,6 +82,7 @@ static std::mutex formLock; constexpr int64_t SEC_TO_MILLISEC = 1000; constexpr int64_t MILLISEC_TO_NANOSEC = 1000000; +constexpr int32_t DISTRIBUTED_OBJECT_TIMEOUT = 10000; Ability* Ability::Create(const std::unique_ptr& runtime) { @@ -129,6 +134,11 @@ void Ability::Init(const std::shared_ptr &abilityInfo, const std::s continuationHandler_->SetAbilityInfo(abilityInfo_); } } + + // register displayid change callback + APP_LOGI("Ability::Init call RegisterDisplayListener"); + OHOS::sptr thisAbility(this); + Rosen::DisplayManager::GetInstance().RegisterDisplayListener(thisAbility); } lifecycle_ = std::make_shared(); abilityLifecycleExecutor_ = std::make_shared(); @@ -198,11 +208,11 @@ void Ability::OnStart(const Want &want) } if (abilityInfo_->bundleName == LAUNCHER_BUNDLE_NAME && abilityInfo_->name == LAUNCHER_ABILITY_NAME) { - winType = Rosen::WindowType::WINDOW_TYPE_WALLPAPER; + winType = Rosen::WindowType::WINDOW_TYPE_DESKTOP; } int defualtDisplayId = Rosen::WindowScene::DEFAULT_DISPLAY_ID; - int displayId = want.GetIntParam(StartOptions::STRING_DISPLAY_ID, defualtDisplayId); + int displayId = want.GetIntParam(Want::PARAM_RESV_DISPLAY_ID, defualtDisplayId); APP_LOGI("Ability::OnStart bundleName:%{public}s, abilityName:%{public}s, windowType:%{public}d, " "displayId:%{public}d", abilityInfo_->bundleName.c_str(), @@ -222,6 +232,34 @@ void Ability::OnStart(const Want &want) } APP_LOGI("%{public}s end abilityWindow_->OnPostAbilityStart.", __func__); } + + // Update resMgr, Configuration + APP_LOGI("%{public}s get display by displayId %{public}d.", __func__, displayId); + auto display = Rosen::DisplayManager::GetInstance().GetDisplayById(displayId); + if (display) { + float density = display->GetVirtualPixelRatio(); + int32_t width = display->GetWidth(); + int32_t height = display->GetHeight(); + auto configuration = application_->GetConfiguration(); + configuration->AddItem(displayId, ConfigurationInner::APPLICATION_DIRECTION, + GetDirectionStr(height, width)); + configuration->AddItem(displayId, ConfigurationInner::APPLICATION_DENSITYDPI, GetDensityStr(density)); + configuration->AddItem(ConfigurationInner::APPLICATION_DISPLAYID, std::to_string(displayId)); + UpdateContextConfiguration(); + + std::unique_ptr resConfig(Global::Resource::CreateResConfig()); + if (resConfig == nullptr) { + APP_LOGE("%{public}s error, resConfig is nullptr.", __func__); + return; + } + resConfig->SetScreenDensity(ConvertDensity(density)); + resConfig->SetDirection(ConvertDirection(height, width)); + auto resourceManager = GetResourceManager(); + if (resourceManager != nullptr) { + resourceManager->UpdateResConfig(*resConfig); + APP_LOGI("%{public}s Notify ResourceManager.", __func__); + } + } } SetWant(want); @@ -275,6 +313,7 @@ void Ability::Destroy() APP_LOGI("%{public}s begin.", __func__); // Release the scene. if (scene_ != nullptr) { + scene_->GoDestroy(); scene_ = nullptr; onSceneDestroyed(); } @@ -413,8 +452,43 @@ bool Ability::IsRestoredInContinuation() const return false; } +void Ability::WaitingDistributedObjectSyncComplete(const Want& want) +{ + int sessionId = want.GetIntParam(DMS_SESSION_ID, DEFAULT_DMS_SESSION_ID); + std::string originDeviceId = want.GetStringParam(DMS_ORIGIN_DEVICE_ID); + + APP_LOGI("continuation WaitingDistributedObjectSyncComplete begin"); + auto timeout = [self = shared_from_this(), sessionId, originDeviceId]() { + APP_LOGI("DistributedObject sync timeout"); + self->continuationManager_->NotifyCompleteContinuation( + originDeviceId, sessionId, false, nullptr); + }; + + // std::shared_ptr handler = handler_; + auto callback = [self = shared_from_this(), sessionId, originDeviceId]() { + APP_LOGI("DistributedObject sync complete"); + if (self->handler_ != nullptr) { + self->handler_->RemoveTask("Waiting_Sync_Timeout"); + } + self->continuationManager_->NotifyCompleteContinuation( + originDeviceId, sessionId, true, nullptr); + }; + + std::string &bundleName = abilityInfo_->bundleName; + APP_LOGI("continuation TriggerRestore begin"); + ObjectStore::DistributedObjectStore::GetInstance(bundleName)->TriggerRestore(callback); + APP_LOGI("continuation TriggerRestore end"); + + if (handler_ != nullptr) { + APP_LOGI("continuation set timeout begin"); + handler_->PostTask(timeout, "Waiting_Sync_Timeout", DISTRIBUTED_OBJECT_TIMEOUT); + APP_LOGI("continuation set timeout end"); + } +} + void Ability::NotityContinuationResult(const Want& want, bool success) { + APP_LOGI("NotityContinuationResult begin"); std::weak_ptr ReplicaHandler = continuationHandler_; reverseContinuationSchedulerReplica_ = sptr( new (std::nothrow) ReverseContinuationSchedulerReplica(handler_, ReplicaHandler)); @@ -867,30 +941,40 @@ void Ability::OnConfigurationUpdatedNotify(const Configuration &changeConfigurat APP_LOGI("%{public}s begin.", __func__); std::string language; + std::string colormode; if (setting_) { auto displayId = std::atoi(setting_->GetProperty(AbilityStartSetting::WINDOW_DISPLAY_ID_KEY).c_str()); language = changeConfiguration.GetItem(displayId, GlobalConfigurationKey::SYSTEM_LANGUAGE); - APP_LOGI("displayId :[%{public}d] | language :[%{public}s]", displayId, language.c_str()); + colormode = changeConfiguration.GetItem(displayId, GlobalConfigurationKey::SYSTEM_COLORMODE); + APP_LOGI("displayId: [%{public}d], language: [%{public}s], colormode: [%{public}s]", + displayId, language.c_str(), colormode.c_str()); } else { language = changeConfiguration.GetItem(GlobalConfigurationKey::SYSTEM_LANGUAGE); - APP_LOGI("language :[%{public}s]", language.c_str()); + colormode = changeConfiguration.GetItem(GlobalConfigurationKey::SYSTEM_COLORMODE); + APP_LOGI("language: [%{public}s], colormode: [%{public}s]", language.c_str(), colormode.c_str()); } // Notify ResourceManager std::unique_ptr resConfig(Global::Resource::CreateResConfig()); - if (resConfig != nullptr && !language.empty()) { - APP_LOGE("make resource mgr date"); - UErrorCode status = U_ZERO_ERROR; - icu::Locale locale = icu::Locale::forLanguageTag(language, status); - APP_LOGI("get Locale::forLanguageTag return[%{public}d].", static_cast(status)); - if (status == U_ZERO_ERROR) { - resConfig->SetLocaleInfo(locale); - auto resourceManager = GetResourceManager(); - if (resourceManager != nullptr) { - resourceManager->UpdateResConfig(*resConfig); - APP_LOGI("%{public}s Notify ResourceManager.", __func__); + if (resConfig != nullptr) { + APP_LOGI("make resource mgr data"); + + if (!language.empty()) { + UErrorCode status = U_ZERO_ERROR; + icu::Locale locale = icu::Locale::forLanguageTag(language, status); + APP_LOGI("get Locale::forLanguageTag return[%{public}d].", static_cast(status)); + if (status == U_ZERO_ERROR) { + resConfig->SetLocaleInfo(locale); } } + + resConfig->SetColorMode(ConvertColorMode(colormode)); + + auto resourceManager = GetResourceManager(); + if (resourceManager != nullptr) { + resourceManager->UpdateResConfig(*resConfig); + APP_LOGI("%{public}s Notify ResourceManager.", __func__); + } } // Notify WindowScene @@ -900,7 +984,9 @@ void Ability::OnConfigurationUpdatedNotify(const Configuration &changeConfigurat APP_LOGE("%{public}s scene_ -> UpdateConfiguration success.", __func__); } - abilityContext_->SetConfiguration(application_->GetConfiguration()); + if (abilityContext_ != nullptr && application_ != nullptr) { + abilityContext_->SetConfiguration(application_->GetConfiguration()); + } // Notify Ability Subclass OnConfigurationUpdated(changeConfiguration); APP_LOGI("%{public}s Notify Ability Subclass.", __func__); @@ -1220,6 +1306,15 @@ void Ability::Dump(const std::string &extra) } } +/** + * @brief dump ability info + * + * @param params dump params that indicate different dump targets + * @param info dump ability info +*/ +void Ability::Dump(const std::vector ¶ms, std::vector &info) +{} + /** * @brief Keeps this Service ability in the background and displays a notification bar. * To use this method, you need to request the ohos.permission.KEEP_BACKGROUND_RUNNING permission from the system. @@ -1943,6 +2038,30 @@ bool Ability::DeleteForm(const int64_t formId) return DeleteForm(formId, DELETE_FORM); } +/** + * @brief Keep this Service ability in the background and displays a notification bar. + * + * @param wantAgent Indicates which ability to start when user click the notification bar. + * @return the method result code, 0 means succeed + */ +int Ability::StartBackgroundRunning(const AbilityRuntime::WantAgent::WantAgent &wantAgent) +{ + uint32_t defaultBgMode = 0; + BackgroundTaskMgr::ContinuousTaskParam taskParam = BackgroundTaskMgr::ContinuousTaskParam(false, defaultBgMode, + std::make_shared(wantAgent), abilityInfo_->name, GetToken()); + return BackgroundTaskMgr::BackgroundTaskMgrHelper::RequestStartBackgroundRunning(taskParam); +} + +/** + * @brief Cancel background running of this ability to free up system memory. + * + * @return the method result code, 0 means succeed + */ +int Ability::StopBackgroundRunning() +{ + return BackgroundTaskMgr::BackgroundTaskMgrHelper::RequestStopBackgroundRunning(abilityInfo_->name, GetToken()); +} + /** * @brief Cast temp form with formId. * @@ -3258,7 +3377,7 @@ sptr Ability::GetWindowOption(const Want &want) 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); + option->SetWindowType(Rosen::WindowType::WINDOW_TYPE_DESKTOP); } APP_LOGI("%{public}s end", __func__); @@ -3270,6 +3389,13 @@ void Ability::DoOnForeground(const Want& want) if (abilityWindow_ != nullptr) { APP_LOGI("%{public}s begin abilityWindow_->OnPostAbilityForeground, sceneFlag:%{public}d.", __func__, sceneFlag_); + auto window = abilityWindow_->GetWindow(); + if (window != nullptr && want.HasParameter(Want::PARAM_RESV_WINDOW_MODE)) { + auto windowMode = want.GetIntParam(Want::PARAM_RESV_WINDOW_MODE, + AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED); + window->SetWindowMode(static_cast(windowMode)); + APP_LOGI("set window mode = %{public}d.", windowMode); + } abilityWindow_->OnPostAbilityForeground(sceneFlag_); APP_LOGI("%{public}s end abilityWindow_->OnPostAbilityForeground.", __func__); } else { @@ -3300,5 +3426,76 @@ int Ability::GetCurrentWindowMode() } return windowMode; } + +void Ability::OnCreate(Rosen::DisplayId displayId) +{ + APP_LOGI("%{public}s called.", __func__); +} + +void Ability::OnDestroy(Rosen::DisplayId displayId) +{ + APP_LOGI("%{public}s called.", __func__); +} + +void Ability::OnChange(Rosen::DisplayId displayId, Rosen::DisplayChangeEvent changeEvent) +{ + APP_LOGI("%{public}s start, displayId: %{public}" PRIu64", changeEvent: %{public}d.", __func__, + displayId, changeEvent); + + // Get display + auto display = Rosen::DisplayManager::GetInstance().GetDisplayById(displayId); + if (!display) { + APP_LOGE("Get display by displayId %{public}" PRIu64" failed.", displayId); + } + + // Notify ResourceManager + float density = display->GetVirtualPixelRatio(); + int32_t width = display->GetWidth(); + int32_t height = display->GetHeight(); + std::unique_ptr resConfig(Global::Resource::CreateResConfig()); + if (resConfig != nullptr) { + resConfig->SetScreenDensity(ConvertDensity(density)); + resConfig->SetDirection(ConvertDirection(height, width)); + + auto resourceManager = GetResourceManager(); + if (resourceManager != nullptr) { + resourceManager->UpdateResConfig(*resConfig); + APP_LOGI("%{public}s Notify ResourceManager.", __func__); + } + } + + // Notify ability + Configuration newConfig; + newConfig.AddItem(displayId, ConfigurationInner::APPLICATION_DIRECTION, GetDirectionStr(height, width)); + newConfig.AddItem(displayId, ConfigurationInner::APPLICATION_DENSITYDPI, GetDensityStr(density)); + + std::vector changeKeyV; + auto configuration = application_->GetConfiguration(); + configuration->CompareDifferent(changeKeyV, newConfig); + int size = changeKeyV.size(); + APP_LOGI("changeKeyV size :%{public}d", size); + if (!changeKeyV.empty()) { + configuration->Merge(changeKeyV, newConfig); + OnConfigurationUpdated(*configuration); + } + + APP_LOGI("%{public}s end", __func__); +} + +void Ability::RequsetFocus(const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + if (abilityWindow_ == nullptr) { + return; + } + auto window = abilityWindow_->GetWindow(); + if (window != nullptr && want.HasParameter(Want::PARAM_RESV_WINDOW_MODE)) { + auto windowMode = want.GetIntParam(Want::PARAM_RESV_WINDOW_MODE, + AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED); + window->SetWindowMode(static_cast(windowMode)); + APP_LOGI("set window mode = %{public}d.", windowMode); + } + abilityWindow_->OnPostAbilityForeground(sceneFlag_); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/src/ability_context.cpp b/frameworks/kits/ability/native/src/ability_context.cpp index 4b22e8595538aa7940490976cbed6ca21639c481..89a120c423fadfcd5a1c5d3da0747566f3c2a18a 100644 --- a/frameworks/kits/ability/native/src/ability_context.cpp +++ b/frameworks/kits/ability/native/src/ability_context.cpp @@ -28,25 +28,8 @@ namespace AppExecFwk { int AbilityContext::ABILITY_CONTEXT_DEFAULT_REQUEST_CODE(0); -/** - * @brief Starts a new ability. - * An ability using the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE template uses this method - * to start a specific ability. The system locates the target ability from installed abilities based on the value - * of the want parameter and then starts it. You can specify the ability to start using the want parameter. - * - * @param want Indicates the Want containing information about the target ability to start. - * - * @param requestCode Indicates the request code returned after the ability using the AbilityInfo.AbilityType.PAGE - * template is started. You can define the request code to identify the results returned by abilities. The value - * ranges from 0 to 65535. This parameter takes effect only on abilities using the AbilityInfo.AbilityType.PAGE - * template. - * - * @return errCode ERR_OK on success, others on failure. - * - */ ErrCode AbilityContext::StartAbility(const AAFwk::Want &want, int requestCode) { - APP_LOGI("%{public}s begin.", __func__); APP_LOGI("AbilityContext::StartAbility called, requestCode = %{public}d", requestCode); AppExecFwk::AbilityType type = GetAbilityInfoType(); @@ -61,23 +44,11 @@ ErrCode AbilityContext::StartAbility(const AAFwk::Want &want, int requestCode) if (err != ERR_OK) { APP_LOGE("AbilityContext::StartAbility is failed %{public}d", err); } - APP_LOGI("%{public}s end.", __func__); return err; } -/** - * @brief Starts a new ability with special ability start setting. - * - * @param want Indicates the Want containing information about the target ability to start. - * @param requestCode Indicates the request code returned after the ability is started. You can define the request code - * to identify the results returned by abilities. The value ranges from 0 to 65535. - * @param abilityStartSetting Indicates the special start setting used in starting ability. - * - * @return errCode ERR_OK on success, others on failure. - */ ErrCode AbilityContext::StartAbility(const Want &want, int requestCode, const AbilityStartSetting &abilityStartSetting) { - APP_LOGI("%{public}s begin.", __func__); AppExecFwk::AbilityType type = GetAbilityInfoType(); if (AppExecFwk::AbilityType::PAGE != type && AppExecFwk::AbilityType::SERVICE != type) { APP_LOGE("AbilityContext::StartAbility AbilityType = %{public}d", type); @@ -92,18 +63,9 @@ ErrCode AbilityContext::StartAbility(const Want &want, int requestCode, const Ab APP_LOGE("AbilityContext::StartAbility is failed %{public}d", err); } - APP_LOGI("%{public}s end.", __func__); return err; } -/** - * @brief Destroys another ability you had previously started by calling Ability.startAbilityForResult - * (ohos.aafwk.content.Want, int, ohos.aafwk.ability.startsetting.AbilityStartSetting) with the same requestCode passed. - * - * @param requestCode Indicates the request code passed for starting the ability. - * - * @return errCode ERR_OK on success, others on failure. - */ ErrCode AbilityContext::TerminateAbility(int requestCode) { APP_LOGI("%{public}s begin.", __func__); @@ -115,11 +77,6 @@ ErrCode AbilityContext::TerminateAbility(int requestCode) return err; } -/** - * @brief Destroys the current ability. - * - * @return errCode ERR_OK on success, others on failure. - */ ErrCode AbilityContext::TerminateAbility() { APP_LOGI("%{public}s begin.", __func__); @@ -154,24 +111,11 @@ ErrCode AbilityContext::TerminateAbility() return err; } -/** - * @brief Obtains the bundle name of the ability that called the current ability. - * You can use the obtained bundle name to check whether the calling ability is allowed to receive the data you will - * send. If you did not use Ability.startAbilityForResult(ohos.aafwk.content.Want, int, - * ohos.aafwk.ability.startsetting.AbilityStartSetting) to start the calling ability, null is returned. - * - * @return Returns the bundle name of the calling ability; returns null if no calling ability is available. - */ std::string AbilityContext::GetCallingBundle() { return callingBundleName_; } -/** - * @brief Obtains the ohos.bundle.ElementName object of the current ability. - * - * @return Returns the ohos.bundle.ElementName object of the current ability. - */ std::shared_ptr AbilityContext::GetElementName() { APP_LOGI("%{public}s begin.", __func__); @@ -193,11 +137,6 @@ std::shared_ptr AbilityContext::GetElementName() return elementName; } -/** - * @brief Obtains the ElementName of the ability that called the current ability. - * - * @return Returns the ElementName of the calling ability; returns null if no calling ability is available. - */ std::shared_ptr AbilityContext::GetCallingAbility() { APP_LOGI("%{public}s begin.", __func__); @@ -214,15 +153,6 @@ std::shared_ptr AbilityContext::GetCallingAbility() return elementName; } -/** - * @brief Connects the current ability to an ability - * - * @param want Indicates the want containing information about the ability to connect - * - * @param conn Indicates the callback object when the target ability is connected. - * - * @return True means success and false means failure - */ bool AbilityContext::ConnectAbility(const Want &want, const sptr &conn) { APP_LOGI("%{public}s begin.", __func__); @@ -250,13 +180,6 @@ bool AbilityContext::ConnectAbility(const Want &want, const sptr &conn) { APP_LOGI("%{public}s begin.", __func__); @@ -276,16 +199,6 @@ ErrCode AbilityContext::DisconnectAbility(const sptr return ret; } -/** - * @brief Destroys another ability that uses the AbilityInfo.AbilityType.SERVICE template. - * The current ability using either the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE - * template can call this method to destroy another ability that uses the AbilityInfo.AbilityType.SERVICE - * template. The current ability itself can be destroyed by calling the terminateAbility() method. - * - * @param want Indicates the Want containing information about the ability to destroy. - * - * @return Returns true if the ability is destroyed successfully; returns false otherwise. - */ bool AbilityContext::StopAbility(const AAFwk::Want &want) { APP_LOGI("%{public}s begin.", __func__); @@ -312,200 +225,91 @@ sptr AbilityContext::GetToken() return token_; } -/** - * @brief Obtains information about the current application. The returned application information includes basic - * information such as the application name and application permissions. - * - * @return Returns the ApplicationInfo for the current application. - */ std::shared_ptr AbilityContext::GetApplicationInfo() const { return ContextContainer::GetApplicationInfo(); } -/** - * @brief Obtains the application-specific cache directory on the device's internal storage. The system - * automatically deletes files from the cache directory if disk space is required elsewhere on the device. - * Older files are always deleted first. - * - * @return Returns the application-specific cache directory. - */ std::string AbilityContext::GetCacheDir() { return ContextContainer::GetCacheDir(); } -/** - * @brief Obtains the application-specific code-cache directory on the device's internal storage. - * The system will delete any files stored in this location both when your specific application is upgraded, - * and when the entire platform is upgraded. - * - * @return Returns the application-specific code-cache directory. - */ std::string AbilityContext::GetCodeCacheDir() { return ContextContainer::GetCodeCacheDir(); } -/** - * @brief Obtains the local database path. - * If the local database path does not exist, the system creates one and returns the created path. - * - * @return Returns the local database file. - */ std::string AbilityContext::GetDatabaseDir() { return ContextContainer::GetDatabaseDir(); } -/** - * @brief Obtains the absolute path where all private data files of this application are stored. - * - * @return Returns the absolute path storing all private data files of this application. - */ std::string AbilityContext::GetDataDir() { return ContextContainer::GetDataDir(); } -/** - * @brief Obtains the directory for storing custom data files of the application. - * You can use the returned File object to create and access files in this directory. The files - * can be accessible only by the current application. - * - * @param name Indicates the name of the directory to retrieve. This directory is created as part - * of your application data. - * @param mode Indicates the file operating mode. The value can be 0 or a combination of MODE_PRIVATE. - * - * @return Returns a File object for the requested directory. - */ std::string AbilityContext::GetDir(const std::string &name, int mode) { return ContextContainer::GetDir(name, mode); } -/** - * @brief Obtains an IBundleMgr instance. - * You can use this instance to obtain information about the application bundle. - * - * @return Returns an IBundleMgr instance. - */ sptr AbilityContext::GetBundleManager() const { return ContextContainer::GetBundleManager(); } -/** - * @brief Obtains the path of the package containing the current ability. The returned path contains the resources, - * source code, and configuration files of a module. - * - * @return Returns the path of the package file. - */ std::string AbilityContext::GetBundleCodePath() { return ContextContainer::GetBundleCodePath(); } -/** - * @brief Obtains the bundle name of the current ability. - * - * @return Returns the bundle name of the current ability. - */ std::string AbilityContext::GetBundleName() { return ContextContainer::GetBundleName(); } -/** - * @brief Obtains the path of the OHOS Ability Package (HAP} containing this ability. - * - * @return Returns the path of the HAP containing this ability. - */ std::string AbilityContext::GetBundleResourcePath() { return ContextContainer::GetBundleResourcePath(); } -/** - * @brief Obtains the Context object of the application. - * - * @return Returns the Context object of the application. - */ std::shared_ptr AbilityContext::GetApplicationContext() const { return ContextContainer::GetApplicationContext(); } -/** - * @brief Obtains the Context object of the application. - * - * @return Returns the Context object of the application. - */ std::shared_ptr AbilityContext::GetContext() { return ContextContainer::GetContext(); } -/** - * @brief Obtains an ability manager. - * The ability manager provides information about running processes and memory usage of an application. - * - * @return Returns an IAbilityManager instance. - */ sptr AbilityContext::GetAbilityManager() { return ContextContainer::GetAbilityManager(); } -/** - * Called when getting the ProcessInfo - * - * @return ProcessInfo - */ std::shared_ptr AbilityContext::GetProcessInfo() const { return ContextContainer::GetProcessInfo(); } -/** - * @brief Obtains the type of this application. - * - * @return Returns system if this application is a system application; - * returns normal if it is released in official AppGallery; - * returns other if it is released by a third-party vendor; - * returns an empty string if the query fails. - */ std::string AbilityContext::GetAppType() { return ContextContainer::GetAppType(); } -/** - * @brief Obtains information about the current ability. - * The returned information includes the class name, bundle name, and other information about the current ability. - * - * @return Returns the AbilityInfo object for the current ability. - */ const std::shared_ptr AbilityContext::GetAbilityInfo() { return ContextContainer::GetAbilityInfo(); } -/** - * @brief Obtains the HapModuleInfo object of the application. - * - * @return Returns the HapModuleInfo object of the application. - */ std::shared_ptr AbilityContext::GetHapModuleInfo() { return ContextContainer::GetHapModuleInfo(); } -/** - * @brief Get Current Ability Type - * - * @return Current Ability Type - */ AppExecFwk::AbilityType AbilityContext::GetAbilityInfoType() { std::shared_ptr info = GetAbilityInfo(); @@ -517,28 +321,11 @@ AppExecFwk::AbilityType AbilityContext::GetAbilityInfoType() return info->type; } -/** - * @brief Creates a Context object for an application with the given bundle name. - * - * @param bundleName Indicates the bundle name of the application. - * - * @param flag Indicates the flag for creating a Context object. It can be 0, any of - * the following values, or any combination of the following values: CONTEXT_IGNORE_SECURITY, - * CONTEXT_INCLUDE_CODE, and CONTEXT_RESTRICTED. The value 0 indicates that there is no restriction - * on creating contexts for applications. - * - * @return Returns a Context object created for the specified application. - */ -std::shared_ptr AbilityContext::CreateBundleContext(std::string bundleName, int flag) +std::shared_ptr AbilityContext::CreateBundleContext(std::string bundleName, int flag, int accountId) { - return ContextContainer::CreateBundleContext(bundleName, flag); + return ContextContainer::CreateBundleContext(bundleName, flag, accountId); } -/** - * @brief Obtains a resource manager. - * - * @return Returns a ResourceManager object. - */ std::shared_ptr AbilityContext::GetResourceManager() const { APP_LOGI("%{public}s begin.", __func__); @@ -559,16 +346,6 @@ std::shared_ptr AbilityContext::GetResourceMa return resourceManager; } -/** - * @brief Checks whether the current process has the given permission. - * You need to call requestPermissionsFromUser(java.lang.std::string[],int) to request a permission only - * if the current process does not have the specific permission. - * - * @param permission Indicates the permission to check. This parameter cannot be null. - * - * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; - * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. - */ int AbilityContext::VerifySelfPermission(const std::string &permission) { APP_LOGI("%{public}s begin. permission=%{public}s", __func__, permission.c_str()); @@ -596,15 +373,6 @@ int AbilityContext::VerifySelfPermission(const std::string &permission) return ret; } -/** - * @brief Checks whether the calling process for inter-process communication has the given permission. - * The calling process is not the current process. - * - * @param permission Indicates the permission to check. This parameter cannot be null. - * - * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the calling process has the permission; - * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. - */ int AbilityContext::VerifyCallingPermission(const std::string &permission) { APP_LOGI("%{public}s begin. permission=%{public}s", __func__, permission.c_str()); @@ -632,18 +400,6 @@ int AbilityContext::VerifyCallingPermission(const std::string &permission) return ret; } -/** - * @brief Confirms with the permission management module to check whether a request prompt is required for granting a - * certain permission. You need to call the current method to check whether a prompt is required before calling - * requestPermissionsFromUser(java.lang.String[],int) to request a permission. If a prompt is not required, permission - * request will not be initiated. - * - * @param requestCode Indicates the permission to be queried. This parameter cannot be null. - * - * @return Returns true if the current application does not have the permission and the user does not turn off further - * requests; returns false if the current application already has the permission, the permission is rejected by the - * system, or the permission is denied by the user and the user has turned off further requests. - */ bool AbilityContext::CanRequestPermission(const std::string &permission) { APP_LOGI("%{public}s begin. permission=%{public}s", __func__, permission.c_str()); @@ -671,28 +427,11 @@ bool AbilityContext::CanRequestPermission(const std::string &permission) return ret; } -/** - * @brief When there is a remote call to check whether the remote has permission, otherwise check whether it has - * permission - * - * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. - * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; - * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. - */ int AbilityContext::VerifyCallingOrSelfPermission(const std::string &permission) { return VerifySelfPermission(permission); } -/** - * @brief Query whether the application of the specified PID and UID has been granted a certain permission - * - * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. - * @param pid Process id - * @param uid - * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; - * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. - */ int AbilityContext::VerifyPermission(const std::string &permission, int pid, int uid) { APP_LOGI("%{public}s begin. permission=%{public}s, pid=%{public}d, uid=%{public}d", @@ -740,15 +479,6 @@ void AbilityContext::GetPermissionDes(const std::string &permissionName, std::st APP_LOGI("%{public}s end bms->GetPermissionDef.", __func__); } -/** - * @brief Requests certain permissions from the system. - * This method is called for permission request. This is an asynchronous method. When it is executed, - * the Ability.onRequestPermissionsFromUserResult(int, String[], int[]) method will be called back. - * - * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. - * @param requestCode Indicates the request code to be passed to the Ability.onRequestPermissionsFromUserResult(int, - * String[], int[]) callback method. This code cannot be a negative number. - */ void AbilityContext::RequestPermissionsFromUser(std::vector &permissions, int requestCode) { APP_LOGI("%{public}s begin.", __func__); @@ -782,26 +512,11 @@ void AbilityContext::RequestPermissionsFromUser(std::vector &permis APP_LOGI("%{public}s end.", __func__); } -/* @brief Deletes the specified private file associated with the application. - * - * @param fileName Indicates the name of the file to delete. The file name cannot contain path separators. - * - * @return Returns true if the file is deleted successfully; returns false otherwise. - */ bool AbilityContext::DeleteFile(const std::string &fileName) { return ContextContainer::DeleteFile(fileName); } -/** - * @brief Set deviceId/bundleName/abilityName of the calling ability - * - * @param deviceId deviceId of the calling ability - * - * @param deviceId bundleName of the calling ability - * - * @param deviceId abilityName of the calling ability - */ void AbilityContext::SetCallingContext( const std::string &deviceId, const std::string &bundleName, const std::string &abilityName) { @@ -810,23 +525,11 @@ void AbilityContext::SetCallingContext( callingAbilityName_ = abilityName; } -/** - * @brief Obtains information about the caller of this ability. - * - * @return Returns the caller information. - */ Uri AbilityContext::GetCaller() { return ContextContainer::GetCaller(); } -/** - * Attaches a Context object to the current ability. - * Generally, this method is called after Ability is loaded to provide the application context for the current - * ability. - * - * @param base Indicates a Context object. - */ void AbilityContext::AttachBaseContext(const std::shared_ptr &base) { APP_LOGI("AbilityContext::AttachBaseContext. Start."); @@ -834,222 +537,96 @@ void AbilityContext::AttachBaseContext(const std::shared_ptr &base) APP_LOGI("AbilityContext::AttachBaseContext. End."); } -/** - * @brief Obtains the absolute path to the application-specific cache directory - * on the primary external or shared storage device. - * - * @return Returns the absolute path to the application-specific cache directory on the external or - * shared storage device; returns null if the external or shared storage device is temporarily unavailable. - */ std::string AbilityContext::GetExternalCacheDir() { return ContextContainer::GetExternalCacheDir(); } -/** - * @brief Obtains the absolute path to the directory for storing files for the application on the - * primary external or shared storage device. - * - * @param type Indicates the type of the file directory to return - * - * @return Returns the absolute path to the application file directory on the external or shared storage - * device; returns null if the external or shared storage device is temporarily unavailable. - */ std::string AbilityContext::GetExternalFilesDir(std::string &type) { return ContextContainer::GetExternalFilesDir(type); } -/** - * @brief Obtains the directory for storing files for the application on the device's internal storage. - * - * @return Returns the application file directory. - */ std::string AbilityContext::GetFilesDir() { return ContextContainer::GetFilesDir(); } -/** - * @brief Obtains the absolute path which app created and will be excluded from automatic backup to remote storage. - * The returned path maybe changed if the application is moved to an adopted storage device. - * - * @return The path of the directory holding application files that will not be automatically backed up to remote - * storage. - */ std::string AbilityContext::GetNoBackupFilesDir() { return ContextContainer::GetNoBackupFilesDir(); } -/** - * @brief Remove permissions for all users who have access to specific permissions - * - * @param permission Indicates the permission to unauth. This parameter cannot be null. - * @param uri Indicates the URI to unauth. This parameter cannot be null. - * @param uid Indicates the UID of the unauth to check. - * - */ void AbilityContext::UnauthUriPermission(const std::string &permission, const Uri &uri, int uid) { ContextContainer::UnauthUriPermission(permission, uri, uid); } -/** - * @brief Obtains the distributed file path. - * If the distributed file path does not exist, the system creates one and returns the created path. This method is - * applicable only to the context of an ability rather than that of an application. - * - * @return Returns the distributed file. - */ std::string AbilityContext::GetDistributedDir() { return ContextContainer::GetDistributedDir(); } -/** - * @brief Sets the pattern of this Context based on the specified pattern ID. - * - * @param patternId Indicates the resource ID of the pattern to set. - */ void AbilityContext::SetPattern(int patternId) { ContextContainer::SetPattern(patternId); } -/** - * @brief Obtains the Context object of this ability. - * - * @return Returns the Context object of this ability. - */ std::shared_ptr AbilityContext::GetAbilityPackageContext() { return ContextContainer::GetAbilityPackageContext(); } -/** - * @brief Obtains the name of the current process. - * - * @return Returns the current process name. - */ std::string AbilityContext::GetProcessName() { return ContextContainer::GetProcessName(); } -/** - * @brief InitResourceManager - * - * @param bundleInfo BundleInfo - */ void AbilityContext::InitResourceManager(BundleInfo &bundleInfo, std::shared_ptr &deal) { ContextContainer::InitResourceManager(bundleInfo, deal); } -/** - * @brief Get the string of this Context based on the specified resource ID. - * - * @param resId Indicates the resource ID of the string to get. - * - * @return Returns the string of this Context. - */ std::string AbilityContext::GetString(int resId) { return ContextContainer::GetString(resId); } -/** - * @brief Get the string array of this Context based on the specified resource ID. - * - * @param resId Indicates the resource ID of the string array to get. - * - * @return Returns the string array of this Context. - */ std::vector AbilityContext::GetStringArray(int resId) { return ContextContainer::GetStringArray(resId); } -/** - * @brief Get the integer array of this Context based on the specified resource ID. - * - * @param resId Indicates the resource ID of the integer array to get. - * - * @return Returns the integer array of this Context. - */ std::vector AbilityContext::GetIntArray(int resId) { return ContextContainer::GetIntArray(resId); } -/** - * @brief Obtains the theme of this Context. - * - * @return theme Returns the theme of this Context. - */ std::map AbilityContext::GetTheme() { return ContextContainer::GetTheme(); } -/** - * @brief Sets the theme of this Context based on the specified theme ID. - * - * @param themeId Indicates the resource ID of the theme to set. - */ void AbilityContext::SetTheme(int themeId) { ContextContainer::SetTheme(themeId); } -/** - * @brief Obtains the pattern of this Context. - * - * @return getPattern in interface Context - */ std::map AbilityContext::GetPattern() { return ContextContainer::GetPattern(); } -/** - * @brief Get the color of this Context based on the specified resource ID. - * - * @param resId Indicates the resource ID of the color to get. - * - * @return Returns the color value of this Context. - */ int AbilityContext::GetColor(int resId) { return ContextContainer::GetColor(resId); } -/** - * @brief Obtains the theme id of this Context. - * - * @return int Returns the theme id of this Context. - */ int AbilityContext::GetThemeId() { return ContextContainer::GetThemeId(); } -/** - * @brief - * Destroys this Service ability if the number of times it has been started equals the number represented by the - * given {@code startId}. This method is the same as calling {@link #terminateAbility} to destroy this Service - * ability, except that this method helps you avoid destroying it if a client has requested a Service - * ability startup in {@link ohos.aafwk.ability.Ability#onCommand} but you are unaware of it. - * - * @param startId Indicates the number of startup times of this Service ability passed to - * {@link ohos.aafwk.ability.Ability#onCommand}. The {@code startId} is - * incremented by 1 every time this ability is started. For example, - * if this ability has been started for six times, the value of {@code startId} is {@code 6}. - * - * @return Returns {@code true} if the {@code startId} matches the number of startup times - * and this Service ability will be destroyed; returns {@code false} otherwise. - */ bool AbilityContext::TerminateAbilityResult(int startId) { APP_LOGI("%{public}s begin.", __func__); @@ -1070,71 +647,36 @@ bool AbilityContext::TerminateAbilityResult(int startId) return (errval == ERR_OK) ? true : false; } -/** - * @brief Obtains the current display orientation of this ability. - * - * @return Returns the current display orientation. - */ int AbilityContext::GetDisplayOrientation() { return ContextContainer::GetDisplayOrientation(); } -/** - * @brief Obtains the path storing the preference file of the application. - * If the preference file path does not exist, the system creates one and returns the created path. - * - * @return Returns the preference file path . - */ std::string AbilityContext::GetPreferencesDir() { return ContextContainer::GetPreferencesDir(); } -/** - * @brief Set color mode - * - * @param the value of color mode. - */ void AbilityContext::SetColorMode(int mode) { ContextContainer::SetColorMode(mode); } -/** - * @brief Obtains color mode. - * - * @return Returns the color mode value. - */ int AbilityContext::GetColorMode() { return ContextContainer::GetColorMode(); } -/** - * @brief Obtains the unique ID of the mission containing this ability. - * - * @return Returns the unique mission ID. - */ int AbilityContext::GetMissionId() { return ContextContainer::GetMissionId(); } -/** - * @brief Call this when your ability should be closed and the mission should be completely removed as a part of - * finishing the root ability of the mission. - */ void AbilityContext::TerminateAndRemoveMission() { ContextContainer::TerminateAndRemoveMission(); } -/** - * @brief Starts multiple abilities. - * - * @param wants Indicates the Want containing information array about the target ability to start. - */ void AbilityContext::StartAbilities(const std::vector &wants) { APP_LOGI("%{public}s begin.", __func__); @@ -1144,11 +686,6 @@ void AbilityContext::StartAbilities(const std::vector &wants) APP_LOGI("%{public}s end.", __func__); } -/** - * @brief Checks whether this ability is the first ability in a mission. - * - * @return Returns true is first in Mission. - */ bool AbilityContext::IsFirstInMission() { APP_LOGI("%{public}s begin.", __func__); @@ -1168,115 +705,56 @@ bool AbilityContext::IsFirstInMission() return (errval == ERR_OK) ? true : false; } -/** - * @brief Obtains a task dispatcher that is bound to the UI thread. - * - * @return Returns the task dispatcher that is bound to the UI thread. - */ std::shared_ptr AbilityContext::GetUITaskDispatcher() { return ContextContainer::GetUITaskDispatcher(); } -/** - * @brief Obtains a task dispatcher that is bound to the application main thread. - * - * @return Returns the task dispatcher that is bound to the application main thread. - */ std::shared_ptr AbilityContext::GetMainTaskDispatcher() { return ContextContainer::GetMainTaskDispatcher(); } -/** - * @brief Creates a parallel task dispatcher with a specified priority. - * - * @param name Indicates the task dispatcher name. This parameter is used to locate problems. - * @param priority Indicates the priority of all tasks dispatched by the parallel task dispatcher. - * - * @return Returns a parallel task dispatcher. - */ + std::shared_ptr AbilityContext::CreateParallelTaskDispatcher( const std::string &name, const TaskPriority &priority) { return ContextContainer::CreateParallelTaskDispatcher(name, priority); } -/** - * @brief Creates a serial task dispatcher with a specified priority. - * - * @param name Indicates the task dispatcher name. This parameter is used to locate problems. - * @param priority Indicates the priority of all tasks dispatched by the created task dispatcher. - * - * @return Returns a serial task dispatcher. - */ std::shared_ptr AbilityContext::CreateSerialTaskDispatcher( const std::string &name, const TaskPriority &priority) { return ContextContainer::CreateSerialTaskDispatcher(name, priority); } -/** - * @brief Obtains a global task dispatcher with a specified priority. - * - * @param priority Indicates the priority of all tasks dispatched by the global task dispatcher. - * - * @return Returns a global task dispatcher. - */ std::shared_ptr AbilityContext::GetGlobalTaskDispatcher(const TaskPriority &priority) { return ContextContainer::GetGlobalTaskDispatcher(priority); } -/** - * @brief Requires that tasks associated with a given capability token be moved to the background - * - * @param nonFirst If nonfirst is false and not the lowest ability of the mission, you cannot move mission to end - * - * @return Returns true on success, others on failure. - */ bool AbilityContext::MoveMissionToEnd(bool nonFirst) { return ContextContainer::MoveMissionToEnd(nonFirst); } -/** - * @brief Sets the application to start its ability in lock mission mode. - */ void AbilityContext::LockMission() { ContextContainer::LockMission(); } -/** - * @brief Unlocks this ability by exiting the lock mission mode. - */ void AbilityContext::UnlockMission() { ContextContainer::UnlockMission(); } -/** - * @brief Sets description information about the mission containing this ability. - * - * @param MissionInformation Indicates the object containing information about the - * mission. This parameter cannot be null. - * @return Returns true on success, others on failure. - */ bool AbilityContext::SetMissionInformation(const MissionInformation &missionInformation) { return ContextContainer::SetMissionInformation(missionInformation); } -/** - * set lock screen white list - * - * @param isAllow Whether to allow lock screen. - * - */ void AbilityContext::SetShowOnLockScreen(bool isAllow) { ContextContainer::SetShowOnLockScreen(isAllow); } - } // 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 d8c6ec9d22741c0847173449577171a790c6e446..e4aed208c0b86bafd483c7795b99c2151532e007 100755 --- a/frameworks/kits/ability/native/src/ability_impl.cpp +++ b/frameworks/kits/ability/native/src/ability_impl.cpp @@ -66,7 +66,7 @@ void AbilityImpl::Init(std::shared_ptr &application, const std: void AbilityImpl::Start(const Want &want) { APP_LOGI("%{public}s begin.", __func__); - if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) { + if (ability_ == nullptr || ability_->GetAbilityInfo() == nullptr || abilityLifecycleCallbacks_ == nullptr) { APP_LOGE("AbilityImpl::Start ability_ or abilityLifecycleCallbacks_ is nullptr"); return; } @@ -107,7 +107,7 @@ void AbilityImpl::Start(const Want &want) void AbilityImpl::Stop() { APP_LOGI("%{public}s begin.", __func__); - if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) { + if (ability_ == nullptr || ability_->GetAbilityInfo() == nullptr || abilityLifecycleCallbacks_ == nullptr) { APP_LOGE("AbilityImpl::Stop ability_ or abilityLifecycleCallbacks_ is nullptr"); return; } @@ -133,7 +133,7 @@ void AbilityImpl::Stop() void AbilityImpl::Active() { APP_LOGI("%{public}s begin.", __func__); - if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) { + if (ability_ == nullptr || ability_->GetAbilityInfo() == nullptr || abilityLifecycleCallbacks_ == nullptr) { APP_LOGE("AbilityImpl::Active ability_ or abilityLifecycleCallbacks_ is nullptr"); return; } @@ -159,7 +159,7 @@ void AbilityImpl::Active() void AbilityImpl::Inactive() { APP_LOGI("%{public}s begin.", __func__); - if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) { + if (ability_ == nullptr || ability_->GetAbilityInfo() == nullptr || abilityLifecycleCallbacks_ == nullptr) { APP_LOGE("AbilityImpl::Inactive ability_ or abilityLifecycleCallbacks_ is nullptr"); return; } @@ -194,7 +194,8 @@ int AbilityImpl::GetCompatibleVersion() void AbilityImpl::AfterUnFocused() { APP_LOGI("%{public}s begin.", __func__); - if (!ability_ || !contextDeal_ || !handler_) { + if (!ability_ || !ability_->GetAbilityInfo() || !contextDeal_ || !handler_) { + APP_LOGE("AbilityImpl::AfterUnFocused failed"); return; } @@ -268,7 +269,7 @@ void AbilityImpl::WindowLifeCycleImpl::AfterUnFocused() void AbilityImpl::Foreground(const Want &want) { APP_LOGI("%{public}s begin.", __func__); - if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) { + if (ability_ == nullptr || ability_->GetAbilityInfo() == nullptr || abilityLifecycleCallbacks_ == nullptr) { APP_LOGE("AbilityImpl::Foreground ability_ or abilityLifecycleCallbacks_ is nullptr"); return; } @@ -293,7 +294,7 @@ void AbilityImpl::Foreground(const Want &want) void AbilityImpl::Background() { APP_LOGI("%{public}s begin.", __func__); - if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) { + if (ability_ == nullptr || ability_->GetAbilityInfo() == nullptr || abilityLifecycleCallbacks_ == nullptr) { APP_LOGE("AbilityImpl::Background ability_ or abilityLifecycleCallbacks_ is nullptr"); return; } @@ -838,8 +839,6 @@ Uri AbilityImpl::DenormalizeUri(const Uri &uri) void AbilityImpl::ScheduleUpdateConfiguration(const Configuration &config) { APP_LOGI("%{public}s begin.", __func__); - - if (ability_ == nullptr) { APP_LOGE("AbilityImpl::ScheduleUpdateConfiguration ability_ is nullptr"); return; @@ -919,7 +918,7 @@ void AbilityImpl::ContinueAbility(const std::string& deviceId) ability_->ContinueAbilityWithStack(deviceId); } -void AbilityImpl::NotifyContinuationResult(const int32_t result) +void AbilityImpl::NotifyContinuationResult(int32_t result) { if (ability_ == nullptr) { APP_LOGE("AbilityImpl::NotifyContinuationResult ability_ is nullptr"); diff --git a/frameworks/kits/ability/native/src/ability_local_record.cpp b/frameworks/kits/ability/native/src/ability_local_record.cpp index 1b71efd33191b1b43697381b34c452bd85653289..057ea243ec1604e5f492dee384e1a8222ad50c48 100644 --- a/frameworks/kits/ability/native/src/ability_local_record.cpp +++ b/frameworks/kits/ability/native/src/ability_local_record.cpp @@ -151,5 +151,15 @@ void AbilityLocalRecord::SetCompatibleVersion(int32_t compatibleVersion) { compatibleVersion_ = compatibleVersion; } + +void AbilityLocalRecord::SetWant(const std::shared_ptr &want) +{ + want_ = want; +} + +const std::shared_ptr &AbilityLocalRecord::GetWant() +{ + return want_; +} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/ability_process.cpp b/frameworks/kits/ability/native/src/ability_process.cpp index d7580e7fcad917c0f8b02b558af06e7755bcfda5..2f72f04fc98cb3e3c48849f0789dddb3497724a4 100644 --- a/frameworks/kits/ability/native/src/ability_process.cpp +++ b/frameworks/kits/ability/native/src/ability_process.cpp @@ -89,7 +89,7 @@ ErrCode AbilityProcess::StartAbility(Ability *ability, CallAbilityParam param, C APP_LOGI("AbilityProcess::StartAbility ability: %{public}p is in the abilityResultMap_", ability); map = it->second; } - + callback.errCode = err; map[param.requestCode] = callback; abilityResultMap_[ability] = map; } else { 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 a5563e07cd4b44bbd7d94b58cd97b8226cb2dc36..efa71ba1bb51a1a1d3b75fb23563fcc59a0a0c20 100755 --- a/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp +++ b/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp @@ -15,6 +15,7 @@ #include #include "system_ability_definition.h" #include "if_system_ability_manager.h" +#include "ability_delegator_registry.h" #include "ability_runtime/js_ability.h" #include "ability_runtime/js_ability_context.h" @@ -144,6 +145,12 @@ void JsAbility::OnStart(const Want &want) CreateJsLaunchParam(nativeEngine, GetLaunchParam()), }; CallObjectMethod("onCreate", argv, ArraySize(argv)); + + auto delegator = AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator(); + if (delegator) { + HILOG_INFO("Call AbilityDelegator::PostPerformStart"); + delegator->PostPerformStart(CreateADelegatorAbilityProperty()); + } } void JsAbility::OnStop() @@ -151,8 +158,16 @@ void JsAbility::OnStop() Ability::OnStop(); CallObjectMethod("onDestroy"); + + auto delegator = AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator(); + if (delegator) { + HILOG_INFO("Call AbilityDelegator::PostPerformStop"); + delegator->PostPerformStop(CreateADelegatorAbilityProperty()); + } + bool ret = ConnectionManager::GetInstance().DisconnectCaller(AbilityContext::token_); if (ret) { + ConnectionManager::GetInstance().ReportConnectionLeakEvent(getpid(), gettid()); HILOG_INFO("The service connection is not disconnected."); } } @@ -168,6 +183,12 @@ void JsAbility::OnSceneCreated() } NativeValue *argv[] = {jsAppWindowStage->Get()}; CallObjectMethod("onWindowStageCreate", argv, ArraySize(argv)); + + auto delegator = AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator(); + if (delegator) { + HILOG_INFO("Call AbilityDelegator::PostPerformScenceCreated"); + delegator->PostPerformScenceCreated(CreateADelegatorAbilityProperty()); + } } void JsAbility::OnSceneRestored() @@ -181,6 +202,12 @@ void JsAbility::OnSceneRestored() } NativeValue *argv[] = {jsAppWindowStage->Get()}; CallObjectMethod("onWindowStageRestore", argv, ArraySize(argv)); + + auto delegator = AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator(); + if (delegator) { + HILOG_INFO("Call AbilityDelegator::PostPerformScenceRestored"); + delegator->PostPerformScenceRestored(CreateADelegatorAbilityProperty()); + } } void JsAbility::onSceneDestroyed() @@ -188,6 +215,12 @@ void JsAbility::onSceneDestroyed() Ability::onSceneDestroyed(); CallObjectMethod("onWindowStageDestroy"); + + auto delegator = AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator(); + if (delegator) { + HILOG_INFO("Call AbilityDelegator::PostPerformScenceDestroyed"); + delegator->PostPerformScenceDestroyed(CreateADelegatorAbilityProperty()); + } } void JsAbility::OnForeground(const Want &want) @@ -210,6 +243,12 @@ void JsAbility::OnForeground(const Want &want) obj->SetProperty("lastRequestWant", jsWant); CallObjectMethod("onForeground", &jsWant, 1); + + auto delegator = AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator(); + if (delegator) { + HILOG_INFO("Call AbilityDelegator::PostPerformForeground"); + delegator->PostPerformForeground(CreateADelegatorAbilityProperty()); + } } void JsAbility::OnBackground() @@ -217,6 +256,12 @@ void JsAbility::OnBackground() Ability::OnBackground(); CallObjectMethod("onBackground"); + + auto delegator = AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator(); + if (delegator) { + HILOG_INFO("Call AbilityDelegator::PostPerformBackground"); + delegator->PostPerformBackground(CreateADelegatorAbilityProperty()); + } } bool JsAbility::OnContinue(WantParams &wantParams) @@ -260,13 +305,22 @@ void JsAbility::OnConfigurationUpdated(const Configuration &configuration) HandleScope handleScope(jsRuntime_); auto& nativeEngine = jsRuntime_.GetNativeEngine(); - JsAbilityContext::ConfigurationUpdated(&nativeEngine, shellContextRef_, GetAbilityContext()->GetConfiguration()); + auto fullConfig = GetAbilityContext()->GetConfiguration(); + JsAbilityContext::ConfigurationUpdated(&nativeEngine, shellContextRef_, fullConfig); napi_value napiConfiguration = OHOS::AppExecFwk::WrapConfiguration( - reinterpret_cast(&nativeEngine), configuration); + reinterpret_cast(&nativeEngine), *fullConfig); NativeValue* jsConfiguration = reinterpret_cast(napiConfiguration); CallObjectMethod("onConfigurationUpdated", &jsConfiguration, 1); } +void JsAbility::UpdateContextConfiguration() +{ + HILOG_INFO("%{public}s called.", __func__); + HandleScope handleScope(jsRuntime_); + auto& nativeEngine = jsRuntime_.GetNativeEngine(); + JsAbilityContext::ConfigurationUpdated(&nativeEngine, shellContextRef_, GetAbilityContext()->GetConfiguration()); +} + void JsAbility::OnNewWant(const Want &want) { HILOG_INFO("%{public}s begin.", __func__); @@ -455,14 +509,48 @@ void JsAbility::DoOnForeground(const Want &want) HILOG_ERROR("restore: content storage is nullptr"); } OnSceneRestored(); - NotityContinuationResult(want, true); + WaitingDistributedObjectSyncComplete(want); } else { OnSceneCreated(); } + } else { + auto window = scene_->GetMainWindow(); + if (window != nullptr && want.HasParameter(Want::PARAM_RESV_WINDOW_MODE)) { + auto windowMode = want.GetIntParam(Want::PARAM_RESV_WINDOW_MODE, + AAFwk::AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED); + window->SetWindowMode(static_cast(windowMode)); + HILOG_INFO("set window mode = %{public}d.", windowMode); + } } 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__); } + +std::shared_ptr JsAbility::CreateADelegatorAbilityProperty() +{ + auto property = std::make_shared(); + property->token_ = GetAbilityContext()->GetToken(); + property->name_ = GetAbilityName(); + property->lifecycleState_ = GetState(); + + return property; +} + +void JsAbility::RequsetFocus(const Want &want) +{ + HILOG_INFO("%{public}s called.", __func__); + if (scene_ == nullptr) { + return; + } + auto window = scene_->GetMainWindow(); + if (window != nullptr && want.HasParameter(Want::PARAM_RESV_WINDOW_MODE)) { + auto windowMode = want.GetIntParam(Want::PARAM_RESV_WINDOW_MODE, + AAFwk::AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED); + window->SetWindowMode(static_cast(windowMode)); + HILOG_INFO("set window mode = %{public}d.", windowMode); + } + scene_->GoForeground(Ability::sceneFlag_); +} } // namespace AbilityRuntime } // namespace OHOS 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 385b00081e0b3a465c903f4bb2119a20aecfe9f1..edfd6546923a9afcab000847b0f6d4dd2f3aea53 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 @@ -934,7 +934,7 @@ NativeValue* CreateJsAbilityContext(NativeEngine& engine, std::shared_ptrGetConfiguration(); if (configuration != nullptr) { - object->SetProperty("configuration", CreateJsConfiguration(engine, *configuration)); + object->SetProperty("config", CreateJsConfiguration(engine, *configuration)); } BindNativeFunction(engine, *object, "startAbility", JsAbilityContext::StartAbility); 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 1f317c0f8e9729646c611f12a4bc69529d1bd776..76b16908e1db9803802758bc4062d9a01ce0a494 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 @@ -136,89 +136,57 @@ private: NativeValue* ReleaseInner(NativeEngine& engine, NativeCallbackInfo& info) { HILOG_DEBUG("JsCallerComplex::%{public}s, called", __func__); - constexpr size_t ARGC_ZERO = 0; - constexpr size_t ARGC_ONE = 1; - int errCode = 0; - AsyncTask::ExecuteCallback execute = - [weak = context_, callback = callerCallBackObj_, &errCode] (NativeEngine& engine, AsyncTask& task) { - auto context = weak.lock(); - if (context == nullptr) { - HILOG_ERROR("JsCallerComplex::%{public}s, context is nullptr", "ReleaseInner::ExecuteCallback"); - errCode = -1; - return; - } - - errCode = context->ReleaseAbility(callback); - HILOG_DEBUG("JsCallerComplex::%{public}s %{public}d, end", "ReleaseInner::ExecuteCallback", errCode); - }; - AsyncTask::CompleteCallback complete = - [errCode] (NativeEngine& engine, AsyncTask& task, int32_t status) { - if (errCode == 0) { - task.Resolve(engine, engine.CreateUndefined()); - } else { - task.Reject(engine, CreateJsError(engine, errCode, "CallerComplex Release Failed.")); - } - HILOG_DEBUG("JsCallerComplex::%{public}s, end", "ReleaseInner::CompleteCallback"); - }; - - NativeValue* lastParam = ((info.argc == ARGC_ONE) ? info.argv[ARGC_ZERO] : nullptr); - NativeValue* retsult = nullptr; - AsyncTask::Schedule( - engine, - CreateAsyncTaskWithLastParam(engine, lastParam, std::move(execute), std::move(complete), &retsult)); - - return retsult; + if (callerCallBackObj_ == nullptr) { + HILOG_ERROR("JsCallerComplex::%{public}s, CallBacker is nullptr", __func__); + return CreateJsError(engine, -1, "CallerComplex callback is nullptr."); + } + + auto context = context_.lock(); + if (context == nullptr) { + HILOG_ERROR("JsCallerComplex::%{public}s, context is nullptr", __func__); + return CreateJsError(engine, -1, "CallerComplex get context failed."); + } + + auto retErr = context->ReleaseAbility(callerCallBackObj_); + if (retErr != ERR_OK) { + HILOG_ERROR("JsCallerComplex::%{public}s, ReleaseAbility failed %{public}d", + __func__, static_cast(retErr)); + return CreateJsError(engine, -1, "CallerComplex get context failed."); + } + + return engine.CreateUndefined(); } NativeValue* SetOnReleaseCallBackInner(NativeEngine& engine, NativeCallbackInfo& info) { HILOG_DEBUG("JsCallerComplex::%{public}s, begin", __func__); - constexpr size_t ARGC_ONE = 1; constexpr size_t ARGC_TWO = 2; - bool errCode = true; if (info.argc >= ARGC_TWO) { HILOG_ERROR("JsCallerComplex::%{public}s, Invalid input params", __func__); - return engine.CreateUndefined(); + return CreateJsError(engine, -1, "CallerComplex on release CallBack input params error."); } if (!info.argv[0]->IsCallable()) { HILOG_ERROR("JsCallerComplex::%{public}s, IsCallable is %{public}s.", __func__, ((info.argv[0]->IsCallable()) ? "true" : "false")); - return engine.CreateUndefined(); + return CreateJsError(engine, -1, "CallerComplex on release CallBack input params not function."); + } + + if (callerCallBackObj_ == nullptr) { + HILOG_ERROR("JsCallerComplex::%{public}s, param1 is nullptr", __func__); + return CreateJsError(engine, -1, "CallerComplex on release CallBacker is nullptr."); } - while (errCode) { - if (callerCallBackObj_ == nullptr) { - HILOG_ERROR("JsCallerComplex::%{public}s, param1 is nullptr", __func__); - errCode = false; - break; - } - auto param1 = info.argv[0]; - if (param1 == nullptr) { - HILOG_ERROR("JsCallerComplex::%{public}s, param1 is nullptr", __func__); - errCode = false; - break; - } - jsreleaseCallBackObj_ = - std::unique_ptr(releaseCallBackEngine_.CreateReference(param1, 1)); - auto task = [notify = this] (const std::string &str) { notify->OnReleaseNotify(str); }; - callerCallBackObj_->SetOnRelease(task); - break; + + auto param1 = info.argv[0]; + if (param1 == nullptr) { + HILOG_ERROR("JsCallerComplex::%{public}s, param1 is nullptr", __func__); + return CreateJsError(engine, -1, "CallerComplex on release input params isn`t function."); } - AsyncTask::CompleteCallback complete = - [errCode] (NativeEngine& engine, AsyncTask& task, int32_t status) { - if (errCode) { - task.Resolve(engine, engine.CreateUndefined()); - } else { - task.Reject(engine, CreateJsError(engine, -1, "CallerComplex On Release CallBack Failed.")); - } - HILOG_DEBUG("JsCallerComplex::%{public}s, %{public}s end", "ReleaseInner::CompleteCallback", - (errCode ? "true" : "false")); - }; - NativeValue* lastParam = ((info.argc == ARGC_TWO) ? info.argv[ARGC_ONE] : nullptr); - NativeValue* retsult = nullptr; - AsyncTask::Schedule(engine, - CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &retsult)); + + jsreleaseCallBackObj_ = std::unique_ptr(releaseCallBackEngine_.CreateReference(param1, 1)); + auto task = [notify = this] (const std::string &str) { notify->OnReleaseNotify(str); }; + callerCallBackObj_->SetOnRelease(task); HILOG_DEBUG("JsCallerComplex::%{public}s, end", __func__); - return retsult; + return engine.CreateUndefined(); } private: diff --git a/frameworks/kits/ability/native/src/ability_thread.cpp b/frameworks/kits/ability/native/src/ability_thread.cpp index 2b10f6edcac472e4f5011cb1da9bde758bd6e668..d962b23b2c187e6b5bc464adf15b4248ccb1ceb3 100644 --- a/frameworks/kits/ability/native/src/ability_thread.cpp +++ b/frameworks/kits/ability/native/src/ability_thread.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,8 +15,6 @@ #include "ability_thread.h" -#include - #include "ability_context_impl.h" #include "ability_impl_factory.h" #include "ability_loader.h" @@ -45,6 +43,8 @@ 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"; +constexpr static char WORK_SCHEDULER_EXTENSION[] = "WorkSchedulerExtension"; +constexpr static char ACCESSIBILITY_EXTENSION[] = "AccessibilityExtension"; /** * @brief Default constructor used to create a AbilityThread instance. @@ -114,6 +114,12 @@ std::string AbilityThread::CreateAbilityName(const std::shared_ptrextensionAbilityType == ExtensionAbilityType::DATASHARE) { abilityName = DATA_SHARE_EXT_ABILITY; } + if (abilityInfo->extensionAbilityType == ExtensionAbilityType::WORK_SCHEDULER) { + abilityName = WORK_SCHEDULER_EXTENSION; + } + if (abilityInfo->extensionAbilityType == ExtensionAbilityType::ACCESSIBILITY) { + abilityName = ACCESSIBILITY_EXTENSION; + } APP_LOGI("CreateAbilityName extension type, abilityName:%{public}s", abilityName.c_str()); } else { abilityName = abilityInfo->name; @@ -527,12 +533,13 @@ void AbilityThread::HandleCommandAbility(const Want &want, bool restart, int sta { BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); APP_LOGI("AbilityThread::HandleCommandAbility begin"); - APP_LOGI("AbilityThread::HandleCommandAbility before abilityImpl_->CommandAbility"); + if (abilityImpl_ == nullptr) { + APP_LOGE("AbilityThread::HandleCommandAbility failed. abilityImpl_ == nullptr"); + return; + } abilityImpl_->CommandAbility(want, restart, startId); - APP_LOGI("AbilityThread::HandleCommandAbility after abilityImpl_->CommandAbility"); APP_LOGI("AbilityThread::HandleCommandAbility before ScheduleCommandAbilityDone"); ErrCode err = AbilityManagerClient::GetInstance()->ScheduleCommandAbilityDone(token_); - APP_LOGI("AbilityThread::HandleCommandAbility after ScheduleCommandAbilityDone"); if (err != ERR_OK) { APP_LOGE("AbilityThread:: HandleCommandAbility faile err = %{public}d", err); } @@ -665,11 +672,6 @@ void AbilityThread::ScheduleRestoreAbilityState(const PacMap &state) void AbilityThread::ScheduleUpdateConfiguration(const Configuration &config) { APP_LOGI("AbilityThread::ScheduleUpdateConfiguration begin"); - if (abilityImpl_ == nullptr) { - APP_LOGE("AbilityThread::ScheduleUpdateConfiguration abilityImpl_ is nullptr"); - return; - } - wptr weak = this; auto task = [weak, config]() { auto abilityThread = weak.promote(); @@ -677,7 +679,12 @@ void AbilityThread::ScheduleUpdateConfiguration(const Configuration &config) APP_LOGE("abilityThread is nullptr, ScheduleUpdateConfiguration failed."); return; } - abilityThread->HandleUpdateConfiguration(config); + + if (abilityThread->isExtension_) { + abilityThread->HandleExtensionUpdateConfiguration(config); + } else { + abilityThread->HandleUpdateConfiguration(config); + } }; if (abilityHandler_ == nullptr) { @@ -709,6 +716,20 @@ void AbilityThread::HandleUpdateConfiguration(const Configuration &config) APP_LOGI("AbilityThread::HandleUpdateConfiguration end"); } +void AbilityThread::HandleExtensionUpdateConfiguration(const Configuration &config) +{ + APP_LOGI("AbilityThread::HandleExtensionUpdateConfiguration begin"); + if (!extensionImpl_) { + APP_LOGE("AbilityThread::HandleExtensionUpdateConfiguration extensionImpl_ is nullptr"); + return; + } + + APP_LOGI("AbilityThread::HandleExtensionUpdateConfiguration before extensionImpl_->ScheduleUpdateConfiguration"); + extensionImpl_->ScheduleUpdateConfiguration(config); + APP_LOGI("AbilityThread::HandleExtensionUpdateConfiguration after extensionImpl_->ScheduleUpdateConfiguration"); + APP_LOGI("AbilityThread::HandleExtensionUpdateConfiguration end"); +} + /** * @description: Provide operating system AbilityTransaction information to the observer * @param want Indicates the structure containing Transaction information about the ability. @@ -759,7 +780,7 @@ void AbilityThread::ScheduleAbilityTransaction(const Want &want, const LifeCycle */ void AbilityThread::ScheduleConnectAbility(const Want &want) { - APP_LOGI("AbilityThread::ScheduleConnectAbility begin, isExtension_:%{public}d", isExtension_); + APP_LOGI("AbilityThread::ScheduleConnectAbility begin, isExtension_:%{public}d", isExtension_); wptr weak = this; auto task = [weak, want]() { auto abilityThread = weak.promote(); @@ -792,7 +813,7 @@ void AbilityThread::ScheduleConnectAbility(const Want &want) */ void AbilityThread::ScheduleDisconnectAbility(const Want &want) { - APP_LOGI("AbilityThread::ScheduleDisconnectAbility begin, isExtension_:%{public}d", isExtension_); + APP_LOGI("AbilityThread::ScheduleDisconnectAbility begin, isExtension_:%{public}d", isExtension_); wptr weak = this; auto task = [weak, want]() { auto abilityThread = weak.promote(); @@ -1144,7 +1165,7 @@ int AbilityThread::BatchInsert(const Uri &uri, const std::vectorContinueAbility(deviceId); } -void AbilityThread::NotifyContinuationResult(const int32_t result) +void AbilityThread::NotifyContinuationResult(int32_t result) { APP_LOGI("NotifyContinuationResult, result:%{public}d", result); if (abilityImpl_ == nullptr) { @@ -1255,8 +1276,8 @@ void AbilityThread::AbilityThreadMain( { APP_LOGI("AbilityThread::AbilityThreadMain begin"); sptr thread = sptr(new (std::nothrow) AbilityThread()); - if (thread == nullptr) { - APP_LOGE("AbilityThread::AbilityThreadMain failed,thread is nullptr"); + if (thread == nullptr || abilityRecord == nullptr) { + APP_LOGE("AbilityThread::AbilityThreadMain failed, thread is nullptr"); return; } thread->InitExtensionFlag(abilityRecord); @@ -1273,10 +1294,12 @@ void AbilityThread::InitExtensionFlag(const std::shared_ptr APP_LOGI("AbilityThread::InitExtensionFlag start"); if (abilityRecord == nullptr) { APP_LOGE("AbilityThread::InitExtensionFlag abilityRecord null"); + return; } std::shared_ptr abilityInfo = abilityRecord->GetAbilityInfo(); if (abilityInfo == nullptr) { APP_LOGE("AbilityThread::InitExtensionFlag abilityInfo null"); + return; } APP_LOGI("AbilityThread::InitExtensionFlag:%{public}d", abilityInfo->type); if (abilityInfo->type == AppExecFwk::AbilityType::EXTENSION) { @@ -1554,10 +1577,29 @@ std::shared_ptr AbilityThread::BuildAbilityConte return abilityContextImpl; } -void AbilityThread::DumpAbilityInfo(std::vector &info) +void AbilityThread::DumpAbilityInfo(const std::vector ¶ms, std::vector &info) { APP_LOGI("%{public}s begin.", __func__); - std::string dumpInfo = " event:"; + if (!params.empty()) { + if (abilityImpl_->IsStageBasedModel()) { + auto scene = currentAbility_->GetScene(); + if (scene == nullptr) { + APP_LOGE("DumpAbilityInfo scene == nullptr"); + return; + } + auto window = scene->GetMainWindow(); + if (window == nullptr) { + APP_LOGE("DumpAbilityInfo window == nullptr"); + return; + } + window->DumpInfo(params, info); + } else { + currentAbility_->Dump(params, info); + } + + return; + } + std::string dumpInfo = " event:"; info.push_back(dumpInfo); if (!abilityHandler_) { @@ -1574,19 +1616,62 @@ void AbilityThread::DumpAbilityInfo(std::vector &info) runner->DumpRunnerInfo(dumpInfo); info.push_back(dumpInfo); + if (!currentAbility_) { + APP_LOGI("currentAbility is nullptr."); + return; + } + + const auto ablityContext = currentAbility_->GetAbilityContext(); + if (!ablityContext) { + APP_LOGI("current ability context is nullptr."); + return; + } + + const auto localCallContainer = ablityContext->GetLocalCallContainer(); + if (!localCallContainer) { + APP_LOGI("current ability context locall call container is nullptr."); + return; + } + + localCallContainer->DumpCalls(info); + APP_LOGI("localCallContainer need to get calls info."); } sptr AbilityThread::CallRequest() { - APP_LOGI("AbilityThread::CallRequest start"); + APP_LOGI("AbilityThread::CallRequest begin"); if (!currentAbility_) { APP_LOGI("ability is nullptr."); return nullptr; } - return currentAbility_->CallRequest(); + sptr retval = nullptr; + std::weak_ptr weakAbility = currentAbility_; + auto syncTask = [ability = weakAbility, &retval] () { + auto currentAbility = ability.lock(); + if (currentAbility == nullptr) { + APP_LOGE("ability is nullptr."); + return; + } + + APP_LOGD("AbilityThread::CallRequest syncTask CallRequest begin"); + retval = currentAbility->CallRequest(); + APP_LOGD("AbilityThread::CallRequest syncTask CallRequest end %{public}p", retval.GetRefPtr()); + }; + + if (abilityHandler_ == nullptr) { + APP_LOGE("ability Handler is nullptr."); + return nullptr; + } + + APP_LOGD("AbilityThread::CallRequest post sync task"); + + abilityHandler_->PostSyncTask(syncTask); + + APP_LOGI("AbilityThread::CallRequest end"); + return retval; } } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/src/continuation/distributed/continuation_manager.cpp b/frameworks/kits/ability/native/src/continuation/distributed/continuation_manager.cpp index cb26a3056faad3fca07eabb702b6b31b870e919a..92d95f336f54d4eb0808697cd104683c8b7cb16a 100644 --- a/frameworks/kits/ability/native/src/continuation/distributed/continuation_manager.cpp +++ b/frameworks/kits/ability/native/src/continuation/distributed/continuation_manager.cpp @@ -21,6 +21,7 @@ #include "app_log_wrapper.h" #include "continuation_handler.h" #include "distributed_client.h" +#include "distributed_objectstore.h" #include "operation_builder.h" #include "string_ex.h" #include "string_wrapper.h" @@ -162,6 +163,9 @@ int32_t ContinuationManager::OnContinueAndGetContent(WantParams &wantParams) APP_LOGE("OnContinue failed."); return CONTINUE_ON_CONTINUE_FAILED; } + auto abilityInfo = abilityInfo_.lock(); + std::string &bundleName = abilityInfo->bundleName; + ObjectStore::DistributedObjectStore::GetInstance(bundleName)->TriggerSync(); status = GetContentInfo(wantParams); if (!status) { diff --git a/frameworks/kits/ability/native/src/data_ability_helper.cpp b/frameworks/kits/ability/native/src/data_ability_helper.cpp index 7b1bf5fc64695d39a62a211c15b99127db8b17b8..278b7460741c0c28668e42f4f3ad61389cc391db 100644 --- a/frameworks/kits/ability/native/src/data_ability_helper.cpp +++ b/frameworks/kits/ability/native/src/data_ability_helper.cpp @@ -359,7 +359,6 @@ std::shared_ptr DataAbilityHelper::Creator( bool DataAbilityHelper::Release() { APP_LOGI("DataAbilityHelper::Release start."); - std::lock_guard guard(lock_); if (uri_ == nullptr) { APP_LOGE("DataAbilityHelper::Release failed, uri_ is nullptr"); return false; @@ -371,7 +370,9 @@ bool DataAbilityHelper::Release() APP_LOGE("DataAbilityHelper::Release failed to ReleaseDataAbility err = %{public}d", err); return false; } + APP_LOGI("DataAbilityHelper::Release after ReleaseDataAbility."); + std::lock_guard guard(lock_); dataAbilityProxy_ = nullptr; uri_.reset(); APP_LOGI("DataAbilityHelper::Release end."); @@ -389,37 +390,36 @@ bool DataAbilityHelper::Release() std::vector DataAbilityHelper::GetFileTypes(Uri &uri, const std::string &mimeTypeFilter) { APP_LOGI("DataAbilityHelper::GetFileTypes start."); - std::lock_guard guard(lock_); std::vector matchedMIMEs; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return matchedMIMEs; } + sptr dataAbilityProxy = dataAbilityProxy_; if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::GetFileTypes before AcquireDataAbility."); - dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + dataAbilityProxy = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); APP_LOGI("DataAbilityHelper::GetFileTypes after AcquireDataAbility."); - if (dataAbilityProxy_ == nullptr) { + if (dataAbilityProxy == nullptr) { APP_LOGE("DataAbilityHelper::GetFileTypes failed dataAbility == nullptr"); return matchedMIMEs; } if (isSystemCaller_) { - AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); + AddDataAbilityDeathRecipient(dataAbilityProxy->AsObject()); } } - APP_LOGI("DataAbilityHelper::GetFileTypes before dataAbilityProxy_->GetFileTypes."); - matchedMIMEs = dataAbilityProxy_->GetFileTypes(uri, mimeTypeFilter); - APP_LOGI("DataAbilityHelper::GetFileTypes after dataAbilityProxy_->GetFileTypes."); + APP_LOGI("DataAbilityHelper::GetFileTypes before dataAbilityProxy->GetFileTypes."); + matchedMIMEs = dataAbilityProxy->GetFileTypes(uri, mimeTypeFilter); + APP_LOGI("DataAbilityHelper::GetFileTypes after dataAbilityProxy->GetFileTypes."); if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::GetFileTypes before ReleaseDataAbility."); - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); APP_LOGI("DataAbilityHelper::GetFileTypes after ReleaseDataAbility."); if (err != ERR_OK) { APP_LOGE("DataAbilityHelper::GetFileTypes failed to ReleaseDataAbility err = %{public}d", err); } - dataAbilityProxy_ = nullptr; } APP_LOGI("DataAbilityHelper::GetFileTypes end."); @@ -440,37 +440,36 @@ std::vector DataAbilityHelper::GetFileTypes(Uri &uri, const std::st int DataAbilityHelper::OpenFile(Uri &uri, const std::string &mode) { APP_LOGI("DataAbilityHelper::OpenFile start."); - std::lock_guard guard(lock_); int fd = -1; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return fd; } + sptr dataAbilityProxy = dataAbilityProxy_; if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::OpenFile before AcquireDataAbility."); - dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + dataAbilityProxy = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); APP_LOGI("DataAbilityHelper::OpenFile after AcquireDataAbility."); - if (dataAbilityProxy_ == nullptr) { + if (dataAbilityProxy == nullptr) { APP_LOGE("DataAbilityHelper::OpenFile failed dataAbility == nullptr"); return fd; } if (isSystemCaller_) { - AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); + AddDataAbilityDeathRecipient(dataAbilityProxy->AsObject()); } } - APP_LOGI("DataAbilityHelper::OpenFile before dataAbilityProxy_->OpenFile."); - fd = dataAbilityProxy_->OpenFile(uri, mode); - APP_LOGI("DataAbilityHelper::OpenFile after dataAbilityProxy_->OpenFile."); + APP_LOGI("DataAbilityHelper::OpenFile before dataAbilityProxy->OpenFile."); + fd = dataAbilityProxy->OpenFile(uri, mode); + APP_LOGI("DataAbilityHelper::OpenFile after dataAbilityProxy->OpenFile."); if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::OpenFile before ReleaseDataAbility."); - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); APP_LOGI("DataAbilityHelper::OpenFile after ReleaseDataAbility."); if (err != ERR_OK) { APP_LOGE("DataAbilityHelper::OpenFile failed to ReleaseDataAbility err = %{public}d", err); } - dataAbilityProxy_ = nullptr; } APP_LOGI("DataAbilityHelper::OpenFile end."); return fd; @@ -491,36 +490,35 @@ int DataAbilityHelper::OpenFile(Uri &uri, const std::string &mode) int DataAbilityHelper::OpenRawFile(Uri &uri, const std::string &mode) { APP_LOGI("DataAbilityHelper::OpenRawFile start."); - std::lock_guard guard(lock_); int fd = -1; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return fd; } + sptr dataAbilityProxy = dataAbilityProxy_; if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::OpenRawFile before AcquireDataAbility."); - dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + dataAbilityProxy = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); APP_LOGI("DataAbilityHelper::OpenRawFile after AcquireDataAbility."); - if (dataAbilityProxy_ == nullptr) { + if (dataAbilityProxy == nullptr) { APP_LOGE("DataAbilityHelper::OpenRawFile failed dataAbility == nullptr"); return fd; } if (isSystemCaller_) { - AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); + AddDataAbilityDeathRecipient(dataAbilityProxy->AsObject()); } } - APP_LOGI("DataAbilityHelper::OpenRawFile before dataAbilityProxy_->OpenRawFile."); - fd = dataAbilityProxy_->OpenRawFile(uri, mode); - APP_LOGI("DataAbilityHelper::OpenRawFile after dataAbilityProxy_->OpenRawFile."); + APP_LOGI("DataAbilityHelper::OpenRawFile before dataAbilityProxy->OpenRawFile."); + fd = dataAbilityProxy->OpenRawFile(uri, mode); + APP_LOGI("DataAbilityHelper::OpenRawFile after dataAbilityProxy->OpenRawFile."); if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::OpenRawFile before ReleaseDataAbility."); - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); APP_LOGI("DataAbilityHelper::OpenRawFile after ReleaseDataAbility."); if (err != ERR_OK) { APP_LOGE("DataAbilityHelper::OpenRawFile failed to ReleaseDataAbility err = %{public}d", err); } - dataAbilityProxy_ = nullptr; } APP_LOGI("DataAbilityHelper::OpenRawFile end."); return fd; @@ -537,36 +535,35 @@ int DataAbilityHelper::OpenRawFile(Uri &uri, const std::string &mode) int DataAbilityHelper::Insert(Uri &uri, const NativeRdb::ValuesBucket &value) { APP_LOGI("DataAbilityHelper::Insert start."); - std::lock_guard guard(lock_); int index = -1; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return index; } + sptr dataAbilityProxy = dataAbilityProxy_; if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::Insert before AcquireDataAbility."); - dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + dataAbilityProxy = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); APP_LOGI("DataAbilityHelper::Insert after AcquireDataAbility."); - if (dataAbilityProxy_ == nullptr) { + if (dataAbilityProxy == nullptr) { APP_LOGE("DataAbilityHelper::Insert failed dataAbility == nullptr"); return index; } if (isSystemCaller_) { - AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); + AddDataAbilityDeathRecipient(dataAbilityProxy->AsObject()); } } - APP_LOGI("DataAbilityHelper::Insert before dataAbilityProxy_->Insert."); - index = dataAbilityProxy_->Insert(uri, value); - APP_LOGI("DataAbilityHelper::Insert after dataAbilityProxy_->Insert."); + APP_LOGI("DataAbilityHelper::Insert before dataAbilityProxy->Insert."); + index = dataAbilityProxy->Insert(uri, value); + APP_LOGI("DataAbilityHelper::Insert after dataAbilityProxy->Insert."); if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::Insert before ReleaseDataAbility."); - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); APP_LOGI("DataAbilityHelper::Insert after ReleaseDataAbility."); if (err != ERR_OK) { APP_LOGE("DataAbilityHelper::Insert failed to ReleaseDataAbility err = %{public}d", err); } - dataAbilityProxy_ = nullptr; } APP_LOGI("DataAbilityHelper::Insert end."); return index; @@ -585,36 +582,35 @@ int DataAbilityHelper::Update( Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("DataAbilityHelper::Update start."); - std::lock_guard guard(lock_); int index = -1; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return index; } + sptr dataAbilityProxy = dataAbilityProxy_; if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::Update before AcquireDataAbility."); - dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + dataAbilityProxy = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); APP_LOGI("DataAbilityHelper::Update after AcquireDataAbility."); - if (dataAbilityProxy_ == nullptr) { + if (dataAbilityProxy == nullptr) { APP_LOGE("DataAbilityHelper::Update failed dataAbility == nullptr"); return index; } if (isSystemCaller_) { - AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); + AddDataAbilityDeathRecipient(dataAbilityProxy->AsObject()); } } - APP_LOGI("DataAbilityHelper::Update before dataAbilityProxy_->Update."); - index = dataAbilityProxy_->Update(uri, value, predicates); - APP_LOGI("DataAbilityHelper::Update after dataAbilityProxy_->Update."); + APP_LOGI("DataAbilityHelper::Update before dataAbilityProxy->Update."); + index = dataAbilityProxy->Update(uri, value, predicates); + APP_LOGI("DataAbilityHelper::Update after dataAbilityProxy->Update."); if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::Update before ReleaseDataAbility."); - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); APP_LOGI("DataAbilityHelper::Update after ReleaseDataAbility."); if (err != ERR_OK) { APP_LOGE("DataAbilityHelper::Update failed to ReleaseDataAbility err = %{public}d", err); } - dataAbilityProxy_ = nullptr; } APP_LOGI("DataAbilityHelper::Update end."); return index; @@ -631,36 +627,35 @@ int DataAbilityHelper::Update( int DataAbilityHelper::Delete(Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("DataAbilityHelper::Delete start."); - std::lock_guard guard(lock_); int index = -1; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return index; } + sptr dataAbilityProxy = dataAbilityProxy_; if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::Delete before AcquireDataAbility."); - dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + dataAbilityProxy = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); APP_LOGI("DataAbilityHelper::Delete after AcquireDataAbility."); - if (dataAbilityProxy_ == nullptr) { + if (dataAbilityProxy == nullptr) { APP_LOGE("DataAbilityHelper::Delete failed dataAbility == nullptr"); return index; } if (isSystemCaller_) { - AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); + AddDataAbilityDeathRecipient(dataAbilityProxy->AsObject()); } } - APP_LOGI("DataAbilityHelper::Delete before dataAbilityProxy_->Delete."); - index = dataAbilityProxy_->Delete(uri, predicates); - APP_LOGI("DataAbilityHelper::Delete after dataAbilityProxy_->Delete."); + APP_LOGI("DataAbilityHelper::Delete before dataAbilityProxy->Delete."); + index = dataAbilityProxy->Delete(uri, predicates); + APP_LOGI("DataAbilityHelper::Delete after dataAbilityProxy->Delete."); if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::Delete before ReleaseDataAbility."); - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); APP_LOGI("DataAbilityHelper::Delete after ReleaseDataAbility."); if (err != ERR_OK) { APP_LOGE("DataAbilityHelper::Delete failed to ReleaseDataAbility err = %{public}d", err); } - dataAbilityProxy_ = nullptr; } APP_LOGI("DataAbilityHelper::Delete end."); return index; @@ -679,7 +674,6 @@ std::shared_ptr DataAbilityHelper::Query( Uri &uri, std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("DataAbilityHelper::Query start."); - std::lock_guard guard(lock_); std::shared_ptr resultset = nullptr; if (!CheckUriParam(uri)) { @@ -687,29 +681,29 @@ std::shared_ptr DataAbilityHelper::Query( return resultset; } + sptr dataAbilityProxy = dataAbilityProxy_; if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::Query before AcquireDataAbility."); - dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + dataAbilityProxy = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); APP_LOGI("DataAbilityHelper::Query after AcquireDataAbility."); - if (dataAbilityProxy_ == nullptr) { + if (dataAbilityProxy == nullptr) { APP_LOGE("DataAbilityHelper::Query failed dataAbility == nullptr"); return resultset; } if (isSystemCaller_) { - AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); + AddDataAbilityDeathRecipient(dataAbilityProxy->AsObject()); } } - APP_LOGI("DataAbilityHelper::Query before dataAbilityProxy_->Query."); - resultset = dataAbilityProxy_->Query(uri, columns, predicates); - APP_LOGI("DataAbilityHelper::Query after dataAbilityProxy_->Query."); + APP_LOGI("DataAbilityHelper::Query before dataAbilityProxy->Query."); + resultset = dataAbilityProxy->Query(uri, columns, predicates); + APP_LOGI("DataAbilityHelper::Query after dataAbilityProxy->Query."); if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::Query before ReleaseDataAbility."); - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); APP_LOGI("DataAbilityHelper::Query after ReleaseDataAbility."); if (err != ERR_OK) { APP_LOGE("DataAbilityHelper::Query failed to ReleaseDataAbility err = %{public}d", err); } - dataAbilityProxy_ = nullptr; } APP_LOGI("DataAbilityHelper::Query end."); return resultset; @@ -726,36 +720,35 @@ std::shared_ptr DataAbilityHelper::Query( std::string DataAbilityHelper::GetType(Uri &uri) { APP_LOGI("DataAbilityHelper::GetType start."); - std::lock_guard guard(lock_); std::string type; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return type; } + sptr dataAbilityProxy = dataAbilityProxy_; if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::GetType before AcquireDataAbility."); - dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + dataAbilityProxy = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); APP_LOGI("DataAbilityHelper::GetType after AcquireDataAbility."); - if (dataAbilityProxy_ == nullptr) { + if (dataAbilityProxy == nullptr) { APP_LOGE("DataAbilityHelper::GetType failed dataAbility == nullptr"); return type; } if (isSystemCaller_) { - AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); + AddDataAbilityDeathRecipient(dataAbilityProxy->AsObject()); } } - APP_LOGI("DataAbilityHelper::GetType before dataAbilityProxy_->GetType."); - type = dataAbilityProxy_->GetType(uri); - APP_LOGI("DataAbilityHelper::GetType after dataAbilityProxy_->GetType."); + APP_LOGI("DataAbilityHelper::GetType before dataAbilityProxy->GetType."); + type = dataAbilityProxy->GetType(uri); + APP_LOGI("DataAbilityHelper::GetType after dataAbilityProxy->GetType."); if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::GetType before ReleaseDataAbility."); - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); APP_LOGI("DataAbilityHelper::GetType after ReleaseDataAbility."); if (err != ERR_OK) { APP_LOGE("DataAbilityHelper::GetType failed to ReleaseDataAbility err = %{public}d", err); } - dataAbilityProxy_ = nullptr; } APP_LOGI("DataAbilityHelper::GetType end."); return type; @@ -774,36 +767,35 @@ std::string DataAbilityHelper::GetType(Uri &uri) bool DataAbilityHelper::Reload(Uri &uri, const PacMap &extras) { APP_LOGI("DataAbilityHelper::Reload start."); - std::lock_guard guard(lock_); bool ret = false; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return ret; } + sptr dataAbilityProxy = dataAbilityProxy_; if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::Reload before AcquireDataAbility."); - dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + dataAbilityProxy = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); APP_LOGI("DataAbilityHelper::Reload after AcquireDataAbility."); - if (dataAbilityProxy_ == nullptr) { + if (dataAbilityProxy == nullptr) { APP_LOGE("DataAbilityHelper::Reload failed dataAbility == nullptr"); return ret; } if (isSystemCaller_) { - AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); + AddDataAbilityDeathRecipient(dataAbilityProxy->AsObject()); } } - APP_LOGI("DataAbilityHelper::Reload before dataAbilityProxy_->Reload."); - ret = dataAbilityProxy_->Reload(uri, extras); - APP_LOGI("DataAbilityHelper::Reload after dataAbilityProxy_->Reload."); + APP_LOGI("DataAbilityHelper::Reload before dataAbilityProxy->Reload."); + ret = dataAbilityProxy->Reload(uri, extras); + APP_LOGI("DataAbilityHelper::Reload after dataAbilityProxy->Reload."); if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::Reload before ReleaseDataAbility."); - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); APP_LOGI("DataAbilityHelper::Reload after ReleaseDataAbility."); if (err != ERR_OK) { APP_LOGE("DataAbilityHelper::Reload failed to ReleaseDataAbility err = %{public}d", err); } - dataAbilityProxy_ = nullptr; } APP_LOGI("DataAbilityHelper::Reload end."); return ret; @@ -820,36 +812,35 @@ bool DataAbilityHelper::Reload(Uri &uri, const PacMap &extras) int DataAbilityHelper::BatchInsert(Uri &uri, const std::vector &values) { APP_LOGI("DataAbilityHelper::BatchInsert start."); - std::lock_guard guard(lock_); int ret = -1; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return ret; } + sptr dataAbilityProxy = dataAbilityProxy_; if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::BatchInsert before AcquireDataAbility."); - dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + dataAbilityProxy = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); APP_LOGI("DataAbilityHelper::BatchInsert after AcquireDataAbility."); - if (dataAbilityProxy_ == nullptr) { + if (dataAbilityProxy == nullptr) { APP_LOGE("DataAbilityHelper::BatchInsert failed dataAbility == nullptr"); return ret; } if (isSystemCaller_) { - AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); + AddDataAbilityDeathRecipient(dataAbilityProxy->AsObject()); } } - APP_LOGI("DataAbilityHelper::BatchInsert before dataAbilityProxy_->BatchInsert."); - ret = dataAbilityProxy_->BatchInsert(uri, values); - APP_LOGI("DataAbilityHelper::BatchInsert after dataAbilityProxy_->BatchInsert."); + APP_LOGI("DataAbilityHelper::BatchInsert before dataAbilityProxy->BatchInsert."); + ret = dataAbilityProxy->BatchInsert(uri, values); + APP_LOGI("DataAbilityHelper::BatchInsert after dataAbilityProxy->BatchInsert."); if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::BatchInsert before ReleaseDataAbility."); - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); APP_LOGI("DataAbilityHelper::BatchInsert after ReleaseDataAbility."); if (err != ERR_OK) { APP_LOGE("DataAbilityHelper::BatchInsert failed to ReleaseDataAbility err = %{public}d", err); } - dataAbilityProxy_ = nullptr; } APP_LOGI("DataAbilityHelper::BatchInsert end."); return ret; @@ -864,9 +855,10 @@ bool DataAbilityHelper::CheckUriParam(const Uri &uri) return false; } - if (uri_ != nullptr) { - if (!CheckOhosUri(*uri_)) { - APP_LOGE("DataAbilityHelper::CheckUriParam failed. CheckOhosUri uri_ failed"); + auto uriSp = uri_; // do not directly use uri_ here, otherwise, it will crash. + if (uriSp != nullptr) { + if (!CheckOhosUri(*uriSp)) { + APP_LOGE("DataAbilityHelper::CheckUriParam failed. CheckOhosUri uriSp failed"); return false; } @@ -874,10 +866,10 @@ bool DataAbilityHelper::CheckUriParam(const Uri &uri) checkUri.GetPathSegments(checkSegments); std::vector segments; - uri_->GetPathSegments(segments); + uriSp->GetPathSegments(segments); - if (checkSegments[0] != segments[0]) { - APP_LOGE("DataAbilityHelper::CheckUriParam failed. the dataability in uri doesn't equal the one in uri_."); + if (checkSegments.empty() || segments.empty() || checkSegments[0] != segments[0]) { + APP_LOGE("DataAbilityHelper::CheckUriParam failed. the dataability in uri doesn't equal the one in uriSp."); return false; } } @@ -1032,22 +1024,22 @@ void DataAbilityHelper::NotifyChange(const Uri &uri) return; } - if (dataAbilityProxy_ == nullptr) { - dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); - if (dataAbilityProxy_ == nullptr) { + sptr dataAbilityProxy = dataAbilityProxy_; + if (dataAbilityProxy == nullptr) { + dataAbilityProxy = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + if (dataAbilityProxy == nullptr) { APP_LOGE("DataAbilityHelper::NotifyChange failed dataAbility == nullptr"); return; } } - dataAbilityProxy_->ScheduleNotifyChange(uri); + dataAbilityProxy->ScheduleNotifyChange(uri); if (uri_ == nullptr) { - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); if (err != ERR_OK) { APP_LOGE("DataAbilityHelper::NotifyChange failed to ReleaseDataAbility err = %{public}d", err); } - dataAbilityProxy_ = nullptr; } APP_LOGI("DataAbilityHelper::NotifyChange end."); } @@ -1067,36 +1059,35 @@ void DataAbilityHelper::NotifyChange(const Uri &uri) Uri DataAbilityHelper::NormalizeUri(Uri &uri) { APP_LOGI("DataAbilityHelper::NormalizeUri start."); - std::lock_guard guard(lock_); Uri urivalue(""); if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return urivalue; } + sptr dataAbilityProxy = dataAbilityProxy_; if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::NormalizeUri before AcquireDataAbility."); - dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + dataAbilityProxy = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); APP_LOGI("DataAbilityHelper::NormalizeUri after AcquireDataAbility."); - if (dataAbilityProxy_ == nullptr) { + if (dataAbilityProxy == nullptr) { APP_LOGE("DataAbilityHelper::NormalizeUri failed dataAbility == nullptr"); return urivalue; } if (isSystemCaller_) { - AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); + AddDataAbilityDeathRecipient(dataAbilityProxy->AsObject()); } } - APP_LOGI("DataAbilityHelper::NormalizeUri before dataAbilityProxy_->NormalizeUri."); - urivalue = dataAbilityProxy_->NormalizeUri(uri); - APP_LOGI("DataAbilityHelper::NormalizeUri after dataAbilityProxy_->NormalizeUri."); + APP_LOGI("DataAbilityHelper::NormalizeUri before dataAbilityProxy->NormalizeUri."); + urivalue = dataAbilityProxy->NormalizeUri(uri); + APP_LOGI("DataAbilityHelper::NormalizeUri after dataAbilityProxy->NormalizeUri."); if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::NormalizeUri before ReleaseDataAbility."); - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); APP_LOGI("DataAbilityHelper::NormalizeUri after ReleaseDataAbility."); if (err != ERR_OK) { APP_LOGE("DataAbilityHelper::NormalizeUri failed to ReleaseDataAbility err = %{public}d", err); } - dataAbilityProxy_ = nullptr; } APP_LOGI("DataAbilityHelper::NormalizeUri end."); return urivalue; @@ -1115,55 +1106,40 @@ Uri DataAbilityHelper::NormalizeUri(Uri &uri) Uri DataAbilityHelper::DenormalizeUri(Uri &uri) { APP_LOGI("DataAbilityHelper::DenormalizeUri start."); - std::lock_guard guard(lock_); Uri urivalue(""); if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return urivalue; } + sptr dataAbilityProxy = dataAbilityProxy_; if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::DenormalizeUri before AcquireDataAbility."); - dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + dataAbilityProxy = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); APP_LOGI("DataAbilityHelper::DenormalizeUri after AcquireDataAbility."); - if (dataAbilityProxy_ == nullptr) { + if (dataAbilityProxy == nullptr) { APP_LOGE("DataAbilityHelper::DenormalizeUri failed dataAbility == nullptr"); return urivalue; } if (isSystemCaller_) { - AddDataAbilityDeathRecipient(dataAbilityProxy_->AsObject()); + AddDataAbilityDeathRecipient(dataAbilityProxy->AsObject()); } } - APP_LOGI("DataAbilityHelper::DenormalizeUri before dataAbilityProxy_->DenormalizeUri."); - urivalue = dataAbilityProxy_->DenormalizeUri(uri); - APP_LOGI("DataAbilityHelper::DenormalizeUri after dataAbilityProxy_->DenormalizeUri."); + APP_LOGI("DataAbilityHelper::DenormalizeUri before dataAbilityProxy->DenormalizeUri."); + urivalue = dataAbilityProxy->DenormalizeUri(uri); + APP_LOGI("DataAbilityHelper::DenormalizeUri after dataAbilityProxy->DenormalizeUri."); if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::DenormalizeUri before ReleaseDataAbility."); - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); APP_LOGI("DataAbilityHelper::DenormalizeUri after ReleaseDataAbility."); if (err != ERR_OK) { APP_LOGE("DataAbilityHelper::DenormalizeUri failed to ReleaseDataAbility err = %{public}d", err); } - dataAbilityProxy_ = nullptr; } APP_LOGI("DataAbilityHelper::DenormalizeUri end."); return urivalue; } -void DataAbilityDeathRecipient::OnRemoteDied(const wptr &remote) -{ - APP_LOGI("recv DataAbilityDeathRecipient death notice"); - if (handler_) { - handler_(remote); - } - APP_LOGI("DataAbilityHelper::OnRemoteDied end."); -} - -DataAbilityDeathRecipient::DataAbilityDeathRecipient(RemoteDiedHandler handler) : handler_(handler) -{} - -DataAbilityDeathRecipient::~DataAbilityDeathRecipient() -{} std::vector> DataAbilityHelper::ExecuteBatch( const Uri &uri, const std::vector> &operations) { @@ -1173,30 +1149,46 @@ std::vector> DataAbilityHelper::ExecuteBatch( APP_LOGE("DataAbilityHelper::ExecuteBatch. CheckUriParam uri failed"); return results; } + + sptr dataAbilityProxy = dataAbilityProxy_; if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::ExecuteBatch before AcquireDataAbility."); - dataAbilityProxy_ = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); + dataAbilityProxy = AbilityManagerClient::GetInstance()->AcquireDataAbility(uri, tryBind_, token_); APP_LOGI("DataAbilityHelper::ExecuteBatch after AcquireDataAbility."); - if (dataAbilityProxy_ == nullptr) { + if (dataAbilityProxy == nullptr) { APP_LOGE("DataAbilityHelper::ExecuteBatch failed dataAbility == nullptr"); return results; } } - APP_LOGI("DataAbilityHelper::ExecuteBatch before dataAbilityProxy_->ExecuteBatch."); - results = dataAbilityProxy_->ExecuteBatch(operations); - APP_LOGI("DataAbilityHelper::ExecuteBatch after dataAbilityProxy_->ExecuteBatch."); + APP_LOGI("DataAbilityHelper::ExecuteBatch before dataAbilityProxy->ExecuteBatch."); + results = dataAbilityProxy->ExecuteBatch(operations); + APP_LOGI("DataAbilityHelper::ExecuteBatch after dataAbilityProxy->ExecuteBatch."); if (uri_ == nullptr) { APP_LOGI("DataAbilityHelper::ExecuteBatch before ReleaseDataAbility."); - int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy_, token_); + int err = AbilityManagerClient::GetInstance()->ReleaseDataAbility(dataAbilityProxy, token_); APP_LOGI("DataAbilityHelper::ExecuteBatch after ReleaseDataAbility."); if (err != ERR_OK) { APP_LOGE("DataAbilityHelper::ExecuteBatch failed to ReleaseDataAbility err = %{public}d", err); } - dataAbilityProxy_ = nullptr; } APP_LOGI("DataAbilityHelper::ExecuteBatch end"); return results; } + +void DataAbilityDeathRecipient::OnRemoteDied(const wptr &remote) +{ + APP_LOGI("recv DataAbilityDeathRecipient death notice"); + if (handler_) { + handler_(remote); + } + APP_LOGI("DataAbilityHelper::OnRemoteDied end."); +} + +DataAbilityDeathRecipient::DataAbilityDeathRecipient(RemoteDiedHandler handler) : handler_(handler) +{} + +DataAbilityDeathRecipient::~DataAbilityDeathRecipient() +{} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/data_ability_operation.cpp b/frameworks/kits/ability/native/src/data_ability_operation.cpp index c37ba314767e265fa9d6576eb22f820cad2e8e47..ee0a0a9c3cc36e3fd74e59eeafc78be7a3e7a158 100644 --- a/frameworks/kits/ability/native/src/data_ability_operation.cpp +++ b/frameworks/kits/ability/native/src/data_ability_operation.cpp @@ -411,7 +411,8 @@ bool DataAbilityOperation::ReadFromParcel(Parcel &in) APP_LOGE("DataAbilityOperation::ReadFromParcel ReadInt32(empty) error"); return false; } - APP_LOGD("DataAbilityOperation::ReadFromParcel empty is %{public}s", empty == VALUE_OBJECT ? "VALUE_OBJECT" : "VALUE_NULL"); + APP_LOGD("DataAbilityOperation::ReadFromParcel empty is %{public}s", + empty == VALUE_OBJECT ? "VALUE_OBJECT" : "VALUE_NULL"); if (empty == VALUE_OBJECT) { valuesBucket_.reset(in.ReadParcelable()); } else { @@ -423,7 +424,8 @@ bool DataAbilityOperation::ReadFromParcel(Parcel &in) APP_LOGE("DataAbilityOperation::ReadFromParcel ReadInt32(empty) error"); return false; } - APP_LOGD("DataAbilityOperation::ReadFromParcel empty is %{public}s", empty == VALUE_OBJECT ? "VALUE_OBJECT" : "VALUE_NULL"); + APP_LOGD("DataAbilityOperation::ReadFromParcel empty is %{public}s", + empty == VALUE_OBJECT ? "VALUE_OBJECT" : "VALUE_NULL"); if (empty == VALUE_OBJECT) { dataAbilityPredicates_.reset(in.ReadParcelable()); } else { diff --git a/frameworks/kits/ability/native/src/data_ability_operation_builder.cpp b/frameworks/kits/ability/native/src/data_ability_operation_builder.cpp index b47589dea0bf1bbe55211863b86f80c52b5f4e53..87b888478719b62e14a0f97be0686ebb395bbe7d 100644 --- a/frameworks/kits/ability/native/src/data_ability_operation_builder.cpp +++ b/frameworks/kits/ability/native/src/data_ability_operation_builder.cpp @@ -146,4 +146,4 @@ std::shared_ptr DataAbilityOperationBuilder::WithIn return shared_from_this(); } } // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/data_ability_result.cpp b/frameworks/kits/ability/native/src/data_ability_result.cpp index 8cec2c33d7bb21ea02cb11c9646e85d894ec1979..d963656911be900c224d33822f0aee03a9107dd0 100644 --- a/frameworks/kits/ability/native/src/data_ability_result.cpp +++ b/frameworks/kits/ability/native/src/data_ability_result.cpp @@ -16,7 +16,6 @@ #include "data_ability_result.h" #include -#include #include "parcel_macro.h" diff --git a/frameworks/kits/ability/native/src/datashare_helper.cpp b/frameworks/kits/ability/native/src/datashare_helper.cpp index db011ced34f4b0abab034ba8c220b3f4672e2258..5635726b05fea9b0226d738be5b13e677884aece 100644 --- a/frameworks/kits/ability/native/src/datashare_helper.cpp +++ b/frameworks/kits/ability/native/src/datashare_helper.cpp @@ -30,6 +30,7 @@ namespace OHOS { namespace AppExecFwk { namespace { const std::string SCHEME_DATASHARE = "datashare"; +constexpr int INVALID_VALUE = -1; } // namespace std::mutex DataShareHelper::oplock_; @@ -91,7 +92,6 @@ void DataShareHelper::AddDataShareDeathRecipient(const sptr &toke 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; @@ -147,19 +147,19 @@ std::shared_ptr DataShareHelper::Creator( 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."); + APP_LOGI("DataShareHelper::Creator with context, want and uri called start."); if (context == nullptr) { - APP_LOGE("DataShareHelper::Creator (context, uri) failed, context == nullptr"); + APP_LOGE("DataShareHelper::Creator failed, context == nullptr"); return nullptr; } if (uri == nullptr) { - APP_LOGE("DataShareHelper::Creator (context, uri) failed, uri == nullptr"); + APP_LOGE("DataShareHelper::Creator 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", + APP_LOGE("DataShareHelper::Creator failed, the Scheme is not datashare, Scheme: %{public}s", uri->GetScheme().c_str()); return nullptr; } @@ -179,11 +179,11 @@ std::shared_ptr DataShareHelper::Creator( DataShareHelper *ptrDataShareHelper = new (std::nothrow) DataShareHelper(context, want, uri, dataShareProxy); if (ptrDataShareHelper == nullptr) { - APP_LOGE("DataShareHelper::Creator (context, uri) failed, create DataShareHelper failed"); + APP_LOGE("DataShareHelper::Creator failed, create DataShareHelper failed"); return nullptr; } - APP_LOGI("DataShareHelper::Creator with context uri called end."); + APP_LOGI("DataShareHelper::Creator with context, want and uri called end."); return std::shared_ptr(ptrDataShareHelper); } @@ -202,19 +202,19 @@ 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."); + APP_LOGI("DataShareHelper::Creator with runtime context, want and uri called start."); if (context == nullptr) { - APP_LOGE("DataShareHelper::Creator (context, uri) failed, context == nullptr"); + APP_LOGE("DataShareHelper::Creator failed, context == nullptr"); return nullptr; } if (uri == nullptr) { - APP_LOGE("DataShareHelper::Creator (context, uri) failed, uri == nullptr"); + APP_LOGE("DataShareHelper::Creator 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", + APP_LOGE("DataShareHelper::Creator failed, the Scheme is not datashare, Scheme: %{public}s", uri->GetScheme().c_str()); return nullptr; } @@ -234,11 +234,11 @@ std::shared_ptr DataShareHelper::Creator( DataShareHelper *ptrDataShareHelper = new (std::nothrow) DataShareHelper(context, want, uri, dataShareProxy); if (ptrDataShareHelper == nullptr) { - APP_LOGE("DataShareHelper::Creator (context, uri) failed, create DataShareHelper failed"); + APP_LOGE("DataShareHelper::Creator failed, create DataShareHelper failed"); return nullptr; } - APP_LOGI("DataShareHelper::Creator with context uri called end."); + APP_LOGI("DataShareHelper::Creator with runtime context, want and uri called end."); return std::shared_ptr(ptrDataShareHelper); } @@ -251,7 +251,6 @@ std::shared_ptr DataShareHelper::Creator( 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; @@ -279,7 +278,6 @@ bool DataShareHelper::Release() 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__); @@ -296,6 +294,8 @@ std::vector DataShareHelper::GetFileTypes(Uri &uri, const std::stri if (isSystemCaller_ && dataShareProxy_) { AddDataShareDeathRecipient(dataShareProxy_->AsObject()); } + } else { + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -333,8 +333,7 @@ std::vector DataShareHelper::GetFileTypes(Uri &uri, const std::stri int DataShareHelper::OpenFile(Uri &uri, const std::string &mode) { APP_LOGI("DataShareHelper::OpenFile start."); - std::lock_guard guard(lock_); - int fd = -1; + int fd = INVALID_VALUE; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return fd; @@ -350,6 +349,8 @@ int DataShareHelper::OpenFile(Uri &uri, const std::string &mode) if (isSystemCaller_ && dataShareProxy_) { AddDataShareDeathRecipient(dataShareProxy_->AsObject()); } + } else { + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -387,8 +388,7 @@ int DataShareHelper::OpenFile(Uri &uri, const std::string &mode) int DataShareHelper::OpenRawFile(Uri &uri, const std::string &mode) { APP_LOGI("DataShareHelper::OpenRawFile start."); - std::lock_guard guard(lock_); - int fd = -1; + int fd = INVALID_VALUE; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return fd; @@ -404,6 +404,8 @@ int DataShareHelper::OpenRawFile(Uri &uri, const std::string &mode) if (isSystemCaller_ && dataShareProxy_) { AddDataShareDeathRecipient(dataShareProxy_->AsObject()); } + } else { + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -437,8 +439,7 @@ int DataShareHelper::OpenRawFile(Uri &uri, const std::string &mode) int DataShareHelper::Insert(Uri &uri, const NativeRdb::ValuesBucket &value) { APP_LOGI("DataShareHelper::Insert start."); - std::lock_guard guard(lock_); - int index = -1; + int index = INVALID_VALUE; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return index; @@ -454,6 +455,8 @@ int DataShareHelper::Insert(Uri &uri, const NativeRdb::ValuesBucket &value) if (isSystemCaller_ && dataShareProxy_) { AddDataShareDeathRecipient(dataShareProxy_->AsObject()); } + } else { + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -489,8 +492,7 @@ 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; + int index = INVALID_VALUE; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return index; @@ -506,6 +508,8 @@ int DataShareHelper::Update( if (isSystemCaller_ && dataShareProxy_) { AddDataShareDeathRecipient(dataShareProxy_->AsObject()); } + } else { + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -539,8 +543,7 @@ int DataShareHelper::Update( int DataShareHelper::Delete(Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("DataShareHelper::Delete start."); - std::lock_guard guard(lock_); - int index = -1; + int index = INVALID_VALUE; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return index; @@ -556,6 +559,8 @@ int DataShareHelper::Delete(Uri &uri, const NativeRdb::DataAbilityPredicates &pr if (isSystemCaller_ && dataShareProxy_) { AddDataShareDeathRecipient(dataShareProxy_->AsObject()); } + } else { + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -591,7 +596,6 @@ 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)) { @@ -609,6 +613,8 @@ std::shared_ptr DataShareHelper::Query( if (isSystemCaller_ && dataShareProxy_) { AddDataShareDeathRecipient(dataShareProxy_->AsObject()); } + } else { + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -642,7 +648,6 @@ std::shared_ptr DataShareHelper::Query( 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__); @@ -659,6 +664,8 @@ std::string DataShareHelper::GetType(Uri &uri) if (isSystemCaller_ && dataShareProxy_) { AddDataShareDeathRecipient(dataShareProxy_->AsObject()); } + } else { + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -692,8 +699,7 @@ std::string DataShareHelper::GetType(Uri &uri) int DataShareHelper::BatchInsert(Uri &uri, const std::vector &values) { APP_LOGI("DataShareHelper::BatchInsert start."); - std::lock_guard guard(lock_); - int ret = -1; + int ret = INVALID_VALUE; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return ret; @@ -709,6 +715,8 @@ int DataShareHelper::BatchInsert(Uri &uri, const std::vectorAsObject()); } + } else { + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -914,6 +922,8 @@ void DataShareHelper::NotifyChange(const Uri &uri) dataShareConnection_->ConnectDataShareExtAbility(want_, token_); } dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); + } else { + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -947,7 +957,6 @@ void DataShareHelper::NotifyChange(const Uri &uri) 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__); @@ -964,6 +973,8 @@ Uri DataShareHelper::NormalizeUri(Uri &uri) if (isSystemCaller_ && dataShareProxy_) { AddDataShareDeathRecipient(dataShareProxy_->AsObject()); } + } else { + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -999,7 +1010,6 @@ Uri DataShareHelper::NormalizeUri(Uri &uri) 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__); @@ -1016,6 +1026,8 @@ Uri DataShareHelper::DenormalizeUri(Uri &uri) if (isSystemCaller_ && dataShareProxy_) { AddDataShareDeathRecipient(dataShareProxy_->AsObject()); } + } else { + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -1073,6 +1085,8 @@ std::vector> DataShareHelper::ExecuteBatch( APP_LOGE("DataShareHelper::ExecuteBatch failed dataShareProxy_ == nullptr"); return results; } + } else { + dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { diff --git a/frameworks/kits/ability/native/src/distributed_ability_runtime/distributed_client.cpp b/frameworks/kits/ability/native/src/distributed_ability_runtime/distributed_client.cpp index 5cf8c6277f5046c95ee42b2ac43c3de5b79ec91f..9255c711399672cfbddc0d885b9dfd8f81b52799 100644 --- a/frameworks/kits/ability/native/src/distributed_ability_runtime/distributed_client.cpp +++ b/frameworks/kits/ability/native/src/distributed_ability_runtime/distributed_client.cpp @@ -37,7 +37,7 @@ sptr DistributedClient::GetDmsProxy() } int32_t DistributedClient::StartRemoteAbility(const OHOS::AAFwk::Want& want, - int32_t callerUid, int32_t requestCode) + int32_t callerUid, int32_t requestCode, uint32_t accessToken) { HILOG_INFO("called"); sptr remote = GetDmsProxy(); @@ -51,12 +51,13 @@ int32_t DistributedClient::StartRemoteAbility(const OHOS::AAFwk::Want& want, PARCEL_WRITE_HELPER(data, Parcelable, &want); PARCEL_WRITE_HELPER(data, Int32, callerUid); PARCEL_WRITE_HELPER(data, Int32, requestCode); + PARCEL_WRITE_HELPER(data, Uint32, accessToken); MessageParcel reply; PARCEL_TRANSACT_SYNC_RET_INT(remote, START_REMOTE_ABILITY, data, reply); } -int32_t DistributedClient::ConnectRemoteAbility(const OHOS::AAFwk::Want& want, - const sptr& connect, int32_t callerUid, int32_t callerPid) +int32_t DistributedClient::ConnectRemoteAbility(const OHOS::AAFwk::Want& want, const sptr& connect, + int32_t callerUid, int32_t callerPid, uint32_t accessToken) { HILOG_INFO("called"); if (connect == nullptr) { @@ -77,6 +78,7 @@ int32_t DistributedClient::ConnectRemoteAbility(const OHOS::AAFwk::Want& want, PARCEL_WRITE_HELPER(data, RemoteObject, connect); PARCEL_WRITE_HELPER(data, Int32, callerUid); PARCEL_WRITE_HELPER(data, Int32, callerPid); + PARCEL_WRITE_HELPER(data, Uint32, accessToken); MessageParcel reply; PARCEL_TRANSACT_SYNC_RET_INT(remote, CONNECT_REMOTE_ABILITY, data, reply); } @@ -130,7 +132,7 @@ int32_t DistributedClient::ContinueMission(const std::string& srcDeviceId, const } int32_t DistributedClient::StartContinuation(const OHOS::AAFwk::Want& want, int32_t missionId, int32_t callerUid, - int32_t status) + int32_t status, uint32_t accessToken) { HILOG_INFO("called"); sptr remote = GetDmsProxy(); @@ -146,6 +148,7 @@ int32_t DistributedClient::StartContinuation(const OHOS::AAFwk::Want& want, int3 PARCEL_WRITE_HELPER(data, Int32, missionId); PARCEL_WRITE_HELPER(data, Int32, callerUid); PARCEL_WRITE_HELPER(data, Int32, status); + PARCEL_WRITE_HELPER(data, Uint32, accessToken); MessageParcel reply; PARCEL_TRANSACT_SYNC_RET_INT(remote, START_CONTINUATION, data, reply); } @@ -346,5 +349,59 @@ bool DistributedClient::ReadMissionInfosFromParcel(Parcel& parcel, HILOG_INFO("info size is:%{public}zu", missionInfos.size()); return true; } + +int32_t DistributedClient::StartRemoteAbilityByCall(const OHOS::AAFwk::Want& want, + const sptr& connect, int32_t callerUid, int32_t callerPid, uint32_t tokenCaller) +{ + HILOG_INFO("called"); + if (connect == nullptr) { + HILOG_ERROR("StartRemoteAbilityByCall connect is null"); + return ERR_NULL_OBJECT; + } + + sptr remote = GetDmsProxy(); + if (remote == nullptr) { + HILOG_ERROR("StartRemoteAbilityByCall remote is null"); + return ERR_NULL_OBJECT; + } + MessageParcel data; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + PARCEL_WRITE_HELPER(data, Parcelable, &want); + PARCEL_WRITE_HELPER(data, RemoteObject, connect); + PARCEL_WRITE_HELPER(data, Int32, callerUid); + PARCEL_WRITE_HELPER(data, Int32, callerPid); + PARCEL_WRITE_HELPER(data, Uint32, tokenCaller); + MessageParcel reply; + PARCEL_TRANSACT_SYNC_RET_INT(remote, START_REMOTE_ABILITY_BY_CALL, data, reply); +} + +int32_t DistributedClient::ReleaseRemoteAbility(const sptr& connect, + const AppExecFwk::ElementName &element) +{ + HILOG_INFO("called"); + if (connect == nullptr) { + HILOG_ERROR("ReleaseRemoteAbility connect is null"); + return ERR_NULL_OBJECT; + } + + sptr remote = GetDmsProxy(); + if (remote == nullptr) { + HILOG_ERROR("ReleaseRemoteAbility remote is null"); + return ERR_NULL_OBJECT; + } + MessageParcel data; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + PARCEL_WRITE_HELPER(data, RemoteObject, connect); + if (!data.WriteParcelable(&element)) { + HILOG_ERROR("ReleaseRemoteAbility write element error."); + return ERR_INVALID_VALUE; + } + MessageParcel reply; + PARCEL_TRANSACT_SYNC_RET_INT(remote, RELEASE_REMOTE_ABILITY, data, reply); +} } // namespace AAFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/src/extension.cpp b/frameworks/kits/ability/native/src/extension.cpp index 7f145ab36070a62b4698556a9ec40807bcada4ed..1ac123b3b61a89fb199d625078b25b8da2599d55 100644 --- a/frameworks/kits/ability/native/src/extension.cpp +++ b/frameworks/kits/ability/native/src/extension.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,8 +13,10 @@ * limitations under the License. */ -#include "ability_local_record.h" #include "extension.h" + +#include "ability_local_record.h" +#include "configuration.h" #include "extension_context.h" #include "hilog_wrapper.h" @@ -119,5 +121,15 @@ void Extension::SetLastRequestWant(const AAFwk::Want &want) { lastRequestWant_ = std::make_shared(want); } + +/** + * @brief Called when the system configuration is updated. + * + * @param configuration Indicates the updated configuration information. + */ +void Extension::OnConfigurationUpdated(const AppExecFwk::Configuration &configuration) +{ + HILOG_INFO("%{public}s called.", __func__); +} } } \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/extension_impl.cpp b/frameworks/kits/ability/native/src/extension_impl.cpp index 0286fddd1796667ee8d3d9a6ed1783a71bb15b6f..0fa2b171a9cb8132f0f2949bad4d408451718e2a 100644 --- a/frameworks/kits/ability/native/src/extension_impl.cpp +++ b/frameworks/kits/ability/native/src/extension_impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,11 +13,12 @@ * limitations under the License. */ +#include "extension_impl.h" + #include "ability_manager_client.h" #include "ability_local_record.h" #include "bytrace.h" #include "extension_context.h" -#include "extension_impl.h" #include "hilog_wrapper.h" namespace OHOS { @@ -94,6 +95,22 @@ void ExtensionImpl::HandleExtensionTransaction(const Want &want, HILOG_INFO("ExtensionImpl::HandleAbilityTransaction end"); } +void ExtensionImpl::ScheduleUpdateConfiguration(const AppExecFwk::Configuration &config) +{ + HILOG_INFO("%{public}s begin.", __func__); + + if (extension_ == nullptr) { + HILOG_ERROR("ExtensionImpl::ScheduleUpdateConfiguration extension_ is nullptr"); + return; + } + + if (lifecycleState_ != AAFwk::ABILITY_STATE_INITIAL) { + extension_->OnConfigurationUpdated(config); + } + + HILOG_INFO("%{public}s end.", __func__); +} + /** * @brief Toggles the lifecycle status of Extension to AAFwk::ABILITY_STATE_INACTIVE. And notifies the application * that it belongs to of the lifecycle status. diff --git a/frameworks/kits/ability/native/src/form_runtime/form_extension_provider_client.cpp b/frameworks/kits/ability/native/src/form_runtime/form_extension_provider_client.cpp index 1c0bb7f6b900d200026bf5a307a76272fb72b7dd..245874e930dd88815651f3c9727e313095387af7 100644 --- a/frameworks/kits/ability/native/src/form_runtime/form_extension_provider_client.cpp +++ b/frameworks/kits/ability/native/src/form_runtime/form_extension_provider_client.cpp @@ -15,7 +15,6 @@ #include "form_runtime/form_extension_provider_client.h" -#include #include "string_ex.h" #include "app_log_wrapper.h" 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 540c967dc0e2a99db2de80602c545c645bcf7b6b..0a97767f7f236815b33520d715212beadd80828e 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 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,17 +15,18 @@ #include "form_runtime/js_form_extension.h" -#include - #include "ability_info.h" #include "form_provider_data.h" #include "form_runtime/form_extension_provider_client.h" #include "form_runtime/js_form_extension_context.h" +#include "form_runtime/js_form_extension_util.h" #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/native_node_api.h" +#include "napi_common_configuration.h" #include "napi_common_util.h" #include "napi_common_want.h" @@ -83,10 +84,10 @@ void JsFormExtension::Init(const std::shared_ptr &record, } HILOG_INFO("JsFormExtension::Init CreateJsFormExtensionContext."); NativeValue* contextObj = CreateJsFormExtensionContext(engine, context); - auto shellContextRef = jsRuntime_.LoadSystemModule("application.FormExtensionContext", &contextObj, 1); - contextObj = shellContextRef->Get(); + shellContextRef_ = jsRuntime_.LoadSystemModule("application.FormExtensionContext", &contextObj, 1); + contextObj = shellContextRef_->Get(); HILOG_INFO("JsFormExtension::Init Bind."); - context->Bind(jsRuntime_, shellContextRef.release()); + context->Bind(jsRuntime_, shellContextRef_.get()); HILOG_INFO("JsFormExtension::SetProperty."); obj->SetProperty("context", contextObj); @@ -298,40 +299,22 @@ void JsFormExtension::GetSrcPath(std::string &srcPath) } } -bool JsFormExtension::UnwrapRawImageDataMap(NativeEngine& engine, NativeValue* argv, - std::map& rawImageDataMap) +void JsFormExtension::OnConfigurationUpdated(const AppExecFwk::Configuration& configuration) { + Extension::OnConfigurationUpdated(configuration); HILOG_INFO("%{public}s called.", __func__); - auto env = reinterpret_cast(&engine); - auto param = reinterpret_cast(argv); - if (!IsTypeForNapiValue(env, param, napi_object)) { - return false; - } + HandleScope handleScope(jsRuntime_); + auto& nativeEngine = jsRuntime_.GetNativeEngine(); - 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); - } + // Notify extension context + auto fullConfig = GetContext()->GetConfiguration(); + JsExtensionContext::ConfigurationUpdated(&nativeEngine, shellContextRef_, fullConfig); - return true; + napi_value napiConfiguration = OHOS::AppExecFwk::WrapConfiguration( + reinterpret_cast(&nativeEngine), *fullConfig); + NativeValue* jsConfiguration = reinterpret_cast(napiConfiguration); + CallObjectMethod("onConfigurationUpdated", &jsConfiguration, 1); } } // namespace AbilityRuntime -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/form_runtime/js_form_extension_context.cpp b/frameworks/kits/ability/native/src/form_runtime/js_form_extension_context.cpp index 6f786295b60e3fbf900b1c4cd80857672886e99e..5be896a6ba0c47a11ddc1ab0d7ea2c525b0e1528 100644 --- a/frameworks/kits/ability/native/src/form_runtime/js_form_extension_context.cpp +++ b/frameworks/kits/ability/native/src/form_runtime/js_form_extension_context.cpp @@ -18,21 +18,29 @@ #include #include +#include "form_runtime/js_form_extension_util.h" #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_start_options.h" #include "napi_common_want.h" #include "napi_remote_object.h" namespace OHOS { namespace AbilityRuntime { namespace { +constexpr int32_t INDEX_ZERO = 0; +constexpr int32_t INDEX_ONE = 1; +constexpr int32_t ERROR_CODE_ONE = 1; +constexpr size_t ARGC_ONE = 1; +constexpr size_t ARGC_TWO = 2; +constexpr size_t ARGC_THREE = 3; const int UPDATE_FORM_PARAMS_SIZE = 2; class JsFormExtensionContext final { public: - JsFormExtensionContext(const std::shared_ptr& context) : context_(context) {} + explicit JsFormExtensionContext(const std::shared_ptr& context) : context_(context) {} ~JsFormExtensionContext() = default; static void Finalizer(NativeEngine* engine, void* data, void* hint) @@ -46,6 +54,13 @@ public: JsFormExtensionContext* me = CheckParamsAndGetThis(engine, info); return (me != nullptr) ? me->OnUpdateForm(*engine, *info) : nullptr; } + + static NativeValue* StartAbility(NativeEngine* engine, NativeCallbackInfo* info) + { + JsFormExtensionContext* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnStartAbility(*engine, *info) : nullptr; + } + private: std::weak_ptr context_; @@ -62,17 +77,27 @@ private: AppExecFwk::FormProviderData formProviderData; std::string formDataStr = "{}"; + std::map rawImageDataMap; NativeObject* nativeObject = ConvertNativeValueTo(info.argv[1]); if (nativeObject != nullptr) { NativeValue* nativeDataValue = nativeObject->GetProperty("data"); if (nativeDataValue == nullptr || !ConvertFromJsValue(engine, nativeDataValue, formDataStr)) { HILOG_ERROR("%{public}s called. nativeDataValue is nullptr or ConvertFromJsValue failed", __func__); } + nativeDataValue = nativeObject->GetProperty("image"); + if (nativeDataValue != nullptr) { + UnwrapRawImageDataMap(engine, nativeDataValue, rawImageDataMap); + } } else { HILOG_ERROR("%{public}s called. nativeObject is nullptr", __func__); } formProviderData = AppExecFwk::FormProviderData(formDataStr); + HILOG_INFO("Image number is %{public}zu", rawImageDataMap.size()); + for (auto entry : rawImageDataMap) { + formProviderData.AddImageData(entry.first, entry.second); + } + AsyncTask::CompleteCallback complete = [weak = context_, formId, formProviderData](NativeEngine& engine, AsyncTask& task, int32_t status) { auto context = weak.lock(); @@ -96,6 +121,60 @@ private: engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); return result; } + + NativeValue* OnStartAbility(NativeEngine& engine, NativeCallbackInfo& info) + { + HILOG_INFO("OnStartAbility is called"); + // only support one or two or three params + if (info.argc != ARGC_ONE && info.argc != ARGC_TWO && info.argc != ARGC_THREE) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + + decltype(info.argc) unwrapArgc = 0; + AAFwk::Want want; + OHOS::AppExecFwk::UnwrapWant(reinterpret_cast(&engine), + reinterpret_cast(info.argv[INDEX_ZERO]), want); + HILOG_INFO("%{public}s bundlename:%{public}s abilityname:%{public}s", + __func__, + want.GetBundle().c_str(), + want.GetElement().GetAbilityName().c_str()); + unwrapArgc++; + + AAFwk::StartOptions startOptions; + if (info.argc > ARGC_ONE && info.argv[INDEX_ONE]->TypeOf() == NATIVE_OBJECT) { + HILOG_INFO("OnStartAbility start options is used."); + AppExecFwk::UnwrapStartOptions(reinterpret_cast(&engine), + reinterpret_cast(info.argv[INDEX_ONE]), startOptions); + unwrapArgc++; + } + + AsyncTask::CompleteCallback complete = + [weak = context_, want, startOptions, unwrapArgc](NativeEngine& engine, AsyncTask& task, int32_t status) { + HILOG_INFO("startAbility begin"); + auto context = weak.lock(); + if (!context) { + HILOG_WARN("context is released"); + task.Reject(engine, CreateJsError(engine, ERROR_CODE_ONE, "Context is released")); + return; + } + + ErrCode errcode = ERR_OK; + (unwrapArgc == 1) ? errcode = context->StartAbility(want) : + errcode = context->StartAbility(want, startOptions); + if (errcode == 0) { + task.Resolve(engine, engine.CreateUndefined()); + } else { + task.Reject(engine, CreateJsError(engine, errcode, "Start Ability failed.")); + } + }; + + NativeValue* lastParam = (info.argc == unwrapArgc) ? nullptr : info.argv[unwrapArgc]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; + } }; } // namespace @@ -109,6 +188,7 @@ NativeValue* CreateJsFormExtensionContext(NativeEngine& engine, std::shared_ptr< object->SetNativePointer(jsContext.release(), JsFormExtensionContext::Finalizer, nullptr); BindNativeFunction(engine, *object, "updateForm", JsFormExtensionContext::UpdateForm); + BindNativeFunction(engine, *object, "startAbility", JsFormExtensionContext::StartAbility); HILOG_INFO("%{public}s called end.", __func__); return objValue; diff --git a/frameworks/kits/ability/native/src/form_runtime/js_form_extension_util.cpp b/frameworks/kits/ability/native/src/form_runtime/js_form_extension_util.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7727490b22c1f472e7162fa1d61d2e92839e2865 --- /dev/null +++ b/frameworks/kits/ability/native/src/form_runtime/js_form_extension_util.cpp @@ -0,0 +1,59 @@ +/* + * 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 "form_runtime/js_form_extension_util.h" + +#include "hilog_wrapper.h" +#include "napi_common_util.h" + +namespace OHOS { +namespace AbilityRuntime { +using namespace OHOS::AppExecFwk; +bool 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 index ced5009c6b6d6ab87876e7451101769abf539161..a014d20bd34200c454982d7053a2755588a048a2 100644 --- a/frameworks/kits/ability/native/src/js_datashare_ext_ability.cpp +++ b/frameworks/kits/ability/native/src/js_datashare_ext_ability.cpp @@ -16,8 +16,11 @@ #include "js_datashare_ext_ability.h" #include "ability_info.h" +#include "accesstoken_kit.h" +#include "dataobs_mgr_client.h" #include "datashare_stub_impl.h" #include "hilog_wrapper.h" +#include "ipc_skeleton.h" #include "js_datashare_ext_ability_context.h" #include "js_runtime.h" #include "js_runtime_utils.h" @@ -33,6 +36,7 @@ namespace { constexpr size_t ARGC_ONE = 1; constexpr size_t ARGC_TWO = 2; constexpr size_t ARGC_THREE = 3; +constexpr int INVALID_VALUE = -1; #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"; @@ -43,6 +47,9 @@ const std::string LIB_DATA_ABILITY_PATH = "/system/lib64/module/data/libdataabil } using namespace OHOS::AppExecFwk; +using OHOS::Security::AccessToken::AccessTokenKit; +using DataObsMgrClient = OHOS::AAFwk::DataObsMgrClient; + JsDataShareExtAbility* JsDataShareExtAbility::Create(const std::unique_ptr& runtime) { return new JsDataShareExtAbility(static_cast(*runtime)); @@ -69,8 +76,7 @@ void JsDataShareExtAbility::Init(const std::shared_ptr &reco 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()); + HILOG_INFO("%{public}s module:%{public}s, srcPath:%{public}s.", __func__, moduleName.c_str(), srcPath.c_str()); HandleScope handleScope(jsRuntime_); auto& engine = jsRuntime_.GetNativeEngine(); @@ -95,7 +101,8 @@ void JsDataShareExtAbility::Init(const std::shared_ptr &reco } HILOG_INFO("JsDataShareExtAbility::Init CreateJsDataShareExtAbilityContext."); NativeValue* contextObj = CreateJsDataShareExtAbilityContext(engine, context); - auto contextRef = jsRuntime_.LoadSystemModule("application.DataShareExtAbilityContext", &contextObj, ARGC_ONE); + auto contextRef = jsRuntime_.LoadSystemModule("application.DataShareExtensionAbilityContext", + &contextObj, ARGC_ONE); contextObj = contextRef->Get(); HILOG_INFO("JsDataShareExtAbility::Init Bind."); context->Bind(jsRuntime_, contextRef.release()); @@ -162,8 +169,8 @@ void JsDataShareExtAbility::UnloadLibrary() void JsDataShareExtAbility::OnStart(const AAFwk::Want &want) { - Extension::OnStart(want); HILOG_INFO("%{public}s begin.", __func__); + Extension::OnStart(want); HandleScope handleScope(jsRuntime_); napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); napi_value napiWant = OHOS::AppExecFwk::WrapWant(env, want); @@ -175,8 +182,8 @@ void JsDataShareExtAbility::OnStart(const AAFwk::Want &want) sptr JsDataShareExtAbility::OnConnect(const AAFwk::Want &want) { - Extension::OnConnect(want); HILOG_INFO("%{public}s begin.", __func__); + Extension::OnConnect(want); sptr remoteObject = new (std::nothrow) DataShareStubImpl( std::static_pointer_cast(shared_from_this())); HILOG_INFO("%{public}s end. ", __func__); @@ -208,7 +215,7 @@ NativeValue* JsDataShareExtAbility::CallObjectMethod(const char* name, NativeVal return nullptr; } HILOG_INFO("JsDataShareExtAbility::CallFunction(%{public}s), success", name); - return nativeEngine.CallFunction(value, method, argv, argc); + return handleScope.Escape(nativeEngine.CallFunction(value, method, argv, argc)); } void JsDataShareExtAbility::GetSrcPath(std::string &srcPath) @@ -234,8 +241,8 @@ void JsDataShareExtAbility::GetSrcPath(std::string &srcPath) std::vector JsDataShareExtAbility::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) { - auto ret = DataShareExtAbility::GetFileTypes(uri, mimeTypeFilter); HILOG_INFO("%{public}s begin.", __func__); + auto ret = DataShareExtAbility::GetFileTypes(uri, mimeTypeFilter); HandleScope handleScope(jsRuntime_); napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); @@ -264,8 +271,8 @@ std::vector JsDataShareExtAbility::GetFileTypes(const Uri &uri, con int JsDataShareExtAbility::OpenFile(const Uri &uri, const std::string &mode) { - auto ret = DataShareExtAbility::OpenFile(uri, mode); HILOG_INFO("%{public}s begin.", __func__); + auto ret = DataShareExtAbility::OpenFile(uri, mode); HandleScope handleScope(jsRuntime_); napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); @@ -290,8 +297,8 @@ int JsDataShareExtAbility::OpenFile(const Uri &uri, const std::string &mode) int JsDataShareExtAbility::OpenRawFile(const Uri &uri, const std::string &mode) { - auto ret = DataShareExtAbility::OpenRawFile(uri, mode); HILOG_INFO("%{public}s begin.", __func__); + auto ret = DataShareExtAbility::OpenRawFile(uri, mode); HandleScope handleScope(jsRuntime_); napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); @@ -316,8 +323,14 @@ int JsDataShareExtAbility::OpenRawFile(const Uri &uri, const std::string &mode) int JsDataShareExtAbility::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) { - auto ret = DataShareExtAbility::Insert(uri, value); HILOG_INFO("%{public}s begin.", __func__); + int ret = INVALID_VALUE; + if (!CheckCallingPermission(abilityInfo_->writePermission)) { + HILOG_ERROR("%{public}s Check calling permission failed.", __func__); + return ret; + } + + ret = DataShareExtAbility::Insert(uri, value); if (rdbValueBucketNewInstance_ == nullptr) { HILOG_ERROR("%{public}s invalid instance of rdb value bucket.", __func__); return ret; @@ -327,6 +340,10 @@ int JsDataShareExtAbility::Insert(const Uri &uri, const NativeRdb::ValuesBucket 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)); + if (napiValue == nullptr) { + HILOG_ERROR("%{public}s failed to make new instance of rdbValueBucket.", __func__); + return ret; + } NativeValue* nativeUri = reinterpret_cast(napiUri); NativeValue* nativeValue = reinterpret_cast(napiValue); @@ -345,8 +362,14 @@ int JsDataShareExtAbility::Insert(const Uri &uri, const NativeRdb::ValuesBucket 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__); + int ret = INVALID_VALUE; + if (!CheckCallingPermission(abilityInfo_->writePermission)) { + HILOG_ERROR("%{public}s Check calling permission failed.", __func__); + return ret; + } + + ret = DataShareExtAbility::Update(uri, value, predicates); if (rdbValueBucketNewInstance_ == nullptr) { HILOG_ERROR("%{public}s invalid instance of ValuesBucket.", __func__); return ret; @@ -360,10 +383,18 @@ int JsDataShareExtAbility::Update(const Uri &uri, const NativeRdb::ValuesBucket 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)); + if (napiValue == nullptr) { + HILOG_ERROR("%{public}s failed to make new instance of rdbValueBucket.", __func__); + return ret; + } OHOS::NativeRdb::DataAbilityPredicates* predicatesPtr = new OHOS::NativeRdb::DataAbilityPredicates(); *predicatesPtr = predicates; napi_value napiPredicates = dataAbilityPredicatesNewInstance_(env, predicatesPtr); + if (napiPredicates == nullptr) { + HILOG_ERROR("%{public}s failed to make new instance of dataAbilityPredicates.", __func__); + return ret; + } NativeValue* nativeUri = reinterpret_cast(napiUri); NativeValue* nativeValue = reinterpret_cast(napiValue); @@ -382,12 +413,14 @@ int JsDataShareExtAbility::Update(const Uri &uri, const NativeRdb::ValuesBucket 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__); + int ret = INVALID_VALUE; + if (!CheckCallingPermission(abilityInfo_->writePermission)) { + HILOG_ERROR("%{public}s Check calling permission failed.", __func__); return ret; } + + ret = DataShareExtAbility::Delete(uri, predicates); if (dataAbilityPredicatesNewInstance_ == nullptr) { HILOG_ERROR("%{public}s invalid instance of DataAbilityPredicates.", __func__); return ret; @@ -400,6 +433,10 @@ int JsDataShareExtAbility::Delete(const Uri &uri, const NativeRdb::DataAbilityPr OHOS::NativeRdb::DataAbilityPredicates* predicatesPtr = new OHOS::NativeRdb::DataAbilityPredicates(); *predicatesPtr = predicates; napi_value napiPredicates = dataAbilityPredicatesNewInstance_(env, predicatesPtr); + if (napiPredicates == nullptr) { + HILOG_ERROR("%{public}s failed to make new instance of dataAbilityPredicates.", __func__); + return ret; + } NativeValue* nativeUri = reinterpret_cast(napiUri); NativeValue* nativePredicates = reinterpret_cast(napiPredicates); @@ -418,12 +455,14 @@ int JsDataShareExtAbility::Delete(const Uri &uri, const NativeRdb::DataAbilityPr 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__); + std::shared_ptr ret; + if (!CheckCallingPermission(abilityInfo_->readPermission)) { + HILOG_ERROR("%{public}s Check calling permission failed.", __func__); return ret; } + + ret = DataShareExtAbility::Query(uri, columns, predicates); if (dataAbilityPredicatesNewInstance_ == nullptr) { HILOG_ERROR("%{public}s invalid instance of DataAbilityPredicates.", __func__); return ret; @@ -450,6 +489,10 @@ std::shared_ptr JsDataShareExtAbility::Query(cons OHOS::NativeRdb::DataAbilityPredicates* predicatesPtr = new OHOS::NativeRdb::DataAbilityPredicates(); *predicatesPtr = predicates; napi_value napiPredicates = dataAbilityPredicatesNewInstance_(env, predicatesPtr); + if (napiPredicates == nullptr) { + HILOG_ERROR("%{public}s failed to make new instance of dataAbilityPredicates.", __func__); + return ret; + } NativeValue* nativeUri = reinterpret_cast(napiUri); NativeValue* nativeColumns = reinterpret_cast(napiColumns); @@ -461,6 +504,11 @@ std::shared_ptr JsDataShareExtAbility::Query(cons return ret; } + if (rdbResultSetProxyGetNativeObject_ == nullptr) { + HILOG_ERROR("%{public}s rdbResultSetProxyGetNativeObject_ is null.", __func__); + return ret; + } + auto nativeObject = rdbResultSetProxyGetNativeObject_(env, reinterpret_cast(nativeResult)); if (nativeObject == nullptr) { HILOG_ERROR("JsiPaEngine AbsSharedResultSet from JS to Native failed"); @@ -474,8 +522,8 @@ std::shared_ptr JsDataShareExtAbility::Query(cons std::string JsDataShareExtAbility::GetType(const Uri &uri) { - auto ret = DataShareExtAbility::GetType(uri); HILOG_INFO("%{public}s begin.", __func__); + auto ret = DataShareExtAbility::GetType(uri); HandleScope handleScope(jsRuntime_); napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); @@ -497,8 +545,14 @@ std::string JsDataShareExtAbility::GetType(const Uri &uri) int JsDataShareExtAbility::BatchInsert(const Uri &uri, const std::vector &values) { - auto ret = DataShareExtAbility::BatchInsert(uri, values); HILOG_INFO("%{public}s begin.", __func__); + int ret = INVALID_VALUE; + if (!CheckCallingPermission(abilityInfo_->writePermission)) { + HILOG_ERROR("%{public}s Check calling permission failed.", __func__); + return ret; + } + + ret = DataShareExtAbility::BatchInsert(uri, values); if (rdbValueBucketNewInstance_ == nullptr) { HILOG_ERROR("%{public}s invalid instance of rdb value bucket.", __func__); return ret; @@ -518,6 +572,10 @@ int JsDataShareExtAbility::BatchInsert(const Uri &uri, const std::vector(value)); + if (result == nullptr) { + HILOG_ERROR("%{public}s failed to make new instance of rdbValueBucket.", __func__); + return ret; + } napi_set_element(env, napiValues, index++, result); } @@ -537,32 +595,65 @@ int JsDataShareExtAbility::BatchInsert(const Uri &uri, const std::vector &dataObserver) { - DataShareExtAbility::RegisterObserver(uri, dataObserver); HILOG_INFO("%{public}s begin.", __func__); + DataShareExtAbility::RegisterObserver(uri, dataObserver); + auto obsMgrClient = DataObsMgrClient::GetInstance(); + if (obsMgrClient == nullptr) { + HILOG_ERROR("%{public}s obsMgrClient is nullptr", __func__); + return false; + } + + ErrCode ret = obsMgrClient->RegisterObserver(uri, dataObserver); + if (ret != ERR_OK) { + HILOG_ERROR("%{public}s obsMgrClient->RegisterObserver error return %{public}d", __func__, ret); + return false; + } 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__); + DataShareExtAbility::UnregisterObserver(uri, dataObserver); + auto obsMgrClient = DataObsMgrClient::GetInstance(); + if (obsMgrClient == nullptr) { + HILOG_ERROR("%{public}s obsMgrClient is nullptr", __func__); + return false; + } + + ErrCode ret = obsMgrClient->UnregisterObserver(uri, dataObserver); + if (ret != ERR_OK) { + HILOG_ERROR("%{public}s obsMgrClient->UnregisterObserver error return %{public}d", __func__, ret); + return false; + } 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__); + DataShareExtAbility::NotifyChange(uri); + auto obsMgrClient = DataObsMgrClient::GetInstance(); + if (obsMgrClient == nullptr) { + HILOG_ERROR("%{public}s obsMgrClient is nullptr", __func__); + return false; + } + + ErrCode ret = obsMgrClient->NotifyChange(uri); + if (ret != ERR_OK) { + HILOG_ERROR("%{public}s obsMgrClient->NotifyChange error return %{public}d", __func__, ret); + return false; + } HILOG_INFO("%{public}s end.", __func__); - return ret; + return true; } Uri JsDataShareExtAbility::NormalizeUri(const Uri &uri) { - auto ret = DataShareExtAbility::NormalizeUri(uri); HILOG_INFO("%{public}s begin.", __func__); + auto ret = DataShareExtAbility::NormalizeUri(uri); HandleScope handleScope(jsRuntime_); napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); @@ -583,8 +674,8 @@ Uri JsDataShareExtAbility::NormalizeUri(const Uri &uri) Uri JsDataShareExtAbility::DenormalizeUri(const Uri &uri) { - auto ret = DataShareExtAbility::DenormalizeUri(uri); HILOG_INFO("%{public}s begin.", __func__); + auto ret = DataShareExtAbility::DenormalizeUri(uri); HandleScope handleScope(jsRuntime_); napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); @@ -606,10 +697,22 @@ Uri JsDataShareExtAbility::DenormalizeUri(const Uri &uri) std::vector> JsDataShareExtAbility::ExecuteBatch( const std::vector> &operations) { - auto ret = DataShareExtAbility::ExecuteBatch(operations); HILOG_INFO("%{public}s begin.", __func__); + auto ret = DataShareExtAbility::ExecuteBatch(operations); HILOG_INFO("%{public}s end.", __func__); return ret; } + +bool JsDataShareExtAbility::CheckCallingPermission(const std::string &permission) +{ + HILOG_INFO("%{public}s begin, permission:%{public}s", __func__, permission.c_str()); + if (!permission.empty() && AccessTokenKit::VerifyAccessToken(IPCSkeleton::GetCallingTokenID(), permission) + != AppExecFwk::Constants::PERMISSION_GRANTED) { + HILOG_ERROR("%{public}s permission not granted.", __func__); + return false; + } + HILOG_INFO("%{public}s end.", __func__); + return true; +} } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/js_service_extension.cpp b/frameworks/kits/ability/native/src/js_service_extension.cpp index 558599713d9942ae8b67f297ce9b40ea05e88e82..7213058c2cdcdf9d263a52a81c7d11ad16845e62 100755 --- a/frameworks/kits/ability/native/src/js_service_extension.cpp +++ b/frameworks/kits/ability/native/src/js_service_extension.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,11 +18,13 @@ #include "ability_info.h" #include "bytrace.h" #include "hilog_wrapper.h" +#include "js_extension_context.h" #include "js_runtime.h" #include "js_runtime_utils.h" #include "js_service_extension_context.h" #include "napi/native_api.h" #include "napi/native_node_api.h" +#include "napi_common_configuration.h" #include "napi_common_want.h" #include "napi_remote_object.h" @@ -79,10 +81,10 @@ void JsServiceExtension::Init(const std::shared_ptr &record, } HILOG_INFO("JsServiceExtension::Init CreateJsServiceExtensionContext."); NativeValue* contextObj = CreateJsServiceExtensionContext(engine, context); - auto shellContextRef = jsRuntime_.LoadSystemModule("application.ServiceExtensionContext", &contextObj, ARGC_ONE); - contextObj = shellContextRef->Get(); + shellContextRef_ = jsRuntime_.LoadSystemModule("application.ServiceExtAbilityContext", &contextObj, ARGC_ONE); + contextObj = shellContextRef_->Get(); HILOG_INFO("JsServiceExtension::Init Bind."); - context->Bind(jsRuntime_, shellContextRef.release()); + context->Bind(jsRuntime_, shellContextRef_.get()); HILOG_INFO("JsServiceExtension::SetProperty."); obj->SetProperty("context", contextObj); @@ -123,6 +125,7 @@ void JsServiceExtension::OnStop() CallObjectMethod("onDestroy"); bool ret = ConnectionManager::GetInstance().DisconnectCaller(GetContext()->GetToken()); if (ret) { + ConnectionManager::GetInstance().ReportConnectionLeakEvent(getpid(), gettid()); HILOG_INFO("The service extension connection is not disconnected."); } HILOG_INFO("%{public}s end.", __func__); @@ -268,5 +271,23 @@ void JsServiceExtension::GetSrcPath(std::string &srcPath) srcPath.append(".abc"); } } + +void JsServiceExtension::OnConfigurationUpdated(const AppExecFwk::Configuration& configuration) +{ + Extension::OnConfigurationUpdated(configuration); + HILOG_INFO("%{public}s called.", __func__); + + HandleScope handleScope(jsRuntime_); + auto& nativeEngine = jsRuntime_.GetNativeEngine(); + + // Notify extension context + auto fullConfig = GetContext()->GetConfiguration(); + JsExtensionContext::ConfigurationUpdated(&nativeEngine, shellContextRef_, fullConfig); + + napi_value napiConfiguration = OHOS::AppExecFwk::WrapConfiguration( + reinterpret_cast(&nativeEngine), *fullConfig); + NativeValue* jsConfiguration = reinterpret_cast(napiConfiguration); + CallObjectMethod("onConfigurationUpdated", &jsConfiguration, 1); +} } } 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 11827c2589a38f70dbe54ba99f04ca157c0ebdfa..fc0c9560d2a4d85a1f98c3eca0eecf417908e284 100755 --- a/frameworks/kits/ability/native/src/js_service_extension_context.cpp +++ b/frameworks/kits/ability/native/src/js_service_extension_context.cpp @@ -45,7 +45,7 @@ constexpr size_t ARGC_FOUR = 4; class JsServiceExtensionContext final { public: - JsServiceExtensionContext(const std::shared_ptr& context) : context_(context) {} + explicit JsServiceExtensionContext(const std::shared_ptr& context) : context_(context) {} ~JsServiceExtensionContext() = default; static void Finalizer(NativeEngine* engine, void* data, void* hint) diff --git a/frameworks/kits/ability/native/src/new_ability_impl.cpp b/frameworks/kits/ability/native/src/new_ability_impl.cpp index 14408a52073b5b0236845277babf1ccee5c32bad..78f08b58884b401cc5fee58db5dc66810965056e 100644 --- a/frameworks/kits/ability/native/src/new_ability_impl.cpp +++ b/frameworks/kits/ability/native/src/new_ability_impl.cpp @@ -36,6 +36,9 @@ void NewAbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::Lif targetState.isNewWant, targetState.sceneFlag); if ((lifecycleState_ == targetState.state) && !targetState.isNewWant) { + if (ability_ != nullptr && targetState.state == AAFwk::ABILITY_STATE_FOREGROUND_NEW) { + ability_->RequsetFocus(want); + } APP_LOGE("Org lifeCycleState equals to Dst lifeCycleState."); return; } diff --git a/frameworks/kits/ability/native/src/page_ability_impl.cpp b/frameworks/kits/ability/native/src/page_ability_impl.cpp index 71e13ba0334dd3e467a19029a7cb8b1bf6acdf0d..961011ebebd29cdbd190f5e217d8bb9652087c22 100644 --- a/frameworks/kits/ability/native/src/page_ability_impl.cpp +++ b/frameworks/kits/ability/native/src/page_ability_impl.cpp @@ -36,6 +36,9 @@ void PageAbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::Li targetState.isNewWant, targetState.sceneFlag); if ((lifecycleState_ == targetState.state) && !targetState.isNewWant) { + if (ability_ != nullptr && targetState.state == AAFwk::ABILITY_STATE_FOREGROUND_NEW) { + ability_->RequsetFocus(want); + } APP_LOGE("Org lifeCycleState equals to Dst lifeCycleState."); return; } diff --git a/frameworks/kits/ability/native/test/mock/include/bundle_mgr_interface.h b/frameworks/kits/ability/native/test/mock/include/bundle_mgr_interface.h deleted file mode 100644 index 9404f4d2f6379b87dc337270965931a9b53cab5a..0000000000000000000000000000000000000000 --- a/frameworks/kits/ability/native/test/mock/include/bundle_mgr_interface.h +++ /dev/null @@ -1,294 +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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_BUNDLEMGR_INCLUDE_MOCK_BUNDLE_MGR_INTERFACE_H -#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_BUNDLEMGR_INCLUDE_MOCK_BUNDLE_MGR_INTERFACE_H - -#include "ability_info.h" -#include "application_info.h" -#include "iremote_broker.h" -#include "iremote_object.h" - -#include "bundle_info.h" -#include "common_event_info.h" -#include "hap_module_info.h" -#include "ohos/aafwk/content/want.h" -#include "permission_def.h" -#include "module_usage_record.h" -#include "distributed_bundle_info.h" - -using OHOS::AAFwk::Want; - -namespace OHOS { -namespace AppExecFwk { -struct FormInfo; -struct ShortcutInfo; - -enum class DumpFlag { - DUMP_BUNDLE_LIST = 1, - DUMP_ALL_BUNDLE_INFO, - DUMP_BUNDLE_INFO, -}; - -enum class InstallFlag { - NORMAL = 0, - // Allow to replace the existing bundle when the new version isn't lower than the old one. - // If the bundle does not exist, just like normal flag. - REPLACE_EXISTING = 1, -}; - -enum class InstallLocation { - INTERNAL_ONLY = 1, - PREFER_EXTERNAL = 2, -}; - -struct InstallParam : public Parcelable { - InstallFlag installFlag = InstallFlag::NORMAL; - InstallLocation installLocation = InstallLocation::INTERNAL_ONLY; - int userId = -1; - // Is keep user data while uninstall. - bool isKeepData = false; - bool noCheckSignature = false; - - // the parcel object function is not const. - bool ReadFromParcel(Parcel &parcel); - virtual bool Marshalling(Parcel &parcel) const override; - static InstallParam *Unmarshalling(Parcel &parcel); -}; -class IBundleStatusCallback : public IRemoteBroker { -public: - DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.BundleStatusCallback"); - - virtual void OnBundleStateChanged(const uint8_t installType, const int32_t resultCode, const std::string &resultMsg, - const std::string &bundleName) = 0; - - enum class Message { - ON_BUNDLE_STATE_CHANGED, - }; -}; - -class ICleanCacheCallback : public IRemoteBroker { -public: - DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.CleanCacheCallback"); - - virtual void OnCleanCacheFinished(bool succeeded) = 0; - - enum class Message { - ON_CLEAN_CACHE_CALLBACK, - }; -}; - -class OnPermissionChangedCallback : public IRemoteBroker { -public: - DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.OnPermissionChangedCallback"); - /** - * @brief Called when an application's permission changed. - * @param uid Indicates the uid of the application which permission changed. - */ - virtual void OnChanged(const int32_t uid) = 0; - - enum class Message { - ON_CHANGED, - }; -}; - -class IStatusReceiver : public IRemoteBroker { -public: - DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.StatusReceiver"); - - virtual void OnStatusNotify(const int progress) = 0; - virtual void OnFinished(const int32_t resultCode, const std::string &resultMsg) = 0; - - enum class Message { - ON_STATUS_NOTIFY, - ON_FINISHED, - }; - - enum { - SUCCESS = 0, - ERR_INSTALL_INTERNAL_ERROR, - ERR_INSTALL_PARSE_FAILED, - ERR_INSTALL_VERSION_DOWNGRADE, - ERR_INSTALL_VERIFICATION_FAILED, - ERR_INSTALL_NO_SIGNATURE_INFO, - ERR_INSTALL_UPDATE_INCOMPATIBLE, - ERR_INSTALL_INVALID_BUNDLE_FILE, - ERR_INSTALL_MISSING_INSTALLED_BUNDLE, - ERR_INSTALL_ALREADY_EXIST, - ERR_INSTALL_PARSE_UNEXPECTED, - ERR_INSTALL_PARSE_MISSING_BUNDLE, - ERR_INSTALL_PARSE_MISSING_ABILITY, - ERR_INSTALL_PARSE_NO_PROFILE, - ERR_INSTALL_PARSE_BAD_PROFILE, - ERR_INSTALL_PARSE_PROFILE_PROP_TYPE_ERROR, - ERR_INSTALL_PARSE_PROFILE_MISSING_PROP, - ERR_UNINSTALL_INVALID_NAME, - ERR_UNKNOW, - }; -}; - -class IBundleInstaller : public IRemoteBroker { -public: - DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.BundleInstaller"); - - virtual bool Install(const std::string &bundleFilePath, const InstallParam &installParam, - const sptr &statusReceiver) = 0; - virtual bool Uninstall(const std::string &bundleName, const InstallParam &installParam, - const sptr &statusReceiver) = 0; - - enum class Message { - INSTALL, - UNINSTALL, - }; -}; - -class IBundleMgr : public IRemoteBroker { -public: - DECLARE_INTERFACE_DESCRIPTOR(u"ohos.aafwk.BundleMgr"); - virtual bool GetApplicationInfo( - const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) = 0; - virtual bool GetApplicationInfos( - const ApplicationFlag flag, const int userId, std::vector &appInfos) = 0; - virtual bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) = 0; - virtual bool GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos) = 0; - virtual int GetUidByBundleName(const std::string &bundleName, const int userId) = 0; - virtual std::string GetAppIdByBundleName(const std::string &bundleName, const int userId) = 0; - virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) = 0; - virtual bool GetBundlesForUid(const int uid, std::vector &bundleNames) = 0; - virtual bool GetNameForUid(const int uid, std::string &name) = 0; - virtual bool GetBundleGids(const std::string &bundleName, std::vector &gids) = 0; - virtual std::string GetAppType(const std::string &bundleName) = 0; - virtual bool CheckIsSystemAppByUid(const int uid) = 0; - virtual bool GetBundleInfosByMetaData(const std::string &metaData, std::vector &bundleInfos) = 0; - virtual bool QueryAbilityInfo(const Want &want, AbilityInfo &abilityInfo) = 0; - virtual bool QueryAbilityInfos(const Want &want, std::vector &abilityInfos) = 0; - virtual bool QueryAbilityInfosForClone(const Want &want, std::vector &abilityInfos) = 0; - virtual bool QueryAbilityInfoByUri(const std::string &abilityUri, AbilityInfo &abilityInfo) = 0; - virtual bool QueryKeepAliveBundleInfos(std::vector &bundleInfos) = 0; - virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) = 0; - virtual bool GetBundleArchiveInfo( - const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) = 0; - virtual bool GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) = 0; - virtual bool GetLaunchWantForBundle(const std::string &bundleName, Want &want) = 0; - virtual int CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) = 0; - virtual int CheckPermission(const std::string &bundleName, const std::string &permission) = 0; - virtual bool GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) = 0; - virtual bool GetAllPermissionGroupDefs(std::vector &permissionDefs) = 0; - virtual bool GetAppsGrantedPermissions( - const std::vector &permissions, std::vector &appNames) = 0; - virtual bool HasSystemCapability(const std::string &capName) = 0; - virtual bool GetSystemAvailableCapabilities(std::vector &systemCaps) = 0; - virtual bool IsSafeMode() = 0; - virtual bool CleanBundleCacheFiles( - const std::string &bundleName, const sptr &cleanCacheCallback) = 0; - virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0) = 0; - virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) = 0; - virtual bool ClearBundleStatusCallback(const sptr &bundleStatusCallback) = 0; - virtual bool UnregisterBundleStatusCallback() = 0; - virtual bool DumpInfos( - const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result) = 0; - virtual bool IsApplicationEnabled(const std::string &bundleName) = 0; - virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) = 0; - virtual bool IsAbilityEnabled(const AbilityInfo &abilityInfo) = 0; - virtual bool SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) = 0; - virtual std::string GetAbilityIcon(const std::string &bundleName, const std::string &className) = 0; - virtual bool CanRequestPermission( - const std::string &bundleName, const std::string &permissionName, const int userId) = 0; - virtual bool RequestPermissionFromUser( - const std::string &bundleName, const std::string &permission, const int userId) = 0; - virtual bool RegisterAllPermissionsChanged(const sptr &callback) = 0; - virtual bool RegisterPermissionsChanged( - const std::vector &uids, const sptr &callback) = 0; - virtual bool UnregisterPermissionsChanged(const sptr &callback) = 0; - virtual bool GetAllFormsInfo(std::vector &formInfos) = 0; - virtual bool GetFormsInfoByApp(const std::string &bundleName, std::vector &formInfos) = 0; - virtual bool GetFormsInfoByModule( - const std::string &bundleName, const std::string &moduleName, std::vector &formInfos) = 0; - virtual bool GetShortcutInfos(const std::string &bundleName, std::vector &shortcutInfos) = 0; - virtual bool GetModuleUsageRecords(const int32_t number, std::vector &moduleUsageRecords) = 0; - virtual sptr GetBundleInstaller() = 0; - virtual bool NotifyAbilityLifeStatus( - const std::string &bundleName, const std::string &abilityName, const int64_t launchTime, const int uid = 0) = 0; - virtual bool GetBundleGidsByUid(const std::string &bundleName, const int &uid, std::vector &gids) = 0; - virtual bool QueryAbilityInfosByUri(const std::string &abilityUri, std::vector &abilityInfos) = 0; - virtual int CheckPermissionByUid( - const std::string &bundleName, const std::string &permission, const int userId) = 0; - virtual bool GetAllCommonEventInfo(const std::string &eventKey, std::vector &commonEventInfos) = 0; - virtual bool RemoveClonedBundle(const std::string &bundleName, const int32_t uid) = 0; - virtual bool BundleClone(const std::string &bundleName) = 0; - virtual bool CheckBundleNameInAllowList(const std::string &bundleName) = 0; - virtual bool GetDistributedBundleInfo( - const std::string &networkId, int32_t userId, const std::string &bundleName, - DistributedBundleInfo &distributedBundleInfo) = 0; - - enum class Message { - GET_APPLICATION_INFO, - GET_APPLICATION_INFOS, - GET_BUNDLE_INFO, - GET_BUNDLE_INFOS, - GET_UID_BY_BUNDLE_NAME, - GET_APPID_BY_BUNDLE_NAME, - GET_BUNDLE_NAME_FOR_UID, - GET_BUNDLES_FOR_UID, - GET_NAME_FOR_UID, - GET_BUNDLE_GIDS, - GET_APP_TYPE, - CHECK_IS_SYSTEM_APP_BY_UID, - GET_BUNDLE_INFOS_BY_METADATA, - QUERY_ABILITY_INFO, - QUERY_ABILITY_INFOS, - QUERY_ABILITY_INFOS_FOR_CLONE, - QUERY_ABILITY_INFO_BY_URI, - QUERY_KEEPALIVE_BUNDLE_INFOS, - GET_ABILITY_LABEL, - GET_BUNDLE_ARCHIVE_INFO, - GET_HAP_MODULE_INFO, - GET_LAUNCH_WANT_FOR_BUNDLE, - CHECK_PUBLICKEYS, - CHECK_PERMISSION, - GET_PERMISSION_DEF, - GET_ALL_PERMISSION_GROUP_DEFS, - GET_APPS_GRANTED_PERMISSIONS, - HAS_SYSTEM_CAPABILITY, - GET_SYSTEM_AVAILABLE_CAPABILITIES, - IS_SAFE_MODE, - CLEAN_BUNDLE_CACHE_FILES, - CLEAN_BUNDLE_DATA_FILES, - REGISTER_BUNDLE_STATUS_CALLBACK, - CLEAR_BUNDLE_STATUS_CALLBACK, - UNREGISTER_BUNDLE_STATUS_CALLBACK, - DUMP_INFOS, - IS_APPLICATION_ENABLED, - SET_APPLICATION_ENABLED, - IS_ABILITY_ENABLED, - SET_ABILITY_ENABLED, - GET_ABILITY_ICON, - CAN_REQUEST_PERMISSION, - REQUEST_PERMISSION_FROM_USER, - REGISTER_ALL_PERMISSIONS_CHANGED, - REGISTER_PERMISSIONS_CHANGED, - UNREGISTER_PERMISSIONS_CHANGED, - GET_ALL_FORMS_INFO, - GET_FORMS_INFO_BY_APP, - GET_FORMS_INFO_BY_MODULE, - GET_MODULE_USAGE_RECORD, - GET_SHORTCUT_INFO, - GET_BUNDLE_INSTALLER, - NOTIFY_ABILITY_LIFE_STATUS, - }; -}; -} // namespace AppExecFwk -} // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_BUNDLEMGR_INCLUDE_MOCK_BUNDLE_MGR_INTERFACE_H diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.h b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.h index 3c1fda6d1d2cf024ffd8e193479025671469f4a6..c5d85822a23191da8bff21adcca6d7afb56c9b84 100755 --- a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.h @@ -125,9 +125,9 @@ public: { return std::vector>(); }; - virtual void NotifyContinuationResult(const int32_t result) {}; + virtual void NotifyContinuationResult(int32_t result) {}; virtual void ContinueAbility(const std::string& deviceId) {}; - virtual void DumpAbilityInfo(std::vector &info) {}; + virtual void DumpAbilityInfo(const std::vector ¶ms, std::vector &info) {}; virtual sptr CallRequest() { return sptr(nullptr); @@ -135,4 +135,4 @@ public: }; } // namespace AppExecFwk } // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_NATIVE_MOCK_ABILITY_MANAGER_CLIENT_H \ No newline at end of file +#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_NATIVE_MOCK_ABILITY_MANAGER_CLIENT_H diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_service.h b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_service.h index f828cef1da661c0fa4e7c870ea9fa2f8dd643a9a..8aad0460eee2690eb1b69077b75228e57d98cd33 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_service.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_service.h @@ -53,6 +53,11 @@ public: int TerminateAbility( const sptr &token, int resultCode = -1, const Want *resultWant = nullptr) override; + virtual int CloseAbility(const sptr &token, int resultCode = DEFAULT_INVAL_VALUE, + const Want *resultWant = nullptr) override + { + return 0; + } int MinimizeAbility(const sptr &token, bool fromUser) override { return 0; @@ -137,7 +142,7 @@ public: MOCK_METHOD1(GetPendinTerminateAbilityTestgRequestWant, void(int id)); MOCK_METHOD1(GetSystemMemoryAttr, void(AppExecFwk::SystemMemoryAttr &memoryInfo)); MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); - MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result)); + MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, int32_t result)); MOCK_METHOD5(ContinueMission, int(const std::string &srcDeviceId, const std::string &dstDeviceId, int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams)); MOCK_METHOD2(ContinueAbility, int(const std::string &deviceId, int32_t missionId)); @@ -154,6 +159,7 @@ public: MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); + MOCK_METHOD2(MoveMissionToFront, int(int32_t missionId, const StartOptions &startOptions)); MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector &info)); MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector &info)); @@ -270,9 +276,9 @@ public: return 0; } - virtual bool SendANRProcessID(int pid) override + virtual int SendANRProcessID(int pid) override { - return true; + return 0; } virtual int StartUserTest(const Want &want, const sptr &observer) override diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_scheduler_for_observer.h b/frameworks/kits/ability/native/test/mock/include/mock_ability_scheduler_for_observer.h index a638facadc4d357173aa3f0ea53da3967a595c11..b5c7d3e35c29fbf24cb2e0c6472ff8b2ec78dc7a 100755 --- a/frameworks/kits/ability/native/test/mock/include/mock_ability_scheduler_for_observer.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_scheduler_for_observer.h @@ -58,9 +58,9 @@ public: MOCK_METHOD2(ScheduleUnregisterObserver, bool(const Uri &uri, const sptr &dataObserver)); MOCK_METHOD1(ScheduleNotifyChange, bool(const Uri &uri)); MOCK_METHOD1(ExecuteBatch, std::vector>(const std::vector> &operation)); - MOCK_METHOD1(NotifyContinuationResult, void(const int32_t result)); + MOCK_METHOD1(NotifyContinuationResult, void(int32_t result)); MOCK_METHOD1(ContinueAbility, void(const std::string& deviceId)); - MOCK_METHOD1(DumpAbilityInfo, void(std::vector &info)); + MOCK_METHOD2(DumpAbilityInfo, void(const std::vector ¶ms, std::vector &info)); virtual sptr CallRequest() { @@ -71,4 +71,4 @@ public: } // namespace AppExecFwk } // namespace OHOS -#endif /* OHOS_APPEXECFWK_MOCK_ABILITY_SCHEDULER_FOR_OBESERVER_H */ \ No newline at end of file +#endif /* OHOS_APPEXECFWK_MOCK_ABILITY_SCHEDULER_FOR_OBESERVER_H */ diff --git a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.cpp b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.cpp index 0caca14c280c5e4e0f35fc4a0a8e67a229c0cafd..cc5a68fc2514c2de026af7017b6360e7f217d29f 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.cpp +++ b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.cpp @@ -36,14 +36,6 @@ bool BundleMgrProxy::GetApplicationInfos( { return true; } -bool BundleMgrProxy::GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) -{ - return true; -} -bool BundleMgrProxy::GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos) -{ - return true; -} int BundleMgrProxy::GetUidByBundleName(const std::string &bundleName, const int userId) { return 0; @@ -161,11 +153,6 @@ bool BundleMgrProxy::IsSafeMode() { return true; } -bool BundleMgrProxy::CleanBundleCacheFiles( - const std::string &bundleName, const sptr &cleanCacheCallback) -{ - return true; -} bool BundleMgrProxy::CleanBundleDataFiles(const std::string &bundleName, const int userId) { return true; @@ -191,18 +178,10 @@ bool BundleMgrProxy::IsApplicationEnabled(const std::string &bundleName) { return true; } -bool BundleMgrProxy::SetApplicationEnabled(const std::string &bundleName, bool isEnable) -{ - return true; -} bool BundleMgrProxy::IsAbilityEnabled(const AbilityInfo &abilityInfo) { return true; } -bool BundleMgrProxy::SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) -{ - return true; -} std::string BundleMgrProxy::GetAbilityIcon(const std::string &bundleName, const std::string &className) { return ""; @@ -282,14 +261,6 @@ bool BundleMgrService::GetApplicationInfos( { return true; } -bool BundleMgrService::GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) -{ - return true; -} -bool BundleMgrService::GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos) -{ - return true; -} int BundleMgrService::GetUidByBundleName(const std::string &bundleName, const int userId) { return 0; @@ -415,11 +386,6 @@ bool BundleMgrService::IsSafeMode() { return true; } -bool BundleMgrService::CleanBundleCacheFiles( - const std::string &bundleName, const sptr &cleanCacheCallback) -{ - return true; -} bool BundleMgrService::CleanBundleDataFiles(const std::string &bundleName, const int userId) { return true; @@ -445,18 +411,10 @@ bool BundleMgrService::IsApplicationEnabled(const std::string &bundleName) { return true; } -bool BundleMgrService::SetApplicationEnabled(const std::string &bundleName, bool isEnable) -{ - return true; -} bool BundleMgrService::IsAbilityEnabled(const AbilityInfo &abilityInfo) { return true; } -bool BundleMgrService::SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) -{ - return true; -} std::string BundleMgrService::GetAbilityIcon(const std::string &bundleName, const std::string &className) { return ""; diff --git a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.h b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.h index 8ab2ec5c246b517bcab686cdde0d5621e5ce1a0e..aa70e0a23918ce0d9290e7607568fdf4626ffdce 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.h @@ -38,8 +38,19 @@ public: const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override; virtual bool GetApplicationInfos( const ApplicationFlag flag, const int userId, std::vector &appInfos) override; - virtual bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override; - virtual bool GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos) override; + virtual bool GetBundleInfo(const std::string &bundleName, + const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) override + { + return true; + } + virtual bool GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos, int32_t userId) override + { + return true; + } + virtual sptr GetBundleUserMgr() override + { + return nullptr; + } virtual int GetUidByBundleName(const std::string &bundleName, const int userId) override; virtual std::string GetAppIdByBundleName(const std::string &bundleName, const int userId) override; virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) override; @@ -68,8 +79,6 @@ public: virtual bool HasSystemCapability(const std::string &capName) override; virtual bool GetSystemAvailableCapabilities(std::vector &systemCaps) override; virtual bool IsSafeMode() override; - virtual bool CleanBundleCacheFiles( - const std::string &bundleName, const sptr &cleanCacheCallback) override; virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId) override; virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override; virtual bool ClearBundleStatusCallback(const sptr &bundleStatusCallback) override; @@ -77,9 +86,7 @@ public: virtual bool DumpInfos( const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result) override; virtual bool IsApplicationEnabled(const std::string &bundleName) override; - virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override; virtual bool IsAbilityEnabled(const AbilityInfo &abilityInfo) override; - virtual bool SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) override; virtual std::string GetAbilityIcon(const std::string &bundleName, const std::string &className) override; virtual bool CanRequestPermission( const std::string &bundleName, const std::string &permissionName, const int userId) override; @@ -104,7 +111,6 @@ public: class BundleMgrStub : public IRemoteStub { public: - DECLARE_INTERFACE_DESCRIPTOR(u"IBundleMgr"); virtual int OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; }; @@ -115,8 +121,19 @@ public: const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override; virtual bool GetApplicationInfos( const ApplicationFlag flag, const int userId, std::vector &appInfos) override; - virtual bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override; - virtual bool GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos) override; + virtual bool GetBundleInfo(const std::string &bundleName, + const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) override + { + return true; + } + virtual bool GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos, int32_t userId) override + { + return true; + } + virtual sptr GetBundleUserMgr() override + { + return nullptr; + } virtual int GetUidByBundleName(const std::string &bundleName, const int userId) override; virtual std::string GetAppIdByBundleName(const std::string &bundleName, const int userId) override; virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) override; @@ -145,8 +162,6 @@ public: virtual bool HasSystemCapability(const std::string &capName) override; virtual bool GetSystemAvailableCapabilities(std::vector &systemCaps) override; virtual bool IsSafeMode() override; - virtual bool CleanBundleCacheFiles( - const std::string &bundleName, const sptr &cleanCacheCallback) override; virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId) override; virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override; virtual bool ClearBundleStatusCallback(const sptr &bundleStatusCallback) override; @@ -154,9 +169,7 @@ public: virtual bool DumpInfos( const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result) override; virtual bool IsApplicationEnabled(const std::string &bundleName) override; - virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override; virtual bool IsAbilityEnabled(const AbilityInfo &abilityInfo) override; - virtual bool SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) override; virtual std::string GetAbilityIcon(const std::string &bundleName, const std::string &className) override; virtual bool CanRequestPermission( const std::string &bundleName, const std::string &permissionName, const int userId) override; diff --git a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.h b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.h index 40b7dab2c9ec2a6a27fb48de841669cca6fb2868..340a7b37c2440be2a4d3984e522c6fbafe15ae0f 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.h @@ -20,7 +20,7 @@ #include "ability_info.h" #include "application_info.h" -#include "foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h" +#include "bundle_mgr_interface.h" #include "gmock/gmock.h" #include "iremote_proxy.h" #include "iremote_stub.h" @@ -146,12 +146,6 @@ public: { return true; } - // clears cache data of a specified application. - virtual bool CleanBundleCacheFiles( - const std::string &bundleName, const sptr &cleanCacheCallback) override - { - return true; - } virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId) override { return true; @@ -189,7 +183,7 @@ public: * @param form Indicates the callback a list to shortcutinfo. * @return Returns true if shortcutinfo get success */ - virtual bool GetShortcutInfos(const std::string &bundleName,std::vector &shortcut) override + virtual bool GetShortcutInfos(const std::string &bundleName, std::vector &shortcut) override { return true; } @@ -215,10 +209,6 @@ public: { return true; } - virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override - { - return true; - } virtual bool GetBundleInfo( const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) override; @@ -232,7 +222,6 @@ public: class BundleMgrStub : public IRemoteStub { public: - DECLARE_INTERFACE_DESCRIPTOR(u"IBundleMgr"); ~BundleMgrStub() = default; virtual int OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; @@ -250,7 +239,6 @@ public: bool(const std::string &bundleName, const std::string &permission, const int userId)); MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); - MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); @@ -345,12 +333,6 @@ public: { return true; }; - // clears cache data of a specified application. - virtual bool CleanBundleCacheFiles( - const std::string &bundleName, const sptr &cleanCacheCallback) override - { - return true; - }; virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override { @@ -390,10 +372,6 @@ public: return true; }; - virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override - { - return true; - }; /** * @brief Obtains information about the shortcuts of the application. @@ -401,7 +379,7 @@ public: * @param form Indicates the callback a list to shortcutinfo. * @return Returns true if shortcutinfo get success */ - virtual bool GetShortcutInfos(const std::string &bundleName,std::vector &shortcut) override + virtual bool GetShortcutInfos(const std::string &bundleName, std::vector &shortcut) override { return true; } diff --git a/frameworks/kits/ability/native/test/mock/include/mock_continuation_ability.h b/frameworks/kits/ability/native/test/mock/include/mock_continuation_ability.h index a1cc8240260c12252ac25bbc244c2edb4c2f3ffa..d8588193b5a48d7bfaaeae39ce00d084ad85b7b3 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_continuation_ability.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_continuation_ability.h @@ -16,9 +16,10 @@ #ifndef FOUNDATION_APPEXECFWK_OHOS_MOCK_CONTINUATION_ABILITY_H #define FOUNDATION_APPEXECFWK_OHOS_MOCK_CONTINUATION_ABILITY_H -#include "ability.h" #include +#include "ability.h" + namespace OHOS { namespace AppExecFwk { using Want = OHOS::AAFwk::Want; diff --git a/frameworks/kits/ability/native/test/mock/include/mock_replace_ability_impl.cpp b/frameworks/kits/ability/native/test/mock/include/mock_replace_ability_impl.cpp index 446a949e77e00f062f5adc1bd93e9c622bdac5df..5edeb91b6d479a65bc6eb2ddb223b9f8d1b38cf2 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_replace_ability_impl.cpp +++ b/frameworks/kits/ability/native/test/mock/include/mock_replace_ability_impl.cpp @@ -166,7 +166,8 @@ int AbilityImpl::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) return 1; } -int AbilityImpl::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) +int AbilityImpl::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, + const NativeRdb::DataAbilityPredicates &predicates) { GTEST_LOG_(INFO) << "Mock AbilityImpl::Update called"; return 1; diff --git a/frameworks/kits/ability/native/test/mock/include/mock_scene_created_ability.h b/frameworks/kits/ability/native/test/mock/include/mock_scene_created_ability.h index edd2884ca5890d026ab15b9f2412efecf450ae6a..31b888201cc352443e58cbff6aa998efde0c119a 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_scene_created_ability.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_scene_created_ability.h @@ -26,11 +26,13 @@ public: MockSceneCreatedAbility() = default; virtual ~MockSceneCreatedAbility() = default; - void OnSceneCreated() { + void OnSceneCreated() + { ++time; } - int GetTriggerTime() { + int GetTriggerTime() + { return time; } diff --git a/frameworks/kits/ability/native/test/unittest/ability_impl_test.cpp b/frameworks/kits/ability/native/test/unittest/ability_impl_test.cpp index 908acef60a0f0ae5fa46d5115d37067f611c25a7..7768d407651c30ffe51a16594f01a1bf46456fdb 100644 --- a/frameworks/kits/ability/native/test/unittest/ability_impl_test.cpp +++ b/frameworks/kits/ability/native/test/unittest/ability_impl_test.cpp @@ -169,6 +169,8 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_ScheduleUpdateConfiguration_002, Tes auto language = OHOS::Global::I18n::LocaleConfig::GetSystemLanguage(); GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_ScheduleUpdateConfiguration_002 : " << language; config.AddItem(GlobalConfigurationKey::SYSTEM_LANGUAGE, language); + Want want; // Trigger Ability LifeCycle to Active + mockAbilityimpl->CommandAbility(want, 0, 0); mockAbilityimpl->ScheduleUpdateConfiguration(config); auto testNotify3 = pMocKPageAbility->OnConfigurationUpdated_; EXPECT_EQ(testNotify3, 1); @@ -192,6 +194,7 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_ScheduleUpdateConfiguration_003, Tes std::shared_ptr mockAbilityimpl = std::make_shared(); std::shared_ptr application = std::make_shared(); std::shared_ptr abilityInfo = std::make_shared(); + std::shared_ptr applicationInfo = std::make_shared(); abilityInfo->name = "pageAbility"; sptr token = sptr(new (std::nothrow) MockAbilityToken()); EXPECT_NE(token, nullptr); @@ -207,6 +210,8 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_ScheduleUpdateConfiguration_003, Tes std::shared_ptr ability = pMocKPageAbility; if (pMocKPageAbility != nullptr) { std::shared_ptr contextDeal = std::make_shared(); + contextDeal->SetApplicationInfo(applicationInfo); + contextDeal->SetAbilityInfo(abilityInfo); std::shared_ptr resourceManager( Global::Resource::CreateResourceManager()); if (resourceManager == nullptr) { @@ -227,12 +232,14 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_ScheduleUpdateConfiguration_003, Tes auto language = OHOS::Global::I18n::LocaleConfig::GetSystemLanguage(); GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_ScheduleUpdateConfiguration_003 : " << language; config.AddItem(GlobalConfigurationKey::SYSTEM_LANGUAGE, language); + Want want; // Trigger Ability LifeCycle to Active + mockAbilityimpl->CommandAbility(want, 0, 0); mockAbilityimpl->ScheduleUpdateConfiguration(config); auto testNotify3 = pMocKPageAbility->OnConfigurationUpdated_; EXPECT_EQ(testNotify3, 1); mockAbilityimpl->ScheduleUpdateConfiguration(config); auto testNotify4 = pMocKPageAbility->OnConfigurationUpdated_; - EXPECT_EQ(testNotify4, 1); + EXPECT_EQ(testNotify4, 2); } } } @@ -469,11 +476,13 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_Active_001, TestSize.Level1) if (pMocKPageAbility != nullptr) { ability.reset(pMocKPageAbility); std::shared_ptr contextDeal = std::make_shared(); + std::shared_ptr applicationInfo = std::make_shared(); + contextDeal->SetApplicationInfo(applicationInfo); + contextDeal->SetAbilityInfo(abilityInfo); + pMocKPageAbility->AttachBaseContext(contextDeal); + application->AttachBaseContext(contextDeal); mockAbilityimpl->Init(application, record, ability, handler, token, contextDeal); - - AbilityLifecycleExecutor AbilityLifecycleExecutor_; mockAbilityimpl->ImplActive(); - EXPECT_EQ(MockPageAbility::Event::ON_ACTIVE, pMocKPageAbility->state_); EXPECT_EQ(AAFwk::ABILITY_STATE_ACTIVE, mockAbilityimpl->GetCurrentState()); } @@ -509,11 +518,8 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_Active_002, TestSize.Level1) std::shared_ptr ability = nullptr; std::shared_ptr contextDeal = std::make_shared(); mockAbilityimpl->Init(application, record, ability, handler, token, contextDeal); - - AbilityLifecycleExecutor AbilityLifecycleExecutor_; mockAbilityimpl->ImplActive(); mockAbilityimpl->SetlifecycleState(AAFwk::ABILITY_STATE_SUSPENDED); - EXPECT_EQ(AAFwk::ABILITY_STATE_SUSPENDED, mockAbilityimpl->GetCurrentState()); } } @@ -550,11 +556,13 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_Inactive_001, TestSize.Level1) if (pMocKPageAbility != nullptr) { ability.reset(pMocKPageAbility); std::shared_ptr contextDeal = std::make_shared(); + std::shared_ptr applicationInfo = std::make_shared(); + contextDeal->SetApplicationInfo(applicationInfo); + contextDeal->SetAbilityInfo(abilityInfo); + pMocKPageAbility->AttachBaseContext(contextDeal); + application->AttachBaseContext(contextDeal); mockAbilityimpl->Init(application, record, ability, handler, token, contextDeal); - - AbilityLifecycleExecutor AbilityLifecycleExecutor_; mockAbilityimpl->ImplInactive(); - EXPECT_EQ(MockPageAbility::Event::ON_INACTIVE, pMocKPageAbility->state_); EXPECT_EQ(AAFwk::ABILITY_STATE_INACTIVE, mockAbilityimpl->GetCurrentState()); } @@ -590,11 +598,8 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_Inactive_002, TestSize.Level1) std::shared_ptr ability = nullptr; std::shared_ptr contextDeal = std::make_shared(); mockAbilityimpl->Init(application, record, ability, handler, token, contextDeal); - - AbilityLifecycleExecutor AbilityLifecycleExecutor_; mockAbilityimpl->ImplInactive(); mockAbilityimpl->SetlifecycleState(AAFwk::ABILITY_STATE_SUSPENDED); - EXPECT_EQ(AAFwk::ABILITY_STATE_SUSPENDED, mockAbilityimpl->GetCurrentState()); } } @@ -627,16 +632,15 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_Foreground_001, TestSize.Level1) std::shared_ptr handler = std::make_shared(eventRunner, abilityThread); std::shared_ptr ability = nullptr; MockPageAbility *pMocKPageAbility = new (std::nothrow) MockPageAbility(); + Want want; + pMocKPageAbility->OnForeground(want); EXPECT_NE(pMocKPageAbility, nullptr); if (pMocKPageAbility != nullptr) { ability.reset(pMocKPageAbility); std::shared_ptr contextDeal = std::make_shared(); mockAbilityimpl->Init(application, record, ability, handler, token, contextDeal); - - Want want; - AbilityLifecycleExecutor AbilityLifecycleExecutor_; EXPECT_EQ(MockPageAbility::Event::ON_FOREGROUND, pMocKPageAbility->state_); - EXPECT_EQ(AAFwk::ABILITY_STATE_INACTIVE, mockAbilityimpl->GetCurrentState()); + EXPECT_EQ(AAFwk::ABILITY_STATE_INITIAL, mockAbilityimpl->GetCurrentState()); } } } @@ -670,12 +674,9 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_Foreground_002, TestSize.Level1) std::shared_ptr ability = nullptr; std::shared_ptr contextDeal = std::make_shared(); mockAbilityimpl->Init(application, record, ability, handler, token, contextDeal); - Want want; - AbilityLifecycleExecutor AbilityLifecycleExecutor_; mockAbilityimpl->ImplForeground(want); mockAbilityimpl->SetlifecycleState(AAFwk::ABILITY_STATE_SUSPENDED); - EXPECT_EQ(AAFwk::ABILITY_STATE_SUSPENDED, mockAbilityimpl->GetCurrentState()); } } @@ -712,11 +713,13 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_Background_001, TestSize.Level1) if (pMocKPageAbility != nullptr) { ability.reset(pMocKPageAbility); std::shared_ptr contextDeal = std::make_shared(); + std::shared_ptr applicationInfo = std::make_shared(); + contextDeal->SetApplicationInfo(applicationInfo); + contextDeal->SetAbilityInfo(abilityInfo); + pMocKPageAbility->AttachBaseContext(contextDeal); + application->AttachBaseContext(contextDeal); mockAbilityimpl->Init(application, record, ability, handler, token, contextDeal); - - AbilityLifecycleExecutor AbilityLifecycleExecutor_; mockAbilityimpl->ImplBackground(); - EXPECT_EQ(MockPageAbility::Event::ON_BACKGROUND, pMocKPageAbility->state_); EXPECT_EQ(AAFwk::ABILITY_STATE_BACKGROUND, mockAbilityimpl->GetCurrentState()); } @@ -777,6 +780,8 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_New_Foreground_001, TestSize.Level1) std::shared_ptr application = std::make_shared(); std::shared_ptr abilityInfo = std::make_shared(); abilityInfo->name = "pageAbility"; + abilityInfo->isStageBasedModel = true; + abilityInfo->type = AppExecFwk::AbilityType::PAGE; sptr token = sptr(new (std::nothrow) MockAbilityToken()); EXPECT_NE(token, nullptr); if (token != nullptr) { @@ -792,6 +797,11 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_New_Foreground_001, TestSize.Level1) if (pMocKPageAbility != nullptr) { ability.reset(pMocKPageAbility); std::shared_ptr contextDeal = std::make_shared(); + std::shared_ptr applicationInfo = std::make_shared(); + contextDeal->SetApplicationInfo(applicationInfo); + contextDeal->SetAbilityInfo(abilityInfo); + pMocKPageAbility->AttachBaseContext(contextDeal); + application->AttachBaseContext(contextDeal); mockAbilityimpl->Init(application, record, ability, handler, token, contextDeal); Want want; mockAbilityimpl->ImplForeground(want); @@ -818,6 +828,8 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_New_Foreground_002, TestSize.Level1) std::shared_ptr application = std::make_shared(); std::shared_ptr abilityInfo = std::make_shared(); abilityInfo->name = "pageAbility"; + abilityInfo->isStageBasedModel = true; + abilityInfo->type = AppExecFwk::AbilityType::PAGE; sptr token = sptr(new (std::nothrow) MockAbilityToken()); EXPECT_NE(token, nullptr); if (token != nullptr) { @@ -833,6 +845,11 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_New_Foreground_002, TestSize.Level1) if (pMocKPageAbility != nullptr) { ability.reset(pMocKPageAbility); std::shared_ptr contextDeal = std::make_shared(); + std::shared_ptr applicationInfo = std::make_shared(); + contextDeal->SetApplicationInfo(applicationInfo); + contextDeal->SetAbilityInfo(abilityInfo); + pMocKPageAbility->AttachBaseContext(contextDeal); + application->AttachBaseContext(contextDeal); mockAbilityimpl->Init(application, record, ability, handler, token, contextDeal); Want want; mockAbilityimpl->ImplForeground(want); @@ -856,7 +873,7 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_New_Foreground_002, TestSize.Level1) */ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_New_Background_001, TestSize.Level1) { - GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_New_Foreground_001 start"; + GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_New_Background_001 start"; std::shared_ptr mockAbilityimpl = std::make_shared(); std::shared_ptr application = std::make_shared(); std::shared_ptr abilityInfo = std::make_shared(); @@ -876,10 +893,13 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_New_Background_001, TestSize.Level1) if (pMocKPageAbility != nullptr) { ability.reset(pMocKPageAbility); std::shared_ptr contextDeal = std::make_shared(); + std::shared_ptr applicationInfo = std::make_shared(); + contextDeal->SetApplicationInfo(applicationInfo); + contextDeal->SetAbilityInfo(abilityInfo); + pMocKPageAbility->AttachBaseContext(contextDeal); + application->AttachBaseContext(contextDeal); mockAbilityimpl->Init(application, record, ability, handler, token, contextDeal); - mockAbilityimpl->ImplBackground(); - EXPECT_EQ(MockPageAbility::Event::ON_BACKGROUND, pMocKPageAbility->state_); EXPECT_EQ(AAFwk::ABILITY_STATE_BACKGROUND, mockAbilityimpl->GetCurrentState()); } @@ -903,6 +923,8 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_New_Background_002, TestSize.Level1) std::shared_ptr application = std::make_shared(); std::shared_ptr abilityInfo = std::make_shared(); abilityInfo->name = "pageAbility"; + abilityInfo->isStageBasedModel = true; + abilityInfo->type = AppExecFwk::AbilityType::PAGE; sptr token = sptr(new (std::nothrow) MockAbilityToken()); EXPECT_NE(token, nullptr); if (token != nullptr) { @@ -918,12 +940,15 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_New_Background_002, TestSize.Level1) if (pMocKPageAbility != nullptr) { ability.reset(pMocKPageAbility); std::shared_ptr contextDeal = std::make_shared(); + std::shared_ptr applicationInfo = std::make_shared(); + contextDeal->SetApplicationInfo(applicationInfo); + contextDeal->SetAbilityInfo(abilityInfo); + pMocKPageAbility->AttachBaseContext(contextDeal); + application->AttachBaseContext(contextDeal); mockAbilityimpl->Init(application, record, ability, handler, token, contextDeal); - mockAbilityimpl->ImplBackground(); mockAbilityimpl->ImplBackground(); mockAbilityimpl->ImplBackground(); - EXPECT_EQ(MockPageAbility::Event::ON_BACKGROUND, pMocKPageAbility->state_); EXPECT_EQ(AAFwk::ABILITY_STATE_BACKGROUND_NEW, mockAbilityimpl->GetCurrentState()); } @@ -947,6 +972,8 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_New_Foreground_Background_001, TestS std::shared_ptr application = std::make_shared(); std::shared_ptr abilityInfo = std::make_shared(); abilityInfo->name = "pageAbility"; + abilityInfo->isStageBasedModel = true; + abilityInfo->type = AppExecFwk::AbilityType::PAGE; sptr token = sptr(new (std::nothrow) MockAbilityToken()); EXPECT_NE(token, nullptr); if (token != nullptr) { @@ -962,12 +989,15 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_New_Foreground_Background_001, TestS if (pMocKPageAbility != nullptr) { ability.reset(pMocKPageAbility); std::shared_ptr contextDeal = std::make_shared(); + std::shared_ptr applicationInfo = std::make_shared(); + contextDeal->SetApplicationInfo(applicationInfo); + contextDeal->SetAbilityInfo(abilityInfo); + pMocKPageAbility->AttachBaseContext(contextDeal); + application->AttachBaseContext(contextDeal); mockAbilityimpl->Init(application, record, ability, handler, token, contextDeal); - Want want; mockAbilityimpl->ImplForeground(want); mockAbilityimpl->ImplBackground(); - EXPECT_EQ(MockPageAbility::Event::ON_BACKGROUND, pMocKPageAbility->state_); EXPECT_EQ(AAFwk::ABILITY_STATE_BACKGROUND_NEW, mockAbilityimpl->GetCurrentState()); } @@ -991,6 +1021,8 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_New_Foreground_Background_002, TestS std::shared_ptr application = std::make_shared(); std::shared_ptr abilityInfo = std::make_shared(); abilityInfo->name = "pageAbility"; + abilityInfo->isStageBasedModel = true; + abilityInfo->type = AppExecFwk::AbilityType::PAGE; sptr token = sptr(new (std::nothrow) MockAbilityToken()); EXPECT_NE(token, nullptr); if (token != nullptr) { @@ -1006,13 +1038,16 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_New_Foreground_Background_002, TestS if (pMocKPageAbility != nullptr) { ability.reset(pMocKPageAbility); std::shared_ptr contextDeal = std::make_shared(); + std::shared_ptr applicationInfo = std::make_shared(); + contextDeal->SetApplicationInfo(applicationInfo); + contextDeal->SetAbilityInfo(abilityInfo); + pMocKPageAbility->AttachBaseContext(contextDeal); + application->AttachBaseContext(contextDeal); mockAbilityimpl->Init(application, record, ability, handler, token, contextDeal); - Want want; mockAbilityimpl->ImplForeground(want); mockAbilityimpl->ImplBackground(); mockAbilityimpl->ImplForeground(want); - EXPECT_EQ(MockPageAbility::Event::ON_FOREGROUND, pMocKPageAbility->state_); EXPECT_EQ(AAFwk::ABILITY_STATE_FOREGROUND_NEW, mockAbilityimpl->GetCurrentState()); } @@ -1036,6 +1071,8 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_New_Foreground_Background_003, TestS std::shared_ptr application = std::make_shared(); std::shared_ptr abilityInfo = std::make_shared(); abilityInfo->name = "pageAbility"; + abilityInfo->isStageBasedModel = true; + abilityInfo->type = AppExecFwk::AbilityType::PAGE; sptr token = sptr(new (std::nothrow) MockAbilityToken()); EXPECT_NE(token, nullptr); if (token != nullptr) { @@ -1051,12 +1088,15 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_New_Foreground_Background_003, TestS if (pMocKPageAbility != nullptr) { ability.reset(pMocKPageAbility); std::shared_ptr contextDeal = std::make_shared(); + std::shared_ptr applicationInfo = std::make_shared(); + contextDeal->SetApplicationInfo(applicationInfo); + contextDeal->SetAbilityInfo(abilityInfo); + pMocKPageAbility->AttachBaseContext(contextDeal); + application->AttachBaseContext(contextDeal); mockAbilityimpl->Init(application, record, ability, handler, token, contextDeal); - Want want; mockAbilityimpl->ImplBackground(); mockAbilityimpl->ImplForeground(want); - EXPECT_EQ(MockPageAbility::Event::ON_FOREGROUND, pMocKPageAbility->state_); EXPECT_EQ(AAFwk::ABILITY_STATE_FOREGROUND_NEW, mockAbilityimpl->GetCurrentState()); } @@ -1080,6 +1120,8 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_New_Foreground_Background_004, TestS std::shared_ptr application = std::make_shared(); std::shared_ptr abilityInfo = std::make_shared(); abilityInfo->name = "pageAbility"; + abilityInfo->isStageBasedModel = true; + abilityInfo->type = AppExecFwk::AbilityType::PAGE; sptr token = sptr(new (std::nothrow) MockAbilityToken()); EXPECT_NE(token, nullptr); if (token != nullptr) { @@ -1095,13 +1137,16 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_New_Foreground_Background_004, TestS if (pMocKPageAbility != nullptr) { ability.reset(pMocKPageAbility); std::shared_ptr contextDeal = std::make_shared(); + std::shared_ptr applicationInfo = std::make_shared(); + contextDeal->SetApplicationInfo(applicationInfo); + contextDeal->SetAbilityInfo(abilityInfo); + pMocKPageAbility->AttachBaseContext(contextDeal); + application->AttachBaseContext(contextDeal); mockAbilityimpl->Init(application, record, ability, handler, token, contextDeal); - Want want; mockAbilityimpl->ImplBackground(); mockAbilityimpl->ImplForeground(want); mockAbilityimpl->ImplBackground(); - EXPECT_EQ(MockPageAbility::Event::ON_BACKGROUND, pMocKPageAbility->state_); EXPECT_EQ(AAFwk::ABILITY_STATE_BACKGROUND_NEW, mockAbilityimpl->GetCurrentState()); } @@ -1137,7 +1182,6 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_DispatchSaveAbilityState_001, TestSi std::shared_ptr ability = std::make_shared(); std::shared_ptr contextDeal = std::make_shared(); mockAbilityimpl->Init(application, record, ability, handler, token, contextDeal); - AbilityLifecycleExecutor AbilityLifecycleExecutor_; mockAbilityimpl->DispatchSaveAbilityState(); } } @@ -1279,12 +1323,8 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_ConnectAbility_001, TestSize.Level1) ability.reset(pMocKPageAbility); std::shared_ptr contextDeal = std::make_shared(); mockAbilityimpl->Init(application, record, ability, handler, token, contextDeal); - Want want; - - AbilityLifecycleExecutor AbilityLifecycleExecutor_; mockAbilityimpl->ConnectAbility(want); - EXPECT_EQ(MockPageAbility::Event::ON_ACTIVE, pMocKPageAbility->state_); EXPECT_EQ(AAFwk::ABILITY_STATE_ACTIVE, mockAbilityimpl->GetCurrentState()); EXPECT_EQ(nullptr, mockAbilityimpl->ConnectAbility(want)); @@ -1321,10 +1361,7 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_ConnectAbility_002, TestSize.Level1) std::shared_ptr ability = nullptr; std::shared_ptr contextDeal = std::make_shared(); mockAbilityimpl->Init(application, record, ability, handler, token, contextDeal); - Want want; - - AbilityLifecycleExecutor AbilityLifecycleExecutor_; mockAbilityimpl->ConnectAbility(want); mockAbilityimpl->SetlifecycleState(AAFwk::ABILITY_STATE_SUSPENDED); @@ -1366,13 +1403,10 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_CommandAbility_001, TestSize.Level1) ability.reset(pMocKPageAbility); std::shared_ptr contextDeal = std::make_shared(); mockAbilityimpl->Init(application, record, ability, handler, token, contextDeal); - Want want; bool restart = true; int startId = 1; - AbilityLifecycleExecutor AbilityLifecycleExecutor_; mockAbilityimpl->CommandAbility(want, restart, startId); - EXPECT_EQ(MockPageAbility::Event::ON_ACTIVE, pMocKPageAbility->state_); EXPECT_EQ(AAFwk::ABILITY_STATE_ACTIVE, mockAbilityimpl->GetCurrentState()); } @@ -1409,16 +1443,11 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_CommandAbility_002, TestSize.Level1) std::shared_ptr ability = nullptr; std::shared_ptr contextDeal = std::make_shared(); AbilityImpl_->Init(application, record, ability, handler, token, contextDeal); - Want want; - bool restart = true; int startId = 1; - - AbilityLifecycleExecutor AbilityLifecycleExecutor_; AbilityImpl_->CommandAbility(want, restart, startId); mockAbilityimpl->SetlifecycleState(AAFwk::ABILITY_STATE_SUSPENDED); - EXPECT_EQ(AAFwk::ABILITY_STATE_SUSPENDED, mockAbilityimpl->MockGetCurrentState()); } } @@ -1921,7 +1950,6 @@ HWTEST_F(AbilityImplTest, AaFwk_AbilityImpl_CheckAndRestore_001, TestSize.Level1 ability.reset(pMocKPageAbility); std::shared_ptr contextDeal = std::make_shared(); mockAbilityimpl->Init(application, record, ability, handler, token, contextDeal); - EXPECT_FALSE(mockAbilityimpl->CheckAndRestore()); PacMap inState; mockAbilityimpl->DispatchRestoreAbilityState(inState); diff --git a/frameworks/kits/ability/native/test/unittest/ability_test.cpp b/frameworks/kits/ability/native/test/unittest/ability_test.cpp index 7bd0af5b4b43dd43a554dc39474d479194fe2e2a..8ba55aa293af57f45710c25baba13b30c855ccb2 100644 --- a/frameworks/kits/ability/native/test/unittest/ability_test.cpp +++ b/frameworks/kits/ability/native/test/unittest/ability_test.cpp @@ -741,14 +741,18 @@ HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnBackground_0100, Function | MediumTest HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnBackground_0200, Function | MediumTest | Level3) { GTEST_LOG_(INFO) << "AaFwk_Ability_OnBackground_0200 start"; - + std::shared_ptr abilityInfo = std::make_shared(); + std::shared_ptr application = nullptr; + std::shared_ptr handler = nullptr; + sptr token = nullptr; + ability_->Init(abilityInfo, application, handler, token); ability_->OnBackground(); AbilityLifecycleExecutor::LifecycleState state = ability_->GetState(); std::shared_ptr lifeCycle = ability_->GetLifecycle(); - EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::UNINITIALIZED, state); - EXPECT_EQ(nullptr, lifeCycle); + EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::BACKGROUND, state); + EXPECT_TRUE(lifeCycle); GTEST_LOG_(INFO) << "AaFwk_Ability_OnBackground_0200 end"; } @@ -776,8 +780,9 @@ HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnBackground_0300, Function | MediumTest std::shared_ptr lifeCycle = ability_->GetLifecycle(); LifeCycle::Event lifeCycleState = lifeCycle->GetLifecycleState(); - EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::BACKGROUND_NEW, state); - EXPECT_EQ(LifeCycle::Event::ON_BACKGROUND, lifeCycleState); + // Sence is nullptr, so lifecycle schedule failed. + EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::INITIAL, state); + EXPECT_EQ(LifeCycle::Event::UNDEFINED, lifeCycleState); GTEST_LOG_(INFO) << "AaFwk_Ability_OBackground_0300 end"; } diff --git a/frameworks/kits/ability/native/test/unittest/ability_thread_test.cpp b/frameworks/kits/ability/native/test/unittest/ability_thread_test.cpp index e915a2b1b190515f689aa6033adf60c7d099499c..eb25a89e2a85e0f1c607eae5969c2f24231f8c31 100644 --- a/frameworks/kits/ability/native/test/unittest/ability_thread_test.cpp +++ b/frameworks/kits/ability/native/test/unittest/ability_thread_test.cpp @@ -398,6 +398,16 @@ HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_ScheduleConnectAbility_0200, Fun AbilityThread *abilitythread = new (std::nothrow) AbilityThread(); EXPECT_NE(abilitythread, nullptr); if (abilitythread != nullptr) { + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "MockPageAbility"; + abilityInfo->type = AbilityType::PAGE; + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + std::shared_ptr application = std::make_shared(); + std::shared_ptr abilityRecord = + std::make_shared(abilityInfo, token); + std::shared_ptr mainRunner = EventRunner::Create(abilityInfo->name); + abilitythread->Attach(application, abilityRecord, mainRunner, nullptr); + Want want; abilitythread->ScheduleConnectAbility(want); } @@ -449,7 +459,15 @@ HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_ScheduleDisconnectAbility_0200, AbilityThread *abilitythread = new (std::nothrow) AbilityThread(); EXPECT_NE(abilitythread, nullptr); if (abilitythread != nullptr) { - std::shared_ptr abilityimpl = std::make_shared(); + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "MockPageAbility"; + abilityInfo->type = AbilityType::PAGE; + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + std::shared_ptr application = std::make_shared(); + std::shared_ptr abilityRecord = + std::make_shared(abilityInfo, token); + std::shared_ptr mainRunner = EventRunner::Create(abilityInfo->name); + abilitythread->Attach(application, abilityRecord, mainRunner, nullptr); Want want; abilitythread->ScheduleDisconnectAbility(want); @@ -506,10 +524,19 @@ HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_ScheduleCommandAbility_0200, Fun AbilityThread *abilitythread = new (std::nothrow) AbilityThread(); EXPECT_NE(abilitythread, nullptr); if (abilitythread != nullptr) { + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "MockPageAbility"; + abilityInfo->type = AbilityType::PAGE; + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + std::shared_ptr application = std::make_shared(); + std::shared_ptr abilityRecord = + std::make_shared(abilityInfo, token); + std::shared_ptr mainRunner = EventRunner::Create(abilityInfo->name); + abilitythread->Attach(application, abilityRecord, mainRunner, nullptr); + Want want; bool restart = true; int startId = 0; - abilitythread->ScheduleCommandAbility(want, restart, startId); } GTEST_LOG_(INFO) << "AaFwk_AbilityThread_ScheduleCommandAbility_0200 end"; @@ -563,7 +590,15 @@ HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_SendResult_0200, Function | Medi AbilityThread *abilitythread = new (std::nothrow) AbilityThread(); EXPECT_NE(abilitythread, nullptr); if (abilitythread != nullptr) { - std::shared_ptr abilityimpl = std::make_shared(); + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "MockPageAbility"; + abilityInfo->type = AbilityType::PAGE; + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + std::shared_ptr application = std::make_shared(); + std::shared_ptr abilityRecord = + std::make_shared(abilityInfo, token); + std::shared_ptr mainRunner = EventRunner::Create(abilityInfo->name); + abilitythread->Attach(application, abilityRecord, mainRunner, nullptr); int requestCode = 0; int resultCode = 0; diff --git a/frameworks/kits/ability/native/test/unittest/data_ability_result_test.cpp b/frameworks/kits/ability/native/test/unittest/data_ability_result_test.cpp index 9d2a1fa9251674d53fea210d885eb0ecc489e8aa..dbc22a505236b63c658061a0ed7c2d509244e039 100644 --- a/frameworks/kits/ability/native/test/unittest/data_ability_result_test.cpp +++ b/frameworks/kits/ability/native/test/unittest/data_ability_result_test.cpp @@ -31,7 +31,7 @@ public: ~DataAbilityResultTest() {} - std::shared_ptr Base_ = nullptr; + std::shared_ptr base_ = nullptr; static void SetUpTestCase(void); static void TearDownTestCase(void); @@ -47,11 +47,13 @@ void DataAbilityResultTest::TearDownTestCase(void) void DataAbilityResultTest::SetUp(void) { - Base_ = std::make_shared(COUNT_NULL); + base_ = std::make_shared(COUNT_NULL); } void DataAbilityResultTest::TearDown(void) -{} +{ + base_ = nullptr; +} /** * @tc.number: @@ -72,10 +74,10 @@ HWTEST_F(DataAbilityResultTest, AppExecFwk_DataAbilityResult_DataAbilityResult01 EXPECT_EQ(SET_COUNT, test3.GetCount()); EXPECT_EQ(uri.ToString(), test3.GetUri().ToString()); - *Base_ = test3; - if (Base_) { + *base_ = test3; + if (base_) { Parcel in; - Base_->Marshalling(in); + base_->Marshalling(in); DataAbilityResult test4(in); EXPECT_EQ(SET_COUNT, test4.GetCount()); EXPECT_EQ(uri.ToString(), test4.GetUri().ToString()); @@ -128,8 +130,8 @@ HWTEST_F(DataAbilityResultTest, AppExecFwk_DataAbilityResult_Get0100, Function | */ HWTEST_F(DataAbilityResultTest, AppExecFwk_DataAbilityResult_Get0200, Function | MediumTest | Level1) { - EXPECT_EQ(true, Base_->GetUri().ToString().empty()); - EXPECT_EQ(COUNT_NULL, Base_->GetCount()); + EXPECT_EQ(true, base_->GetUri().ToString().empty()); + EXPECT_EQ(COUNT_NULL, base_->GetCount()); } /** @@ -140,8 +142,8 @@ HWTEST_F(DataAbilityResultTest, AppExecFwk_DataAbilityResult_Get0200, Function | HWTEST_F(DataAbilityResultTest, AppExecFwk_DataAbilityResult_CreateFromParcel0100, Function | MediumTest | Level1) { Parcel in; - Base_->Marshalling(in); - DataAbilityResult *ptr = Base_->CreateFromParcel(in); + base_->Marshalling(in); + DataAbilityResult *ptr = base_->CreateFromParcel(in); if (ptr != nullptr) { EXPECT_EQ(true, ptr->GetUri().ToString().empty()); diff --git a/frameworks/kits/appkit/BUILD.gn b/frameworks/kits/appkit/BUILD.gn index 372c6a06c4623140762b0b593ec1e119cda0cb84..b529e6b69df108c18a83cd6bfd77033b8e73f7d4 100644 --- a/frameworks/kits/appkit/BUILD.gn +++ b/frameworks/kits/appkit/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -95,7 +95,6 @@ ohos_shared_library("appkit_native") { "${aafwk_path}/frameworks/kits/appkit/native/ability_runtime/context", "${aafwk_path}/frameworks/kits/appkit/native", "${aafwk_path}/frameworks/kits/ability/native/include", - "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/include", "${aafwk_path}/interfaces/innerkits/ability_manager/include", "${aafwk_path}/services/abilitymgr/include", "//utils/native/base/include", @@ -116,6 +115,8 @@ ohos_shared_library("appkit_native") { public_configs = [ ":appkit_public_config" ] sources = [ + "${aafwk_path}/frameworks/kits/appkit/native/ability_runtime/app/ability_stage.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage.cpp", "${aafwk_path}/frameworks/kits/appkit/native/app/src/ability_manager.cpp", "${aafwk_path}/frameworks/kits/appkit/native/app/src/ability_record_mgr.cpp", "${aafwk_path}/frameworks/kits/appkit/native/app/src/app_loader.cpp", @@ -136,6 +137,7 @@ ohos_shared_library("appkit_native") { "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/src/test_runner.cpp", "${aafwk_path}/frameworks/kits/appkit/native/ability_runtime/app/ability_stage.cpp", "${aafwk_path}/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage_context.cpp", "${aafwk_path}/frameworks/kits/appkit/native/app/src/context_deal.cpp", "${aafwk_path}/frameworks/kits/appkit/native/app/src/main_thread.cpp", "${aafwk_path}/frameworks/kits/appkit/native/app/src/ohos_application.cpp", @@ -149,6 +151,7 @@ ohos_shared_library("appkit_native") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ + ":appkit_delegator", "${aafwk_path}/common/task_dispatcher:task_dispatcher", "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", "${aafwk_path}/frameworks/kits/appkit:app_context", @@ -159,6 +162,7 @@ ohos_shared_library("appkit_native") { "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "${innerkits_path}/uri_permission:uri_permission_mgr", "//base/hiviewdfx/faultloggerd/interfaces/innerkits/dump_catcher:lib_dfx_dump_catcher", "//base/hiviewdfx/faultloggerd/interfaces/innerkits/faultloggerd_client:libfaultloggerd", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", @@ -173,8 +177,10 @@ ohos_shared_library("appkit_native") { "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", ] external_deps = [ + "ability_base:configuration", "ability_runtime:runtime", "bytrace_standard:bytrace_core", + "hisysevent_native:libhisysevent", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "napi:ace_napi", @@ -246,3 +252,63 @@ ohos_shared_library("app_context") { part_name = "ability_runtime" } + +# build so +ohos_shared_library("appkit_delegator") { + include_dirs = [ + "${appexecfwk_path}/common/log/include", + "${aafwk_path}/frameworks/kits/appkit/native/ability_runtime/app", + "${aafwk_path}/frameworks/kits/appkit/native/ability_runtime/context", + "${aafwk_path}/frameworks/kits/appkit/native", + "${aafwk_path}/frameworks/kits/ability/native/include", + "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/include", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "//utils/native/base/include", + ] + + configs = [ ":appkit_config" ] + + public_configs = [ ":appkit_public_config" ] + + sources = [ + "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator_args.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator_registry.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/src/delegator_thread.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/src/iability_monitor.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/src/runner_runtime/js_test_runner.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/src/shell_cmd_result.cpp", + "${aafwk_path}/frameworks/kits/appkit/native/ability_delegator/src/test_runner.cpp", + "//foundation/aafwk/standard/tools/aa/src/shell_command_result.cpp", + "//foundation/aafwk/standard/tools/aa/src/test_observer_proxy.cpp", + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + deps = [ + "${aafwk_path}/frameworks/kits/appkit:app_context", + "${aafwk_path}/interfaces/innerkits/ability_manager:ability_manager", + "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${aafwk_path}/interfaces/innerkits/want:want", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//third_party/icu/icu4c:shared_icuuc", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_runtime:runtime", + "bytrace_standard:bytrace_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + public_deps = [ "//foundation/ace/napi:ace_napi" ] + + part_name = "ability_runtime" +} diff --git a/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator.h b/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator.h index d970c48d466338d8313cb1069bbde592b72f6d55..0a0a1f084a912bdbc4e1fbf090bfd20cef5fc60a 100644 --- a/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator.h +++ b/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator.h @@ -19,24 +19,21 @@ #include #include #include -#include #include -#include #include +#include "ability_delegator_infos.h" #include "iability_monitor.h" #include "delegator_thread.h" #include "shell_cmd_result.h" #include "test_runner.h" -#include "ability_lifecycle_callbacks.h" #include "ability_lifecycle_executor.h" #include "ability_runtime/context/context.h" -#include "main_thread.h" namespace OHOS { namespace AppExecFwk { -class AbilityDelegator : public AbilityLifecycleCallbacks, public std::enable_shared_from_this { +class AbilityDelegator : public std::enable_shared_from_this { public: enum class AbilityState : uint8_t { UNINITIALIZED = 0, @@ -46,24 +43,11 @@ public: STOPED }; - using ability_property = std::tuple, std::shared_ptr, AbilityDelegator::AbilityState>; - using list_ability_property = std::list; - public: - AbilityDelegator(const sptr &mainThread, std::unique_ptr runner, + AbilityDelegator(const std::shared_ptr &context, std::unique_ptr runner, const sptr &observer); ~AbilityDelegator(); - void Init(); - - void OnAbilityStart(const std::shared_ptr &ability) override; - void OnAbilityInactive(const std::shared_ptr &ability) override; - void OnAbilityBackground(const std::shared_ptr &ability) override; - void OnAbilityForeground(const std::shared_ptr &ability) override; - void OnAbilityActive(const std::shared_ptr &ability) override; - void OnAbilityStop(const std::shared_ptr &ability) override; - void OnAbilitySaveState(const PacMap &outState) override; - void AddAbilityMonitor(const std::shared_ptr &monitor); void RemoveAbilityMonitor(const std::shared_ptr &monitor); void ClearAllMonitors(); @@ -88,35 +72,29 @@ public: void Print(const std::string &msg); - void PrePerformStart(const std::shared_ptr &ability); - void PostPerformStart(const std::shared_ptr &ability); - void PrePerformScenceCreated(const std::shared_ptr &ability); - void PrePerformScenceRestored(const std::shared_ptr &ability); - void PrePerformScenceDestroyed(const std::shared_ptr &ability); - void PrePerformForeground(const std::shared_ptr &ability); - void PrePerformBackground(const std::shared_ptr &ability); - void PrePerformStop(const std::shared_ptr &ability); + void PostPerformStart(const std::shared_ptr &ability); + void PostPerformScenceCreated(const std::shared_ptr &ability); + void PostPerformScenceRestored(const std::shared_ptr &ability); + void PostPerformScenceDestroyed(const std::shared_ptr &ability); + void PostPerformForeground(const std::shared_ptr &ability); + void PostPerformBackground(const std::shared_ptr &ability); + void PostPerformStop(const std::shared_ptr &ability); -private: - AbilityDelegator::AbilityState ConvertAbilityState(const AbilityLifecycleExecutor::LifecycleState lifecycleState); - void ProcessAbilityProperties(const std::shared_ptr &ability); - sptr GetAbilityToken(const std::shared_ptr &ability); - std::optional DoesPropertyExist(const sptr &token); - void FinishUserTest(const int32_t resultCode); + void FinishUserTest(const std::string &msg, const int32_t resultCode); private: - static constexpr size_t FIRST_PROPERTY {0}; - static constexpr size_t SECOND_PROPERTY {1}; - static constexpr size_t THIRD_PROPERTY {2}; + AbilityDelegator::AbilityState ConvertAbilityState(const AbilityLifecycleExecutor::LifecycleState lifecycleState); + void ProcessAbilityProperties(const std::shared_ptr &ability); + std::shared_ptr DoesPropertyExist(const sptr &token); private: - sptr mainThread_; + std::shared_ptr appContext_; std::unique_ptr testRunner_; + sptr observer_; + std::unique_ptr delegatorThread_; - list_ability_property abilityProperties_; + std::list> abilityProperties_; std::vector> abilityMonitors_; - std::shared_ptr appContext_; - sptr observer_; std::mutex mutexMonitor_; std::mutex mutexAbilityProperties_; diff --git a/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator_args.h b/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator_args.h index f091705abed7c91657308b4a66890a429ce17d31..8544f749a715d65acd871852d3308165277ab109 100644 --- a/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator_args.h +++ b/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator_args.h @@ -25,8 +25,10 @@ namespace OHOS { namespace AppExecFwk { class AbilityDelegatorArgs { public: + static const std::string KEY_TEST_BUNDLE_NAME; static const std::string KEY_TEST_RUNNER_CLASS; static const std::string KEY_TEST_CASE; + static const std::string KEY_TEST_WAIT_TIMEOUT; public: AbilityDelegatorArgs(); diff --git a/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator_infos.h b/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator_infos.h new file mode 100644 index 0000000000000000000000000000000000000000..f7f69cc39f5fcd160fd408bd89e001476e5b8ccd --- /dev/null +++ b/frameworks/kits/appkit/native/ability_delegator/include/ability_delegator_infos.h @@ -0,0 +1,33 @@ +/* + * 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_DELEGATOR_INFOS_H +#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_DELEGATOR_INFOS_H + +#include +#include "ability_lifecycle_executor.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +struct ADelegatorAbilityProperty { + sptr token_; + std::string name_; + AbilityLifecycleExecutor::LifecycleState lifecycleState_ {AbilityLifecycleExecutor::LifecycleState::UNINITIALIZED}; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_DELEGATOR_INFOS_H diff --git a/frameworks/kits/appkit/native/ability_delegator/include/iability_monitor.h b/frameworks/kits/appkit/native/ability_delegator/include/iability_monitor.h index 00a01e0dea99bb423aa8dd85b955b3e752f6c8b9..337ab3605670330c4e3bb2a11d69fb70ab3d887f 100644 --- a/frameworks/kits/appkit/native/ability_delegator/include/iability_monitor.h +++ b/frameworks/kits/appkit/native/ability_delegator/include/iability_monitor.h @@ -17,14 +17,11 @@ #define FOUNDATION_APPEXECFWK_OHOS_IABILITY_MONITORE_H #include -#include #include #include #include -#include -#include "ability.h" -#include "want.h" +#include "ability_delegator_infos.h" namespace OHOS { namespace AppExecFwk { @@ -36,10 +33,10 @@ public: explicit IAbilityMonitor(const std::string &abilityName); virtual ~IAbilityMonitor() = default; - virtual bool Match(const std::shared_ptr &ability, const Want &want); + virtual bool Match(const std::shared_ptr &ability, bool isNotify = false); - virtual std::shared_ptr waitForAbility(); - virtual std::shared_ptr waitForAbility(const int64_t timeoutMs); + virtual std::shared_ptr waitForAbility(); + virtual std::shared_ptr waitForAbility(const int64_t timeoutMs); virtual void OnAbilityStart(); virtual void OnAbilityForeground(); @@ -52,7 +49,7 @@ public: private: std::string abilityName_; - std::shared_ptr matchedAbility_; + std::shared_ptr matchedAbility_; std::condition_variable cvMatch_; std::mutex mMatch_; 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 471cda75eba6e0f6cb6eee630d37cf392ca58898..81bd3b47ed29ff11623f2a31ec3096c8e7779ad5 100644 --- a/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator.cpp +++ b/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator.cpp @@ -23,67 +23,12 @@ namespace OHOS { namespace AppExecFwk { -AbilityDelegator::AbilityDelegator(const sptr &mainThread, std::unique_ptr runner, - const sptr &observer) - : mainThread_(mainThread), testRunner_(std::move(runner)), observer_(observer) +AbilityDelegator::AbilityDelegator(const std::shared_ptr &context, + std::unique_ptr runner, const sptr &observer) + : appContext_(context), testRunner_(std::move(runner)), observer_(observer) {} AbilityDelegator::~AbilityDelegator() -{ - if (mainThread_) { - auto app = mainThread_->GetApplication(); - if (app) { - app->UnregisterAbilityLifecycleCallbacks(shared_from_this()); - } - } -} - -void AbilityDelegator::Init() -{ - APP_LOGI("Enter"); - - if (!mainThread_) { - APP_LOGE("Invalid mainThread"); - return; - } - - auto app = mainThread_->GetApplication(); - if (!app) { - APP_LOGE("Invalid application"); - return; - } - - appContext_ = app->GetAppContext(); - app->RegisterAbilityLifecycleCallbacks(shared_from_this()); -} - -void AbilityDelegator::OnAbilityStart(const std::shared_ptr &ability) -{ - ProcessAbilityProperties(ability); -} - -void AbilityDelegator::OnAbilityInactive(const std::shared_ptr &ability) -{} - -void AbilityDelegator::OnAbilityBackground(const std::shared_ptr &ability) -{ - ProcessAbilityProperties(ability); -} - -void AbilityDelegator::OnAbilityForeground(const std::shared_ptr &ability) -{ - ProcessAbilityProperties(ability); -} - -void AbilityDelegator::OnAbilityActive(const std::shared_ptr &ability) -{} - -void AbilityDelegator::OnAbilityStop(const std::shared_ptr &ability) -{ - ProcessAbilityProperties(ability); -} - -void AbilityDelegator::OnAbilitySaveState(const PacMap &outState) {} void AbilityDelegator::AddAbilityMonitor(const std::shared_ptr &monitor) @@ -144,7 +89,7 @@ sptr AbilityDelegator::WaitAbilityMonitor(const std::shared_ptrtoken_; } sptr AbilityDelegator::WaitAbilityMonitor( @@ -163,7 +108,7 @@ sptr AbilityDelegator::WaitAbilityMonitor( return {}; } - return GetAbilityToken(obtainedAbility); + return obtainedAbility->token_; } std::shared_ptr AbilityDelegator::GetAppContext() const @@ -185,7 +130,7 @@ AbilityDelegator::AbilityState AbilityDelegator::GetAbilityState(const sptr(existedProperty.value()); + return ConvertAbilityState(existedProperty->lifecycleState_); } sptr AbilityDelegator::GetCurrentTopAbility() @@ -249,8 +194,9 @@ bool AbilityDelegator::DoAbilityForeground(const sptr &token) return false; } - if (AAFwk::AbilityManagerClient::GetInstance()->DelegatorDoAbilityForeground(token)) { - APP_LOGE("Failed to call DelegatorDoAbilityForeground"); + auto ret = AAFwk::AbilityManagerClient::GetInstance()->DelegatorDoAbilityForeground(token); + if (ret) { + APP_LOGE("Failed to call DelegatorDoAbilityForeground, reson : %{public}d", ret); return false; } @@ -264,8 +210,9 @@ bool AbilityDelegator::DoAbilityBackground(const sptr &token) return false; } - if (AAFwk::AbilityManagerClient::GetInstance()->DelegatorDoAbilityBackground(token)) { - APP_LOGE("Failed to call DelegatorDoAbilityBackground"); + auto ret = AAFwk::AbilityManagerClient::GetInstance()->DelegatorDoAbilityBackground(token); + if (ret) { + APP_LOGE("Failed to call DelegatorDoAbilityBackground, reson : %{public}d", ret); return false; } @@ -293,6 +240,7 @@ std::unique_ptr AbilityDelegator::ExecuteShellCommand(const std: void AbilityDelegator::Print(const std::string &msg) { + APP_LOGI("message to print : %{public}s", msg.data()); auto testObserver = iface_cast(observer_); if (!testObserver) { APP_LOGW("Invalid testObserver"); @@ -302,35 +250,14 @@ void AbilityDelegator::Print(const std::string &msg) testObserver->TestStatus(msg, 0); } -void AbilityDelegator::PrePerformStart(const std::shared_ptr &ability) +void AbilityDelegator::PostPerformStart(const std::shared_ptr &ability) { if (!ability) { APP_LOGW("Invalid input parameter"); return; } - std::unique_lock lck(mutexMonitor_); - if (abilityMonitors_.empty()) { - APP_LOGW("Empty abilityMonitors"); - return; - } - - for (auto &monitor : abilityMonitors_) { - if (!monitor) { - continue; - } - - monitor->Match(ability, {}); - monitor->OnAbilityStart(); - } -} - -void AbilityDelegator::PostPerformStart(const std::shared_ptr &ability) -{ - if (!ability) { - APP_LOGW("Invalid input parameter"); - return; - } + ProcessAbilityProperties(ability); std::unique_lock lck(mutexMonitor_); if (abilityMonitors_.empty()) { @@ -343,17 +270,21 @@ void AbilityDelegator::PostPerformStart(const std::shared_ptr &ability) continue; } - monitor->Match(ability, {}); + if (monitor->Match(ability, true)) { + monitor->OnAbilityStart(); + } } } -void AbilityDelegator::PrePerformScenceCreated(const std::shared_ptr &ability) +void AbilityDelegator::PostPerformScenceCreated(const std::shared_ptr &ability) { if (!ability) { APP_LOGW("Invalid input parameter"); return; } + ProcessAbilityProperties(ability); + std::unique_lock lck(mutexMonitor_); if (abilityMonitors_.empty()) { APP_LOGW("Empty abilityMonitors"); @@ -365,18 +296,21 @@ void AbilityDelegator::PrePerformScenceCreated(const std::shared_ptr &a continue; } - monitor->Match(ability, {}); - monitor->OnWindowStageCreate(); + if (monitor->Match(ability)) { + monitor->OnWindowStageCreate(); + } } } -void AbilityDelegator::PrePerformScenceRestored(const std::shared_ptr &ability) +void AbilityDelegator::PostPerformScenceRestored(const std::shared_ptr &ability) { if (!ability) { APP_LOGW("Invalid input parameter"); return; } + ProcessAbilityProperties(ability); + std::unique_lock lck(mutexMonitor_); if (abilityMonitors_.empty()) { APP_LOGW("Empty abilityMonitors"); @@ -388,18 +322,21 @@ void AbilityDelegator::PrePerformScenceRestored(const std::shared_ptr & continue; } - monitor->Match(ability, {}); - monitor->OnWindowStageRestore(); + if (monitor->Match(ability)) { + monitor->OnWindowStageRestore(); + } } } -void AbilityDelegator::PrePerformScenceDestroyed(const std::shared_ptr &ability) +void AbilityDelegator::PostPerformScenceDestroyed(const std::shared_ptr &ability) { if (!ability) { APP_LOGW("Invalid input parameter"); return; } + ProcessAbilityProperties(ability); + std::unique_lock lck(mutexMonitor_); if (abilityMonitors_.empty()) { APP_LOGW("Empty abilityMonitors"); @@ -411,18 +348,21 @@ void AbilityDelegator::PrePerformScenceDestroyed(const std::shared_ptr continue; } - monitor->Match(ability, {}); - monitor->OnWindowStageDestroy(); + if (monitor->Match(ability)) { + monitor->OnWindowStageDestroy(); + } } } -void AbilityDelegator::PrePerformForeground(const std::shared_ptr &ability) +void AbilityDelegator::PostPerformForeground(const std::shared_ptr &ability) { if (!ability) { APP_LOGW("Invalid input parameter"); return; } + ProcessAbilityProperties(ability); + std::unique_lock lck(mutexMonitor_); if (abilityMonitors_.empty()) { APP_LOGW("Empty abilityMonitors"); @@ -434,18 +374,21 @@ void AbilityDelegator::PrePerformForeground(const std::shared_ptr &abil continue; } - monitor->Match(ability, {}); - monitor->OnAbilityForeground(); + if (monitor->Match(ability)) { + monitor->OnAbilityForeground(); + } } } -void AbilityDelegator::PrePerformBackground(const std::shared_ptr &ability) +void AbilityDelegator::PostPerformBackground(const std::shared_ptr &ability) { if (!ability) { APP_LOGW("Invalid input parameter"); return; } + ProcessAbilityProperties(ability); + std::unique_lock lck(mutexMonitor_); if (abilityMonitors_.empty()) { APP_LOGW("Empty abilityMonitors"); @@ -457,18 +400,21 @@ void AbilityDelegator::PrePerformBackground(const std::shared_ptr &abil continue; } - monitor->Match(ability, {}); - monitor->OnAbilityBackground(); + if (monitor->Match(ability)) { + monitor->OnAbilityBackground(); + } } } -void AbilityDelegator::PrePerformStop(const std::shared_ptr &ability) +void AbilityDelegator::PostPerformStop(const std::shared_ptr &ability) { if (!ability) { APP_LOGW("Invalid input parameter"); return; } + ProcessAbilityProperties(ability); + std::unique_lock lck(mutexMonitor_); if (abilityMonitors_.empty()) { APP_LOGW("Empty abilityMonitors"); @@ -480,8 +426,9 @@ void AbilityDelegator::PrePerformStop(const std::shared_ptr &ability) continue; } - monitor->Match(ability, {}); - monitor->OnAbilityStop(); + if (monitor->Match(ability)) { + monitor->OnAbilityStop(); + } } } @@ -510,75 +457,53 @@ AbilityDelegator::AbilityState AbilityDelegator::ConvertAbilityState( return abilityState; } -void AbilityDelegator::ProcessAbilityProperties(const std::shared_ptr &ability) +void AbilityDelegator::ProcessAbilityProperties(const std::shared_ptr &ability) { if (!ability) { - APP_LOGW("Invalid ability"); + APP_LOGW("Invalid ability property"); return; } - auto abilityToken = GetAbilityToken(ability); - if (!abilityToken) { - APP_LOGE("Invalid ability token"); - return; - } + APP_LOGW("ability property : name : %{public}s, state : %{public}d", + ability->name_.data(), ability->lifecycleState_); std::unique_lock lck(mutexAbilityProperties_); - auto existedProperty = DoesPropertyExist(abilityToken); + auto existedProperty = DoesPropertyExist(ability->token_); if (existedProperty) { - abilityProperties_.remove(existedProperty.value()); - } - - auto abilityState = ConvertAbilityState(ability->GetState()); - if (abilityState == AbilityDelegator::AbilityState::FOREGROUND) { - abilityProperties_.emplace_front(abilityToken, ability, abilityState); - } else { - abilityProperties_.emplace_back(abilityToken, ability, abilityState); - } -} - -sptr AbilityDelegator::GetAbilityToken(const std::shared_ptr &ability) -{ - if (!ability) { - APP_LOGW("Invalid ability"); - return {}; - } - - auto abilityContext = ability->GetAbilityContext(); - if (!abilityContext) { - APP_LOGE("Invalid ability context"); - return {}; + // update + existedProperty->lifecycleState_ = ability->lifecycleState_; + return; } - return abilityContext->GetToken(); + abilityProperties_.emplace_back(ability); } -std::optional AbilityDelegator::DoesPropertyExist(const sptr &token) +std::shared_ptr AbilityDelegator::DoesPropertyExist(const sptr &token) { if (!token) { APP_LOGW("Invalid input parameter"); - return std::nullopt; + return {}; } for (auto &it : abilityProperties_) { - auto tmpToken = std::get(it); - if (token == tmpToken) { + if (!it) { + APP_LOGW("Invalid ability property"); + continue; + } + + if (token == it->token_) { + APP_LOGI("Porperty exists"); return it; } } - return std::nullopt; + return {}; } -void AbilityDelegator::FinishUserTest(const int32_t resultCode) +void AbilityDelegator::FinishUserTest(const std::string &msg, const int32_t resultCode) { APP_LOGI("Enter"); - if (!mainThread_) { - APP_LOGE("Invalid mainThread"); - return; - } - if (!observer_) { APP_LOGE("Invalid observer"); return; @@ -591,8 +516,10 @@ void AbilityDelegator::FinishUserTest(const int32_t resultCode) } const auto &bundleName = delegatorArgs->GetTestBundleName(); - - mainThread_->FinishUserTest("UserTest finished", resultCode, bundleName, observer_); + auto err = AAFwk::AbilityManagerClient::GetInstance()->FinishUserTest(msg, resultCode, bundleName, observer_); + if (err) { + APP_LOGE("MainThread::FinishUserTest is failed %{public}d", err); + } } } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator_args.cpp b/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator_args.cpp index 44fbeee45da24eecbc806470121bdada5dc2eb57..0f8c069a800ff758dd6868ad7fb1f9d898bdabdc 100644 --- a/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator_args.cpp +++ b/frameworks/kits/appkit/native/ability_delegator/src/ability_delegator_args.cpp @@ -17,20 +17,27 @@ namespace OHOS { namespace AppExecFwk { +const std::string AbilityDelegatorArgs::KEY_TEST_BUNDLE_NAME {"-p"}; const std::string AbilityDelegatorArgs::KEY_TEST_RUNNER_CLASS {"-s unittest"}; const std::string AbilityDelegatorArgs::KEY_TEST_CASE {"-s class"}; +const std::string AbilityDelegatorArgs::KEY_TEST_WAIT_TIMEOUT {"-w"}; AbilityDelegatorArgs::AbilityDelegatorArgs() {} AbilityDelegatorArgs::AbilityDelegatorArgs(const AAFwk::Want &want) { - bundleName_ = want.GetStringParam("-p"); - params_["-p"] = want.GetStringParam("-p"); - params_["-s unittest"] = want.GetStringParam("-s unittest"); - params_["-s class"] = want.GetStringParam("-s class"); - if (!want.GetStringParam("-w").empty()) { - params_["-w"] = want.GetStringParam("-w"); + bundleName_ = want.GetStringParam(AbilityDelegatorArgs::KEY_TEST_BUNDLE_NAME); + params_[AbilityDelegatorArgs::KEY_TEST_BUNDLE_NAME] = + want.GetStringParam(AbilityDelegatorArgs::KEY_TEST_BUNDLE_NAME); + params_[AbilityDelegatorArgs::KEY_TEST_RUNNER_CLASS] = + want.GetStringParam(AbilityDelegatorArgs::KEY_TEST_RUNNER_CLASS); + if (!want.GetStringParam(AbilityDelegatorArgs::KEY_TEST_CASE).empty()) { + params_[AbilityDelegatorArgs::KEY_TEST_CASE] = want.GetStringParam(AbilityDelegatorArgs::KEY_TEST_CASE); + } + if (!want.GetStringParam(AbilityDelegatorArgs::KEY_TEST_WAIT_TIMEOUT).empty()) { + params_[AbilityDelegatorArgs::KEY_TEST_WAIT_TIMEOUT] = + want.GetStringParam(AbilityDelegatorArgs::KEY_TEST_WAIT_TIMEOUT); } } diff --git a/frameworks/kits/appkit/native/ability_delegator/src/iability_monitor.cpp b/frameworks/kits/appkit/native/ability_delegator/src/iability_monitor.cpp index c592bcd1e6aa4ec6f9808a4c34fda051d839cce2..1e52a05eb80d905817b368c0440bf56fda09c588 100644 --- a/frameworks/kits/appkit/native/ability_delegator/src/iability_monitor.cpp +++ b/frameworks/kits/appkit/native/ability_delegator/src/iability_monitor.cpp @@ -12,9 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#include "iability_monitor.h" +#include #include "app_log_wrapper.h" +#include "iability_monitor.h" using namespace std::chrono_literals; @@ -23,15 +23,15 @@ namespace AppExecFwk { IAbilityMonitor::IAbilityMonitor(const std::string &abilityName) : abilityName_(abilityName) {} -bool IAbilityMonitor::Match(const std::shared_ptr &ability, const Want &want) +bool IAbilityMonitor::Match(const std::shared_ptr &ability, bool isNotify) { - std::string aName; - if (ability) { - aName = ability->GetAbilityName(); - } else { - aName = want.GetElement().GetAbilityName(); + if (!ability) { + APP_LOGW("Invalid ability property"); + return false; } + const auto &aName = ability->name_; + if (abilityName_.empty() || aName.empty()) { APP_LOGW("Invalid name"); return false; @@ -42,25 +42,27 @@ bool IAbilityMonitor::Match(const std::shared_ptr &ability, const Want return false; } - if (ability) { + APP_LOGI("Matched : ability name : %{public}s, isNotify : %{public}s", + abilityName_.data(), (isNotify ? "true" : "false")); + + if (isNotify) { + APP_LOGI("Matched : notify ability matched"); { std::lock_guard matchLock(mMatch_); matchedAbility_ = ability; } cvMatch_.notify_one(); - - return true; } - return false; + return true; } -std::shared_ptr IAbilityMonitor::waitForAbility() +std::shared_ptr IAbilityMonitor::waitForAbility() { return waitForAbility(MAX_TIME_OUT); } -std::shared_ptr IAbilityMonitor::waitForAbility(const int64_t timeoutMs) +std::shared_ptr IAbilityMonitor::waitForAbility(const int64_t timeoutMs) { auto realTime = timeoutMs; if (timeoutMs <= 0) { diff --git a/frameworks/kits/appkit/native/ability_runtime/app/ability_stage.cpp b/frameworks/kits/appkit/native/ability_runtime/app/ability_stage.cpp index e249e7dfea2a62b620f05006ff117b75f3c9a3b4..758ce27fed144d9bf5cbea12c38e6db598e30ff0 100644 --- a/frameworks/kits/appkit/native/ability_runtime/app/ability_stage.cpp +++ b/frameworks/kits/appkit/native/ability_runtime/app/ability_stage.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -37,7 +37,7 @@ std::shared_ptr AbilityStage::Create( } } -void AbilityStage::OnCreate() const +void AbilityStage::OnCreate(const AAFwk::Want &want) const { HILOG_INFO("AbilityStage::OnCreate come"); } @@ -58,7 +58,7 @@ void AbilityStage::Init(std::shared_ptr context) } void AbilityStage::AddAbility(const sptr &token, - std::shared_ptr abilityRecord) + const std::shared_ptr &abilityRecord) { if (token == nullptr) { HILOG_ERROR("AbilityStage::AddAbility failed, token is nullptr"); @@ -92,5 +92,10 @@ std::string AbilityStage::OnAcceptWant(const AAFwk::Want &want) HILOG_INFO("AbilityStage::OnAcceptWant come"); return ""; } + +void AbilityStage::OnConfigurationUpdated(const AppExecFwk::Configuration& configuration) +{ + HILOG_INFO("%{public}s called.", __func__); +} } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/kits/appkit/native/ability_runtime/app/ability_stage.h b/frameworks/kits/appkit/native/ability_runtime/app/ability_stage.h index 9718625f0112b9a36968619f70453eecbaad420f..8990145eb1e852344c50772744d2672c766b2864 100644 --- a/frameworks/kits/appkit/native/ability_runtime/app/ability_stage.h +++ b/frameworks/kits/appkit/native/ability_runtime/app/ability_stage.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -22,6 +22,7 @@ #include "ability_local_record.h" #include "ability_runtime/context/context.h" +#include "configuration.h" #include "want.h" namespace OHOS { @@ -41,14 +42,17 @@ public: AbilityStage() = default; virtual ~AbilityStage() = default; - virtual void OnCreate() const; + virtual void OnCreate(const AAFwk::Want &want) const; virtual void OnDestory() const; virtual std::string OnAcceptWant(const AAFwk::Want &want); virtual void Init(std::shared_ptr context); std::shared_ptr GetContext() const; - void AddAbility(const sptr &token, std::shared_ptr abilityRecord); + void AddAbility(const sptr &token, + const std::shared_ptr &abilityRecord); void RemoveAbility(const sptr &token); bool ContainsAbility(); + virtual void OnConfigurationUpdated(const AppExecFwk::Configuration& configuration); + private: std::shared_ptr context_; std::map, std::shared_ptr> abilityRecords_; diff --git a/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage.cpp b/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage.cpp index 1e8984849b96c7f39cf61bd3701983b7b4914644..deffaa191c2830a1dc71b595587482ca4cc36ffb 100644 --- a/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage.cpp +++ b/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,9 +16,11 @@ #include "js_ability_stage.h" #include "hilog_wrapper.h" +#include "js_ability_stage_context.h" #include "js_context_utils.h" #include "js_runtime.h" #include "js_runtime_utils.h" +#include "napi_common_configuration.h" #include "napi_common_util.h" #include "napi_common_want.h" @@ -87,11 +89,11 @@ void JsAbilityStage::Init(std::shared_ptr context) return; } - NativeValue* contextObj = CreateJsBaseContext(engine, context); - auto shellContextRef = jsRuntime_.LoadSystemModule("application.AbilityStageContext", &contextObj, 1); - contextObj = shellContextRef->Get(); + NativeValue* contextObj = CreateJsAbilityStageContext(engine, context); + shellContextRef_ = jsRuntime_.LoadSystemModule("application.AbilityStageContext", &contextObj, 1); + contextObj = shellContextRef_->Get(); - context->Bind(jsRuntime_, shellContextRef.release()); + context->Bind(jsRuntime_, shellContextRef_.get()); obj->SetProperty("context", contextObj); auto nativeObj = ConvertNativeValueTo(contextObj); @@ -109,11 +111,11 @@ void JsAbilityStage::Init(std::shared_ptr context) }, nullptr); } -void JsAbilityStage::OnCreate() const +void JsAbilityStage::OnCreate(const AAFwk::Want &want) const { HILOG_INFO("JsAbilityStage::OnCreate come"); - AbilityStage::OnCreate(); + AbilityStage::OnCreate(want); if (!jsAbilityStageObj_) { HILOG_WARN("Not found AbilityStage.js"); @@ -173,5 +175,51 @@ std::string JsAbilityStage::OnAcceptWant(const AAFwk::Want &want) return AppExecFwk::UnwrapStringFromJS( reinterpret_cast(&nativeEngine), reinterpret_cast(flagNative)); } + +void JsAbilityStage::OnConfigurationUpdated(const AppExecFwk::Configuration& configuration) +{ + AbilityStage::OnConfigurationUpdated(configuration); + HILOG_INFO("%{public}s called.", __func__); + + HandleScope handleScope(jsRuntime_); + auto& nativeEngine = jsRuntime_.GetNativeEngine(); + + // Notify Ability stage context + auto fullConfig = GetContext()->GetConfiguration(); + JsAbilityStageContext::ConfigurationUpdated(&nativeEngine, shellContextRef_, fullConfig); + + napi_value napiConfiguration = OHOS::AppExecFwk::WrapConfiguration( + reinterpret_cast(&nativeEngine), *fullConfig); + NativeValue* jsConfiguration = reinterpret_cast(napiConfiguration); + CallObjectMethod("onConfigurationUpdated", &jsConfiguration, 1); +} + +NativeValue* JsAbilityStage::CallObjectMethod(const char* name, NativeValue * const * argv, size_t argc) +{ + HILOG_INFO("JsAbilityStage::CallObjectMethod %{public}s", name); + + if (!jsAbilityStageObj_) { + HILOG_WARN("Not found AbilityStage.js"); + return nullptr; + } + + HandleScope handleScope(jsRuntime_); + auto& nativeEngine = jsRuntime_.GetNativeEngine(); + + NativeValue* value = jsAbilityStageObj_->Get(); + NativeObject* obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + HILOG_ERROR("Failed to get AbilityStage object"); + return nullptr; + } + + NativeValue* method = obj->GetProperty(name); + if (method == nullptr) { + HILOG_ERROR("Failed to get '%{public}s' from AbilityStage object", name); + return nullptr; + } + + return nativeEngine.CallFunction(value, method, argv, argc); +} } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage.h b/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage.h index c6020b238248865ac8c26f068752ee6bd2a78b26..abe3af198e2f3b9f8ff228d2dbab6334f2a32304 100644 --- a/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage.h +++ b/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,6 +17,8 @@ #define ABILITY_RUNTIME_JS_ABILITY_STAGE_H #include "ability_stage.h" +#include "configuration.h" +#include "native_engine/native_value.h" class NativeReference; @@ -33,13 +35,18 @@ public: void Init(std::shared_ptr context) override; - void OnCreate() const override; + void OnCreate(const AAFwk::Want &want) const override; std::string OnAcceptWant(const AAFwk::Want &want) override; + void OnConfigurationUpdated(const AppExecFwk::Configuration& configuration) override; + private: + NativeValue* CallObjectMethod(const char* name, NativeValue * const * argv = nullptr, size_t argc = 0); + JsRuntime& jsRuntime_; std::unique_ptr jsAbilityStageObj_; + std::shared_ptr shellContextRef_; }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage_context.cpp b/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage_context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4d4c6aa48a0fdc7ed86aa17003745c14c53e2433 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage_context.cpp @@ -0,0 +1,67 @@ +/* + * 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_ability_stage_context.h" + +#include "hilog_wrapper.h" +#include "js_context_utils.h" +#include "js_data_struct_converter.h" +#include "js_runtime.h" +#include "js_runtime_utils.h" + +namespace OHOS { +namespace AbilityRuntime { +void JsAbilityStageContext::ConfigurationUpdated(NativeEngine* engine, std::shared_ptr &jsContext, + const std::shared_ptr &config) +{ + HILOG_INFO("%{public}s called.", __func__); + if ((!jsContext) || (!config)) { + HILOG_INFO("jsContext or config is nullptr."); + return; + } + + NativeValue* value = jsContext->Get(); + NativeObject* object = ConvertNativeValueTo(value); + if (!object) { + HILOG_INFO("object is nullptr."); + return; + } + + NativeValue* method = object->GetProperty("onUpdateConfiguration"); + if (!method) { + HILOG_ERROR("Failed to get onUpdateConfiguration from object"); + return; + } + + HILOG_INFO("JsAbilityStageContext call onUpdateConfiguration."); + NativeValue* argv[] = {CreateJsConfiguration(*engine, *config)}; + engine->CallFunction(value, method, argv, 1); +} + +NativeValue* CreateJsAbilityStageContext(NativeEngine& engine, std::shared_ptr context) +{ + HILOG_INFO("%{public}s called.", __func__); + NativeValue* objValue = CreateJsBaseContext(engine, context); + NativeObject* object = ConvertNativeValueTo(objValue); + + auto configuration = context->GetConfiguration(); + if (configuration) { + object->SetProperty("config", CreateJsConfiguration(engine, *configuration)); + } + + return objValue; +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage_context.h b/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage_context.h new file mode 100644 index 0000000000000000000000000000000000000000..f34fb698bc47e51df9f9790271bec54143268678 --- /dev/null +++ b/frameworks/kits/appkit/native/ability_runtime/app/js_ability_stage_context.h @@ -0,0 +1,48 @@ +/* + * 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_ABILITY_STAGE_CONTEXT_H +#define ABILITY_RUNTIME_JS_ABILITY_STAGE_CONTEXT_H + +#include "foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/context/context.h" +#include "configuration.h" + +class NativeEngine; +class NativeReference; +class NativeValue; + +namespace OHOS { +namespace AbilityRuntime { +class JsAbilityStageContext final { +public: + explicit JsAbilityStageContext(const std::shared_ptr& context) : context_(context) {} + ~JsAbilityStageContext() = default; + + static void ConfigurationUpdated(NativeEngine* engine, std::shared_ptr &jsContext, + const std::shared_ptr &config); + + std::shared_ptr GetContext() + { + return context_.lock(); + } + +private: + std::weak_ptr context_; +}; + +NativeValue* CreateJsAbilityStageContext(NativeEngine& engine, std::shared_ptr context); +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_JS_ABILITY_STAGE_CONTEXT_H \ No newline at end of file diff --git a/interfaces/kits/js/bundle/moduleusagerecord1.d.ts b/frameworks/kits/appkit/native/ability_runtime/context/ability_constants.h similarity index 53% rename from interfaces/kits/js/bundle/moduleusagerecord1.d.ts rename to frameworks/kits/appkit/native/ability_runtime/context/ability_constants.h index 8cc84046b05a740750de79773155d49bf2e72da0..68d858b9b763d4381ea8a736d76e5b6ad9baa22a 100644 --- a/interfaces/kits/js/bundle/moduleusagerecord1.d.ts +++ b/frameworks/kits/appkit/native/ability_runtime/context/ability_constants.h @@ -13,18 +13,17 @@ * limitations under the License. */ -export interface ModuleUsageRecord { - readonly bundleName: string; - readonly appLabelId: number; - readonly name: string; - readonly labelId: number; - readonly descriptionId: number; - readonly abilityName: string; - readonly abilityLabelId: number; - readonly abilityDescriptionId: number; - readonly abilityIconId: number; - readonly launchedCount: number; - readonly lastLaunchTime: number; - readonly isRemoved: boolean; - readonly installationFreeSupported: boolean; -} \ No newline at end of file +#ifndef FOUNDATION_AAFWK_ABILITY_CONSTANTS_H +#define FOUNDATION_AAFWK_ABILITY_CONSTANTS_H + +namespace OHOS { +namespace AbilityRuntime { +namespace Constants { +const std::string ABS_CODE_PATH = "/data/app/el1/bundle/public"; +const std::string LOCAL_CODE_PATH = "/data/storage/el1/bundle"; +const std::string LOCAL_BUNDLES = "/data/bundles"; +const std::string FILE_SEPARATOR = "/"; +} // namespace Constants +} // namespace AbilityRuntime +} // namespace OHOS +#endif // FOUNDATION_AAFWK_ABILITY_CONSTANTS_H \ No newline at end of file diff --git a/frameworks/kits/appkit/native/ability_runtime/context/context.h b/frameworks/kits/appkit/native/ability_runtime/context/context.h index 743fcecbf3cbdfcd781ae30a1d2381dd898b1557..6d7c81be5022b199beedd52e8bc42d8df6bd8185 100755 --- a/frameworks/kits/appkit/native/ability_runtime/context/context.h +++ b/frameworks/kits/appkit/native/ability_runtime/context/context.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -22,10 +22,11 @@ #include "application_info.h" #include "bindable.h" #include "hap_module_info.h" +#include "foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr/configuration.h" #include "foundation/communication/ipc/interfaces/innerkits/ipc_core/include/iremote_object.h" #include "resource_manager.h" -using IRemoteObject = OHOS::IRemoteObject; +using IRemoteObject = OHOS::IRemoteObject; namespace OHOS { namespace AbilityRuntime { @@ -140,19 +141,19 @@ 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 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 @@ -161,6 +162,13 @@ public: */ virtual void SwitchArea(int mode) = 0; + /** + * @brief Obtains the configuration of application. + * + * @return configuration of application. + */ + virtual std::shared_ptr GetConfiguration() const = 0; + /** * @brief Getting derived class * 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 aa056ea239e6e549acbc434bcffb9452a2232902..b26827017f168e39067246fb08a5b70f5cc480d3 100644 --- a/frameworks/kits/appkit/native/ability_runtime/context/context_impl.cpp +++ b/frameworks/kits/appkit/native/ability_runtime/context/context_impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,6 +15,9 @@ #include "context_impl.h" +#include + +#include "ability_constants.h" #include "file_util.h" #include "hilog_wrapper.h" #include "ipc_singleton.h" @@ -26,6 +29,8 @@ namespace OHOS { namespace AbilityRuntime { +using namespace OHOS::AbilityRuntime::Constants; + const size_t Context::CONTEXT_TYPE_ID(std::hash {} ("Context")); const int64_t ContextImpl::CONTEXT_CREATE_BY_SYSTEM_APP(0x00000001); const std::string ContextImpl::CONTEXT_DATA_APP("/data/app/"); @@ -56,9 +61,14 @@ std::string ContextImpl::GetBundleName() const std::string ContextImpl::GetBundleCodeDir() { + auto appInfo = GetApplicationInfo(); + if (appInfo == nullptr) { + return ""; + } + std::string dir; if (IsCreateBySystemApp()) { - dir = CONTEXT_DATA_APP + CONTEXT_ELS[0] + CONTEXT_BUNDLE + GetBundleName(); + dir = std::regex_replace(appInfo->codePath, std::regex(ABS_CODE_PATH), LOCAL_BUNDLES); } else { dir = CONTEXT_DATA_STORAGE + CONTEXT_ELS[0] + CONTEXT_BUNDLE; } @@ -240,7 +250,15 @@ void ContextImpl::InitResourceManager( HILOG_DEBUG( "ContextImpl::InitResourceManager moduleResPaths count: %{public}zu", bundleInfo.moduleResPaths.size()); - for (auto moduleResPath : bundleInfo.moduleResPaths) { + std::vector moduleResPaths; + std::regex pattern(ABS_CODE_PATH); + for (auto item : bundleInfo.moduleResPaths) { + if (item.empty()) { + continue; + } + moduleResPaths.emplace_back(std::regex_replace(item, pattern, LOCAL_BUNDLES)); + } + for (auto moduleResPath : moduleResPaths) { if (!moduleResPath.empty()) { HILOG_ERROR("ContextImpl::InitResourceManager length: %{public}zu, moduleResPath: %{public}s", moduleResPath.length(), @@ -279,7 +297,6 @@ sptr ContextImpl::GetBundleManager() const } HILOG_DEBUG("ContextImpl::GetBundleManager before iface_cast"); sptr bms = iface_cast(bundleObj); - HILOG_DEBUG("ContextImpl::GetBundleManager after iface_cast"); HILOG_DEBUG("ContextImpl::GetBundleManager end"); return bms; } @@ -411,5 +428,15 @@ void ContextImpl::CreateDirIfNotExist(const std::string& dirPath) const } } } + +void ContextImpl::SetConfiguration(const std::shared_ptr &config) +{ + config_ = config; +} + +std::shared_ptr ContextImpl::GetConfiguration() const +{ + return config_; +} } // 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 5b367f169431220c4d6357cc342d2ee60634abf8..bd0e3b59344b2cf6d70f577c372779736a566eca 100644 --- a/frameworks/kits/appkit/native/ability_runtime/context/context_impl.h +++ b/frameworks/kits/appkit/native/ability_runtime/context/context_impl.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,6 +18,7 @@ #include "context.h" +#include "configuration.h" #include "bundle_mgr_interface.h" namespace OHOS { @@ -182,22 +183,36 @@ public: */ 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_; + /** + * @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; + + /** + * @brief Get the token witch the app launched. + * + * @return token The token which the is launched by app. + */ + void SetConfiguration(const std::shared_ptr &config); + + /** + * @brief Get the token witch the app launched. + * + * @return token The token which the is launched by app. + */ + std::shared_ptr GetConfiguration() const override; + +protected: + sptr token_; private: static const int64_t CONTEXT_CREATE_BY_SYSTEM_APP; @@ -234,6 +249,7 @@ private: std::shared_ptr parentContext_ = nullptr; std::shared_ptr resourceManager_ = nullptr; std::shared_ptr hapModuleInfo_ = nullptr; + std::shared_ptr config_ = nullptr; std::string currArea_ = CONTEXT_ELS[EL_DEFAULT]; }; } // namespace AbilityRuntime diff --git a/frameworks/kits/appkit/native/ability_runtime/form_extension_context.cpp b/frameworks/kits/appkit/native/ability_runtime/form_extension_context.cpp index 1918c42734cc287233b225698d9efd169e2877b5..7e8e1ae7a34097d79f9dd0b6fb150b8fbae30cf4 100644 --- a/frameworks/kits/appkit/native/ability_runtime/form_extension_context.cpp +++ b/frameworks/kits/appkit/native/ability_runtime/form_extension_context.cpp @@ -15,6 +15,7 @@ #include "form_extension_context.h" +#include "ability_manager_client.h" #include "appexecfwk_errors.h" #include "form_mgr.h" #include "hilog_wrapper.h" @@ -48,11 +49,33 @@ int FormExtensionContext::UpdateForm(const int64_t formId, const AppExecFwk::For return AppExecFwk::FormMgr::GetInstance().UpdateForm(formId, abilityInfo_->bundleName, formProviderData); } +ErrCode FormExtensionContext::StartAbility(const AAFwk::Want &want) const +{ + HILOG_DEBUG("%{public}s begin.", __func__); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, token_, -1); + HILOG_DEBUG("%{public}s. End calling StartAbility. ret=%{public}d", __func__, err); + if (err != ERR_OK) { + HILOG_ERROR("FormExtensionContext::StartAbility is failed %{public}d", err); + } + return err; +} + +ErrCode FormExtensionContext::StartAbility(const AAFwk::Want &want, const AAFwk::StartOptions &startOptions) const +{ + HILOG_DEBUG("%{public}s begin.", __func__); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, startOptions, token_, -1); + HILOG_DEBUG("%{public}s. End calling StartAbility. ret=%{public}d", __func__, err); + if (err != ERR_OK) { + HILOG_ERROR("FormExtensionContext::StartAbility is failed %{public}d", err); + } + return err; +} + AppExecFwk::AbilityType FormExtensionContext::GetAbilityInfoType() const { std::shared_ptr info = GetAbilityInfo(); if (info == nullptr) { - HILOG_ERROR("ServiceContext::GetAbilityInfoType info == nullptr"); + HILOG_ERROR("FormExtensionContext::GetAbilityInfoType info == nullptr"); return AppExecFwk::AbilityType::UNKNOWN; } diff --git a/frameworks/kits/appkit/native/ability_runtime/form_extension_context.h b/frameworks/kits/appkit/native/ability_runtime/form_extension_context.h index 0f7eae4c2cef4dd0daa07e5c3add774fcb415936..d9c0b32433b2207c91cdc78d8f21242774468a61 100644 --- a/frameworks/kits/appkit/native/ability_runtime/form_extension_context.h +++ b/frameworks/kits/appkit/native/ability_runtime/form_extension_context.h @@ -19,6 +19,7 @@ #include "ability_info.h" #include "extension_context.h" #include "form_provider_info.h" +#include "start_options.h" namespace OHOS { namespace AbilityRuntime { @@ -43,6 +44,19 @@ public: */ int UpdateForm(const int64_t formId, const AppExecFwk::FormProviderData &formProviderData); + /** + * @brief Starts a new ability. + * An ability using the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE template uses this method + * to start a specific ability. The system locates the target ability from installed abilities based on the value + * of the want parameter and then starts it. You can specify the ability to start using the want parameter. + * + * @param want Indicates the Want containing information about the target ability to start. + * + * @return errCode ERR_OK on success, others on failure. + */ + ErrCode StartAbility(const AAFwk::Want &want) const; + ErrCode StartAbility(const AAFwk::Want &want, const AAFwk::StartOptions &startOptions) const; + /** * @brief Obtains information about the current ability. * The returned information includes the class name, bundle name, and other information about the current ability. diff --git a/frameworks/kits/appkit/native/app/include/application_impl.h b/frameworks/kits/appkit/native/app/include/application_impl.h index fca3847d28da522c458ebd6c5d89d5d1288c3f9c..2c1a8ba191be3bf0a941c102471b706f7467dd5d 100644 --- a/frameworks/kits/appkit/native/app/include/application_impl.h +++ b/frameworks/kits/appkit/native/app/include/application_impl.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -141,6 +141,8 @@ private: int recordId_; std::shared_ptr application_ = nullptr; + void RemoveUriPermission(); + DISALLOW_COPY_AND_MOVE(ApplicationImpl); }; } // namespace AppExecFwk diff --git a/frameworks/kits/appkit/native/app/include/context.h b/frameworks/kits/appkit/native/app/include/context.h index d250982db14b1aa97c4e624a9a56461b220b4fb6..96360e5afd20c87fdae3996260564897d7e4de70 100644 --- a/frameworks/kits/appkit/native/app/include/context.h +++ b/frameworks/kits/appkit/native/app/include/context.h @@ -50,6 +50,7 @@ using AbilityStartSetting = AAFwk::AbilityStartSetting; #define OHOS_REQUEST_PERMISSION_VALUE 1 constexpr int INVALID_RESOURCE_VALUE = -1; // GetColor() Failed return Value +constexpr int DEFAULT_ACCOUNT_ID = -1; class DataAbilityHelper; class DataShareHelper; diff --git a/frameworks/kits/appkit/native/app/include/context_container.h b/frameworks/kits/appkit/native/app/include/context_container.h index 034c1159c1ed503a7a420b3af3c826ebfae16f24..51827dd13ad25f4b29ead230b0822005c1608830 100755 --- a/frameworks/kits/appkit/native/app/include/context_container.h +++ b/frameworks/kits/appkit/native/app/include/context_container.h @@ -338,15 +338,15 @@ public: * @brief Creates a Context object for an application with the given bundle name. * * @param bundleName Indicates the bundle name of the application. - * * @param flag Indicates the flag for creating a Context object. It can be 0, any of * the following values, or any combination of the following values: CONTEXT_IGNORE_SECURITY, * CONTEXT_INCLUDE_CODE, and CONTEXT_RESTRICTED. The value 0 indicates that there is no restriction * on creating contexts for applications. + * @param accountId Indicates the account id. * * @return Returns a Context object created for the specified application. */ - std::shared_ptr CreateBundleContext(std::string bundleName, int flag); + std::shared_ptr CreateBundleContext(std::string bundleName, int flag, int accountId = DEFAULT_ACCOUNT_ID); /** * @brief Obtains information about the caller of this ability. diff --git a/frameworks/kits/appkit/native/app/include/context_deal.h b/frameworks/kits/appkit/native/app/include/context_deal.h index 4259664701092bcb6eff375ebbb6c77784e0adac..9d3e0bc2ddc41b5f173e12262fa23003e36770c4 100755 --- a/frameworks/kits/appkit/native/app/include/context_deal.h +++ b/frameworks/kits/appkit/native/app/include/context_deal.h @@ -25,6 +25,7 @@ namespace AppExecFwk { class ContextDeal : public Context, public std::enable_shared_from_this { public: ContextDeal() = default; + explicit ContextDeal(bool isCreateBySystemApp); virtual ~ContextDeal() = default; /** @@ -730,7 +731,6 @@ public: * @return Returns the lifecycle state info. */ AAFwk::LifeCycleStateInfo GetLifeCycleStateInfo() const; - public: static const std::string CONTEXT_DEAL_FILE_SEPARATOR; static const std::string CONTEXT_DEAL_CODE_CACHE; @@ -759,6 +759,7 @@ private: std::shared_ptr mainTaskDispatcher_; std::shared_ptr mainEventRunner_; std::shared_ptr hapModuleInfoLocal_ = nullptr; + bool isCreateBySystemApp_ = false; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/appkit/native/app/include/main_thread.h b/frameworks/kits/appkit/native/app/include/main_thread.h index 4520c6a637fdcbaf43f7577afd95ac0aea34c1e5..000c8ae72d70fbcace34be506132f03d3a71bf5e 100644 --- a/frameworks/kits/appkit/native/app/include/main_thread.h +++ b/frameworks/kits/appkit/native/app/include/main_thread.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -164,15 +164,8 @@ public: */ void ScheduleAbilityStage(const HapModuleInfo &abilityStage) override; - /** - * - * @brief launch the application. - * - * @param info The launchdata of the application witch launced. - * @param token The launchdata of the application witch launced. - * - */ - void ScheduleLaunchAbility(const AbilityInfo &info, const sptr &token) override; + void ScheduleLaunchAbility(const AbilityInfo &info, const sptr &token, + const std::shared_ptr &want) override; /** * @@ -217,18 +210,6 @@ public: void ScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName) override; - /** - * @brief Finish user test. - * @param msg user test message. - * @param resultCode user test result Code. - * @param bundleName user test bundleName. - * @param observer test observer callback. - * - * @return Returns ERR_OK on success, others on failure. - */ - int FinishUserTest(const std::string &msg, const int &resultCode, - const std::string &bundleName, const sptr &observer); - private: /** * @@ -392,8 +373,10 @@ private: * * @brief Task in event handler timeout detected. * + * @param runner the runner belong to the mainthread. + * */ - void TaskTimeoutDetected(); + void TaskTimeoutDetected(const std::shared_ptr& runner); /** * @@ -473,6 +456,9 @@ private: void LoadAppLibrary(); + void ChangeToLocalPath(const std::string &bundleName, + const std::vector &sourceDirs, std::vector &localPath); + /** * * @brief Close the ability library loaded. @@ -505,7 +491,8 @@ private: Profile &appProfile); bool CheckForHandleLaunchApplication(const AppLaunchData &appLaunchData); bool InitResourceManager(std::shared_ptr &resourceManager, - std::shared_ptr &contextDeal, ApplicationInfo &appInfo, BundleInfo& bundleInfo); + std::shared_ptr &contextDeal, ApplicationInfo &appInfo, BundleInfo& bundleInfo, + const Configuration &config); std::vector fileEntries_; std::vector handleAbilityLib_; // the handler of ACE Library. #endif // ABILITY_LIBRARY_LOADER diff --git a/frameworks/kits/appkit/native/app/include/watchdog.h b/frameworks/kits/appkit/native/app/include/watchdog.h index 63f1afd0bff26300925cf0cbfa838572d1f82140..86833785980a813a12c29290b45c681fa96a37f2 100644 --- a/frameworks/kits/appkit/native/app/include/watchdog.h +++ b/frameworks/kits/appkit/native/app/include/watchdog.h @@ -20,14 +20,14 @@ #include #include "event_handler.h" #include "inner_event.h" +#include "application_impl.h" namespace OHOS { namespace AppExecFwk { const uint32_t MAIN_THREAD_IS_ALIVE = 0; const uint32_t MAIN_THREAD_TIMEOUT_TIME = 3000; -const uint32_t INI_ZERO = 0; -const uint32_t INI_TIMER_FIRST_SECOND = 10; -const uint32_t INI_TIMER_SECOND = 3; +const uint32_t INI_TIMER_FIRST_SECOND = 10000; +const uint32_t INI_TIMER_SECOND = 3000; const std::string MAIN_THREAD_IS_ALIVE_MSG = "MAIN_THREAD_IS_ALIVE"; class WatchDog : public EventHandler { public: @@ -42,7 +42,7 @@ public: * */ void ProcessEvent(const OHOS::AppExecFwk::InnerEvent::Pointer &event) override; - static void Timer(int sig); + bool Timer(); /** * @@ -60,6 +60,13 @@ public: */ void Stop(); + /** + * + * @brief Stop the mainthread function of watchdog. + * + */ + void SetApplicationInfo(const std::shared_ptr &applicationInfo); + /** * * @brief Get the eventHandler of watchdog thread. @@ -77,6 +84,9 @@ public: static bool GetAppMainThreadState(); private: + std::atomic_bool stopWatchDog_ = false; + std::shared_ptr applicationInfo_ = nullptr; + std::shared_ptr watchDogThread_ = nullptr; std::shared_ptr watchDogRunner_; static bool appMainThreadIsAlive_; static std::shared_ptr appMainHandler_; diff --git a/frameworks/kits/appkit/native/app/src/application_impl.cpp b/frameworks/kits/appkit/native/app/src/application_impl.cpp index 639425164fae9b54b63d500341d7f264251dc6d9..8e7a0f982a9ed4f67f6716d815fb428e0fd1ea75 100644 --- a/frameworks/kits/appkit/native/app/src/application_impl.cpp +++ b/frameworks/kits/appkit/native/app/src/application_impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,6 +17,7 @@ #include "app_log_wrapper.h" #include "ohos_application.h" +#include "uri_permission_manager_client.h" namespace OHOS { namespace AppExecFwk { @@ -104,6 +105,7 @@ bool ApplicationImpl::PerformTerminate() if (curState_ == APP_STATE_BACKGROUND) { application_->OnTerminate(); curState_ = APP_STATE_TERMINATED; + RemoveUriPermission(); return true; } APP_LOGE("ApplicationImpl::performTerminate error! curState is %{public}d", curState_); @@ -120,6 +122,23 @@ void ApplicationImpl::PerformTerminateStrong() { APP_LOGD("ApplicationImpl::PerformTerminateStrong called"); application_->OnTerminate(); + RemoveUriPermission(); +} + +void ApplicationImpl::RemoveUriPermission() +{ + auto appContext = application_->GetAppContext(); + if (!appContext) { + APP_LOGE("ApplicationImpl::RemoveUriPermission: Get appliction context failed."); + return; + } + auto appInfo = appContext->GetApplicationInfo(); + if (!appInfo) { + APP_LOGE("ApplicationImpl::RemoveUriPermission: Get appliction info failed."); + return; + } + auto uriPermMgrClient = AAFwk::UriPermissionManagerClient::GetInstance(); + uriPermMgrClient->RemoveUriPermission(appInfo->accessTokenId); } /** diff --git a/frameworks/kits/appkit/native/app/src/context_container.cpp b/frameworks/kits/appkit/native/app/src/context_container.cpp index 700eb866e6a87aea50343a33f961b1db0cd0984d..a63cb549b9d86b0a0728424757222e651ef50e28 100644 --- a/frameworks/kits/appkit/native/app/src/context_container.cpp +++ b/frameworks/kits/appkit/native/app/src/context_container.cpp @@ -14,6 +14,9 @@ */ #include "context_container.h" +#include + +#include "ability_constants.h" #include "ability_manager_client.h" #include "ability_manager_errors.h" #include "app_log_wrapper.h" @@ -22,7 +25,8 @@ namespace OHOS { namespace AppExecFwk { -constexpr int DEFAULT_USERID = 100; +// for api7 demo special +constexpr int CURRENT_ACCOUNT_ID = 100; /** * Attaches a Context object to the current ability. * Generally, this method is called after Ability is loaded to provide the application context for the current ability. @@ -604,19 +608,7 @@ void ContextContainer::RequestPermissionsFromUser(std::vector &perm } } -/** - * @brief Creates a Context object for an application with the given bundle name. - * - * @param bundleName Indicates the bundle name of the application. - * - * @param flag Indicates the flag for creating a Context object. It can be 0, any of - * the following values, or any combination of the following values: CONTEXT_IGNORE_SECURITY, - * CONTEXT_INCLUDE_CODE, and CONTEXT_RESTRICTED. The value 0 indicates that there is no restriction - * on creating contexts for applications. - * - * @return Returns a Context object created for the specified application. - */ -std::shared_ptr ContextContainer::CreateBundleContext(std::string bundleName, int flag) +std::shared_ptr ContextContainer::CreateBundleContext(std::string bundleName, int flag, int accountId) { if (bundleName.empty()) { APP_LOGE("ContextContainer::CreateBundleContext bundleName is empty"); @@ -634,10 +626,13 @@ std::shared_ptr ContextContainer::CreateBundleContext(std::string bundl } BundleInfo bundleInfo; - APP_LOGI("ContextContainer::CreateBundleContext length: %{public}zu, bundleName: %{public}s", - bundleName.length(), - bundleName.c_str()); - bundleMgr->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, DEFAULT_USERID); + APP_LOGI("CreateBundleContext length: %{public}zu, bundleName: %{public}s, accountId is %{public}d", + bundleName.length(), bundleName.c_str(), accountId); + int realAccountId = CURRENT_ACCOUNT_ID; + if (accountId != DEFAULT_ACCOUNT_ID) { + realAccountId = accountId; + } + bundleMgr->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, realAccountId); if (bundleInfo.name.empty() || bundleInfo.applicationInfo.name.empty()) { APP_LOGE("ContextContainer::CreateBundleContext GetBundleInfo is error"); @@ -649,7 +644,7 @@ std::shared_ptr ContextContainer::CreateBundleContext(std::string bundl APP_LOGE("ContextContainer::CreateBundleContext appContext is nullptr"); return nullptr; } - std::shared_ptr deal = std::make_shared(); + std::shared_ptr deal = std::make_shared(true); if (deal == nullptr) { APP_LOGE("ContextContainer::CreateBundleContext bundleName is empty"); return nullptr; @@ -673,9 +668,18 @@ void ContextContainer::InitResourceManager(BundleInfo &bundleInfo, std::shared_p APP_LOGI( "ContextContainer::InitResourceManager moduleResPaths count: %{public}zu", bundleInfo.moduleResPaths.size()); - for (auto moduleResPath : bundleInfo.moduleResPaths) { + std::vector moduleResPaths; + std::regex pattern(AbilityRuntime::Constants::ABS_CODE_PATH); + for (auto item : bundleInfo.moduleResPaths) { + if (item.empty()) { + continue; + } + moduleResPaths.emplace_back(std::regex_replace(item, pattern, AbilityRuntime::Constants::LOCAL_BUNDLES)); + } + + for (auto moduleResPath : moduleResPaths) { if (!moduleResPath.empty()) { - APP_LOGI("ContextContainer::InitResourceManager length: %{public}zu, moduleResPath: %{public}s", + APP_LOGI("ContextContainer::InitResourceManager length: %{public}zu, moduleResPath : %{public}s", moduleResPath.length(), moduleResPath.c_str()); if (!resourceManager->AddResource(moduleResPath.c_str())) { diff --git a/frameworks/kits/appkit/native/app/src/context_deal.cpp b/frameworks/kits/appkit/native/app/src/context_deal.cpp old mode 100755 new mode 100644 index d03ffb4d5542ea851dbaaecba80f5d9b16b41e20..d495386d0bd6549016902890edd3fe55f8e8f9fe --- a/frameworks/kits/appkit/native/app/src/context_deal.cpp +++ b/frameworks/kits/appkit/native/app/src/context_deal.cpp @@ -14,6 +14,10 @@ */ #include "context_deal.h" + +#include + +#include "ability_constants.h" #include "ability_manager_client.h" #include "ability_manager_interface.h" #include "app_log_wrapper.h" @@ -29,12 +33,17 @@ #define MODE 0771 namespace OHOS { namespace AppExecFwk { +using namespace OHOS::AbilityRuntime::Constants; + const std::string ContextDeal::CONTEXT_DEAL_FILE_SEPARATOR("/"); const std::string ContextDeal::CONTEXT_DEAL_CODE_CACHE("code_cache"); const std::string ContextDeal::CONTEXT_DEAL_Files("files"); const std::string ContextDeal::CONTEXT_DEAL_NO_BACKUP_Files("no_backup"); const std::string ContextDeal::CONTEXT_DEAL_DIRNAME("preferences"); +ContextDeal::ContextDeal(bool isCreateBySystemApp) : isCreateBySystemApp_(isCreateBySystemApp) +{} + /** * Called when getting the ProcessInfo * @@ -122,7 +131,18 @@ void ContextDeal::SetApplicationContext(const std::shared_ptr &context) */ std::string ContextDeal::GetBundleCodePath() { - return (applicationInfo_ != nullptr) ? applicationInfo_->codePath : ""; + if (applicationInfo_ == nullptr) { + return ""; + } + + std::string dir; + if (isCreateBySystemApp_) { + dir = std::regex_replace(applicationInfo_->codePath, std::regex(ABS_CODE_PATH), LOCAL_BUNDLES); + } else { + dir = LOCAL_CODE_PATH; + } + + return dir; } /** @@ -456,7 +476,18 @@ std::string ContextDeal::GetBundleName() */ std::string ContextDeal::GetBundleResourcePath() { - return (abilityInfo_ != nullptr) ? abilityInfo_->resourcePath : ""; + if (abilityInfo_ == nullptr) { + return ""; + } + + std::string dir; + if (isCreateBySystemApp_) { + dir = std::regex_replace(abilityInfo_->resourcePath, std::regex(ABS_CODE_PATH), LOCAL_BUNDLES); + } else { + std::regex pattern(ABS_CODE_PATH + FILE_SEPARATOR + abilityInfo_->bundleName); + dir = std::regex_replace(abilityInfo_->resourcePath, pattern, LOCAL_CODE_PATH); + } + return dir; } /** diff --git a/frameworks/kits/appkit/native/app/src/main_thread.cpp b/frameworks/kits/appkit/native/app/src/main_thread.cpp index 5abafb50084280bb348a33aa082b5ab9d50aa6d4..faace598f7c8a2a8391ce4ec743166f30ef01461 100644 --- a/frameworks/kits/appkit/native/app/src/main_thread.cpp +++ b/frameworks/kits/appkit/native/app/src/main_thread.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,7 +16,9 @@ #include "main_thread.h" #include +#include +#include "ability_constants.h" #include "ability_delegator.h" #include "ability_delegator_registry.h" #include "ability_loader.h" @@ -25,6 +27,7 @@ #include "app_log_wrapper.h" #include "application_env_impl.h" #include "bytrace.h" +#include "configuration_convertor.h" #include "context_deal.h" #include "context_impl.h" #include "extension_module_loader.h" @@ -51,6 +54,7 @@ namespace OHOS { namespace AppExecFwk { +using namespace OHOS::AbilityRuntime::Constants; std::shared_ptr MainThread::applicationForAnr_ = nullptr; namespace { constexpr int32_t DELIVERY_TIME = 200; @@ -426,15 +430,8 @@ void MainThread::ScheduleAbilityStage(const HapModuleInfo &abilityStage) APP_LOGI("MainThread::ScheduleAbilityStageInfo end."); } -/** - * - * @brief launch the application. - * - * @param info The launchdata of the application witch launced. - * @param token The launchdata of the application witch launced. - * - */ -void MainThread::ScheduleLaunchAbility(const AbilityInfo &info, const sptr &token) +void MainThread::ScheduleLaunchAbility(const AbilityInfo &info, const sptr &token, + const std::shared_ptr &want) { APP_LOGI("MainThread::scheduleLaunchAbility called start."); APP_LOGI( @@ -447,6 +444,7 @@ void MainThread::ScheduleLaunchAbility(const AbilityInfo &info, const sptr abilityToken = token; std::shared_ptr abilityRecord = std::make_shared(abilityInfo, abilityToken); + abilityRecord->SetWant(want); std::shared_ptr contextDeal = std::make_shared(); sptr bundleMgr = contextDeal->GetBundleManager(); @@ -709,6 +707,10 @@ bool MainThread::InitCreate( return false; } + if (watchDogHandler_ != nullptr) { + watchDogHandler_->SetApplicationInfo(applicationInfo_); + } + contextDeal->SetProcessInfo(processInfo_); contextDeal->SetApplicationInfo(applicationInfo_); contextDeal->SetProfile(appProfile_); @@ -732,12 +734,15 @@ bool MainThread::CheckForHandleLaunchApplication(const AppLaunchData &appLaunchD } bool MainThread::InitResourceManager(std::shared_ptr &resourceManager, - std::shared_ptr &contextDeal, ApplicationInfo &appInfo, BundleInfo& bundleInfo) + std::shared_ptr &contextDeal, ApplicationInfo &appInfo, BundleInfo& bundleInfo, + const Configuration &config) { BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); APP_LOGI("MainThread::handleLaunchApplication moduleResPaths count: %{public}zu start", bundleInfo.moduleResPaths.size()); - for (auto moduleResPath : bundleInfo.moduleResPaths) { + std::vector resPaths; + ChangeToLocalPath(bundleInfo.name, bundleInfo.moduleResPaths, resPaths); + for (auto moduleResPath : resPaths) { if (!moduleResPath.empty()) { APP_LOGI("MainThread::handleLaunchApplication length: %{public}zu, moduleResPath: %{public}s", moduleResPath.length(), @@ -766,6 +771,9 @@ bool MainThread::InitResourceManager(std::shared_ptrSetColorMode(ConvertColorMode(colormode)); + APP_LOGI("MainThread::handleLaunchApplication. Start calling UpdateResConfig."); resourceManager->UpdateResConfig(*resConfig); APP_LOGI("MainThread::handleLaunchApplication. End calling UpdateResConfig."); @@ -786,7 +794,10 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con APP_LOGE("MainThread::handleLaunchApplication CheckForHandleLaunchApplication failed"); return; } - LoadAbilityLibrary(appLaunchData.GetApplicationInfo().moduleSourceDirs); + std::vector localPaths; + ChangeToLocalPath(appLaunchData.GetApplicationInfo().bundleName, + appLaunchData.GetApplicationInfo().moduleSourceDirs, localPaths); + LoadAbilityLibrary(localPaths); LoadAppLibrary(); ApplicationInfo appInfo = appLaunchData.GetApplicationInfo(); @@ -829,11 +840,18 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con APP_LOGD("MainThread::handleLaunchApplication GetBundleInfo fail."); } - if (!InitResourceManager(resourceManager, contextDeal, appInfo, bundleInfo)) { + if (!InitResourceManager(resourceManager, contextDeal, appInfo, bundleInfo, config)) { APP_LOGE("MainThread::handleLaunchApplication InitResourceManager failed"); return; } + // create contextImpl + std::shared_ptr contextImpl = std::make_shared(); + contextImpl->SetResourceManager(resourceManager); + contextImpl->SetApplicationInfo(std::make_shared(appInfo)); + contextImpl->InitAppContext(); + application_->SetApplicationContext(contextImpl); + bool moduelJson = false; bool isStageBased = false; if (!bundleInfo.hapModuleInfos.empty()) { @@ -845,7 +863,7 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con if (isStageBased) { // Create runtime AbilityRuntime::Runtime::Options options; - options.codePath = appInfo.codePath; + options.codePath = LOCAL_CODE_PATH; options.eventRunner = mainHandler_->GetEventRunner(); auto runtime = AbilityRuntime::Runtime::Create(options); if (!runtime) { @@ -873,6 +891,10 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con application_->GetRuntime()); LoadAndRegisterExtension("system/lib/libdatashare_ext_ability_module.z.so", "DataShareExtAbility", application_->GetRuntime()); + LoadAndRegisterExtension("system/lib/libworkschedextension.z.so", "WorkSchedulerExtension", + application_->GetRuntime()); + LoadAndRegisterExtension("system/lib/libaccessibility_extension_module.z.so", "AccessibilityExtension", + application_->GetRuntime()); } contextDeal->initResourceManager(resourceManager); @@ -880,13 +902,7 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con application_->AttachBaseContext(contextDeal); application_->SetAbilityRecordMgr(abilityRecordMgr_); application_->SetConfiguration(config); - - // create contextImpl - std::shared_ptr contextImpl = std::make_shared(); - contextImpl->SetResourceManager(resourceManager); - contextImpl->SetApplicationInfo(std::make_shared(appInfo)); - contextImpl->InitAppContext(); - application_->SetApplicationContext(contextImpl); + contextImpl->SetConfiguration(application_->GetConfiguration()); applicationImpl_->SetRecordId(appLaunchData.GetRecordId()); applicationImpl_->SetApplication(application_); @@ -909,6 +925,19 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con APP_LOGI("MainThread::handleLaunchApplication called end."); } +void MainThread::ChangeToLocalPath(const std::string &bundleName, + const std::vector &sourceDirs, std::vector &localPath) +{ + for (auto item : sourceDirs) { + if (item.empty()) { + continue; + } + std::regex pattern(ABS_CODE_PATH + FILE_SEPARATOR + bundleName + FILE_SEPARATOR); + localPath.emplace_back( + std::regex_replace(item, pattern, LOCAL_CODE_PATH + FILE_SEPARATOR)); + } +} + void MainThread::HandleAbilityStage(const HapModuleInfo &abilityStage) { APP_LOGI("MainThread::HandleAbilityStageInfo"); @@ -960,30 +989,18 @@ bool MainThread::AbilityDelegatorPrepare(const UserTestRecord &record) return false; } - auto delegator = std::make_shared(this, std::move(testRunner), record.observer); + auto delegator = std::make_shared( + application_->GetAppContext(), std::move(testRunner), record.observer); if (!delegator) { APP_LOGE("delegator is null"); return false; } - delegator->Init(); AbilityDelegatorRegistry::RegisterInstance(delegator, args); delegator->Prepare(); return true; } -int MainThread::FinishUserTest(const std::string &msg, const int &resultCode, - const std::string &bundleName, const sptr &observer) -{ - APP_LOGI("MainThread::FinishUserTest"); - ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->FinishUserTest( - msg, resultCode, bundleName, observer); - if (err != ERR_OK) { - APP_LOGE("MainThread::FinishUserTest is failed %{public}d", err); - } - return ERR_OK; -} - /** * * @brief launch the ability. @@ -1292,7 +1309,7 @@ void MainThread::HandleConfigurationUpdated(const Configuration &config) APP_LOGI("MainThread::HandleConfigurationUpdated called end."); } -void MainThread::TaskTimeoutDetected() +void MainThread::TaskTimeoutDetected(const std::shared_ptr &runner) { BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); APP_LOGI("MainThread::TaskTimeoutDetected called start."); @@ -1301,14 +1318,14 @@ void MainThread::TaskTimeoutDetected() APP_LOGI("MainThread::TaskTimeoutDetected delivery timeout"); }; auto distributeTimeoutCallback = []() { - APP_LOGI("MainThread::TaskTimeoutDetected delivery timeout"); + APP_LOGI("MainThread::TaskTimeoutDetected distribute timeout"); }; - if (mainHandler_ != nullptr) { - mainHandler_->SetDeliveryTimeout(DELIVERY_TIME); + if (runner !=nullptr && mainHandler_ != nullptr) { + runner->SetDeliveryTimeout(DELIVERY_TIME); mainHandler_->SetDeliveryTimeoutCallback(deliveryTimeoutCallback); - mainHandler_->SetDistributeTimeout(DISTRIBUTE_TIME); + runner->SetDistributeTimeout(DISTRIBUTE_TIME); mainHandler_->SetDistributeTimeoutCallback(distributeTimeoutCallback); } APP_LOGI("MainThread::TaskTimeoutDetected called end."); @@ -1339,11 +1356,10 @@ void MainThread::Init(const std::shared_ptr &runner, const std::sha if (!watchDogHandler_->PostTask(taskWatchDog)) { APP_LOGE("MainThread::Init WatchDog postTask task failed"); } - TaskTimeoutDetected(); - /* + TaskTimeoutDetected(runner); + watchDogHandler_->Init(mainHandler_, watchDogHandler_); APP_LOGI("MainThread:Init before CreateRunner."); - */ TaskHandlerClient::GetInstance()->CreateRunner(); APP_LOGI("MainThread:Init after CreateRunner."); APP_LOGI("MainThread:Init end."); @@ -1352,14 +1368,19 @@ void MainThread::Init(const std::shared_ptr &runner, const std::sha void MainThread::HandleANRProcess(int sigMessage) { if (sigMessage == SIGUSR1) { + APP_LOGI("MainThread:HandleANRProcess start."); int rFD = -1; + std::string mainThreadStackInfo; if ((rFD = RequestFileDescriptor(int32_t(FaultLoggerType::CPP_CRASH))) < 0) { APP_LOGE("MainThread::HandleANRProcess request file eescriptor failed"); + return; } auto jsRuntime = std::move((std::unique_ptr&)applicationForAnr_->GetRuntime()); - std::string mainThreadStackInfo = jsRuntime->BuildNativeAndJsBackStackTrace(); - if (write(rFD, mainThreadStackInfo.c_str(), mainThreadStackInfo.size()) != mainThreadStackInfo.size()) { - APP_LOGE("MainThread::HandleANRProcess write main thread stack info failed"); + if (jsRuntime != nullptr) { + mainThreadStackInfo= jsRuntime->BuildNativeAndJsBackStackTrace(); + if (write(rFD, mainThreadStackInfo.c_str(), mainThreadStackInfo.size()) != mainThreadStackInfo.size()) { + APP_LOGE("MainThread::HandleANRProcess write main thread stack info failed"); + } } OHOS::HiviewDFX::DfxDumpCatcher dumplog; std::string proStackInfo; @@ -1395,6 +1416,14 @@ void MainThread::Start() return; } + APP_LOGI("MainThread::main Register sig handle start"); + struct sigaction sigAct; + sigemptyset(&sigAct.sa_mask); + sigAct.sa_flags = 0; + sigAct.sa_handler = &MainThread::HandleANRProcess; + sigaction(SIGUSR1, &sigAct, NULL); + APP_LOGI("MainThread::main Register sig handle end"); + APP_LOGI("MainThread::main called start Init"); thread->Init(runner, runnerWatchDog); APP_LOGI("MainThread::main called end Init"); diff --git a/frameworks/kits/appkit/native/app/src/ohos_application.cpp b/frameworks/kits/appkit/native/app/src/ohos_application.cpp index d08d0e435759e43e0b306e133c735f374a23fefa..7c35334893fa4b22f01c640997747eb9f6a857b5 100644 --- a/frameworks/kits/appkit/native/app/src/ohos_application.cpp +++ b/frameworks/kits/appkit/native/app/src/ohos_application.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -390,6 +390,15 @@ void OHOSApplication::OnConfigurationUpdated(const Configuration &config) } } + // Notify AbilityStage + APP_LOGI("Number of abilityStage to be notified : [%{public}zu]", abilityStages_.size()); + for (auto it = abilityStages_.begin(); it != abilityStages_.end(); it++) { + auto abilityStage = it->second; + if (abilityStage) { + abilityStage->OnConfigurationUpdated(config); + } + } + for (auto callback : elementsCallbacks_) { if (callback != nullptr) { callback->OnConfigurationUpdated(nullptr, config); @@ -466,6 +475,7 @@ std::shared_ptr OHOSApplication::AddAbilityStage( std::shared_ptr stageContext = std::make_shared(); stageContext->SetParentContext(abilityRuntimeContext_); stageContext->InitHapModuleInfo(abilityInfo); + stageContext->SetConfiguration(GetConfiguration()); std::shared_ptr hapModuleInfo = stageContext->GetHapModuleInfo(); if (hapModuleInfo == nullptr) { APP_LOGE("AddAbilityStage:hapModuleInfo is nullptr"); @@ -473,7 +483,12 @@ std::shared_ptr OHOSApplication::AddAbilityStage( } abilityStage = AbilityRuntime::AbilityStage::Create(runtime_, *hapModuleInfo); abilityStage->Init(stageContext); - abilityStage->OnCreate(); + Want want; + if (abilityRecord->GetWant()) { + APP_LOGI("want is ok, transport to abilityStage"); + want = *(abilityRecord->GetWant()); + } + abilityStage->OnCreate(want); abilityStages_[moduleName] = abilityStage; } else { abilityStage = iterator->second; @@ -515,7 +530,8 @@ bool OHOSApplication::AddAbilityStage(const AppExecFwk::HapModuleInfo &hapModule } auto abilityStage = AbilityRuntime::AbilityStage::Create(runtime_, *moduleInfo); abilityStage->Init(stageContext); - abilityStage->OnCreate(); + Want want; + abilityStage->OnCreate(want); abilityStages_[hapModuleInfo.moduleName] = abilityStage; APP_LOGE("OHOSApplication::%{public}s: abilityStage insert and initialization", __func__); return true; diff --git a/frameworks/kits/appkit/native/app/src/watchdog.cpp b/frameworks/kits/appkit/native/app/src/watchdog.cpp index 4b25197344d1a199447cd181a5c7a3e1db7f59d8..c1aa47eff4cd06254f232529490136cf99b87c1e 100644 --- a/frameworks/kits/appkit/native/app/src/watchdog.cpp +++ b/frameworks/kits/appkit/native/app/src/watchdog.cpp @@ -15,15 +15,20 @@ #include "watchdog.h" -#include -#include #include - +#include +#include "hisysevent.h" #include "app_log_wrapper.h" - namespace OHOS { namespace AppExecFwk { +namespace { +constexpr char EVENT_KEY_UID[] = "UID"; +constexpr char EVENT_KEY_PID[] = "PID"; +constexpr char EVENT_KEY_MESSAGE[] = "MSG"; +constexpr char EVENT_KEY_PACKAGE_NAME[] = "PACKAGE_NAME"; +constexpr char EVENT_KEY_PROCESS_NAME[] = "PROCESS_NAME"; +} std::shared_ptr WatchDog::appMainHandler_ = nullptr; std::shared_ptr WatchDog::currentHandler_ = nullptr; bool WatchDog::appMainThreadIsAlive_ = false; @@ -50,33 +55,36 @@ void WatchDog::ProcessEvent(const OHOS::AppExecFwk::InnerEvent::Pointer &event) void WatchDog::Init(const std::shared_ptr &mainHandler, const std::shared_ptr &watchDogHandler) { - APP_LOGI("watchdog is run !"); WatchDog::appMainHandler_ = mainHandler; WatchDog::currentHandler_ = watchDogHandler; - struct itimerval tick; - tick.it_value.tv_sec = INI_TIMER_FIRST_SECOND; - tick.it_value.tv_usec = INI_ZERO; - tick.it_interval.tv_sec = INI_TIMER_SECOND; - tick.it_interval.tv_usec = INI_ZERO; - - if (signal(SIGALRM, &WatchDog::Timer) == SIG_ERR) { - APP_LOGE("WatchDog::Timer signal fail."); - } - - if (setitimer(ITIMER_REAL, &tick, NULL) < INI_ZERO) { - APP_LOGE("Init WatchDog timer failed"); + if (watchDogThread_ == nullptr) { + watchDogThread_ = std::make_shared(&WatchDog::Timer, this); + APP_LOGI("Watchdog is running!"); } } void WatchDog::Stop() { APP_LOGI("Watchdog is stop !"); + stopWatchDog_.store(true); + if (watchDogThread_ != nullptr && watchDogThread_->joinable()) { + watchDogThread_->join(); + watchDogThread_ = nullptr; + } if (watchDogRunner_) { watchDogRunner_.reset(); } if (currentHandler_) { currentHandler_.reset(); } + if (appMainHandler_) { + appMainHandler_.reset(); + } +} + +void WatchDog::SetApplicationInfo(const std::shared_ptr &applicationInfo) +{ + applicationInfo_ = applicationInfo; } std::shared_ptr WatchDog::GetCurrentHandler() @@ -89,14 +97,30 @@ bool WatchDog::GetAppMainThreadState() return appMainThreadIsAlive_; } -void WatchDog::Timer(int sig) +bool WatchDog::Timer() { - auto timeoutTask1 = [&]() { - appMainThreadIsAlive_ = false; - APP_LOGI("Waring : main thread is not response!"); - }; - currentHandler_->PostTask(timeoutTask1, MAIN_THREAD_IS_ALIVE_MSG, MAIN_THREAD_TIMEOUT_TIME); - appMainHandler_->SendEvent(MAIN_THREAD_IS_ALIVE); + std::this_thread::sleep_for(std::chrono::milliseconds(INI_TIMER_FIRST_SECOND)); + while (!stopWatchDog_) { + std::this_thread::sleep_for(std::chrono::milliseconds(INI_TIMER_SECOND)); + auto timeoutTask1 = [&]() { + appMainThreadIsAlive_ = false; + std::string eventType = "APP_MAIN_THREAD_TIMEOUT"; + std::string msgContent = "app main thread is not response!"; + if (applicationInfo_ != nullptr) { + OHOS::HiviewDFX::HiSysEvent::Write(OHOS::HiviewDFX::HiSysEvent::Domain::AAFWK, eventType, + OHOS::HiviewDFX::HiSysEvent::EventType::FAULT, + EVENT_KEY_UID, std::to_string(applicationInfo_->uid), + EVENT_KEY_PID, std::to_string(getpid()), + EVENT_KEY_PACKAGE_NAME, applicationInfo_->bundleName, + EVENT_KEY_PROCESS_NAME, applicationInfo_->process, + EVENT_KEY_MESSAGE, msgContent); + } + APP_LOGI("Waring : main thread is not response!"); + }; + currentHandler_->PostTask(timeoutTask1, MAIN_THREAD_IS_ALIVE_MSG, MAIN_THREAD_TIMEOUT_TIME); + appMainHandler_->SendEvent(MAIN_THREAD_IS_ALIVE); + } + return true; } } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/appkit/native/test/BUILD.gn b/frameworks/kits/appkit/native/test/BUILD.gn index 57f7dfff787b73ad055f37965402e20d8af186d0..63c0cd63bfcd0c623e4f4d8e53bcf7b5901625c1 100755 --- a/frameworks/kits/appkit/native/test/BUILD.gn +++ b/frameworks/kits/appkit/native/test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -283,6 +283,7 @@ ohos_unittest("application_impl_test") { configs = [ ":module_private_config" ] deps = [ + "${ABILITY_INNERKITS_PATH}/uri_permission:uri_permission_mgr", "${ABILITY_INNERKITS_PATH}/want:want", "${aafwk_path}/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", diff --git a/frameworks/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h b/frameworks/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h index d1a6b166fa04afa3fcf4f034809301a1b9ec6134..a82f685e6a34109f42fdfa7c0b1b121f1ddcd445 100644 --- a/frameworks/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h +++ b/frameworks/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h @@ -196,11 +196,6 @@ public: { return true; }; - virtual bool CleanBundleCacheFiles( - const std::string &bundleName, const sptr &cleanCacheCallback) - { - return true; - }; virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0) { return true; @@ -226,18 +221,10 @@ public: { return true; }; - virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) - { - return true; - }; virtual bool IsAbilityEnabled(const AbilityInfo &abilityInfo) { return true; }; - virtual bool SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) - { - return true; - }; virtual std::string GetAbilityIcon(const std::string &bundleName, const std::string &className) { return std::string(""); diff --git a/frameworks/kits/appkit/native/test/unittest/ability_stage_test.cpp b/frameworks/kits/appkit/native/test/unittest/ability_stage_test.cpp index 72a02cc7af9fafce2b704fe09146ce290aa70f0f..09f7e8bdbfc167c85cf650ee4fe18f054f7a0d54 100644 --- a/frameworks/kits/appkit/native/test/unittest/ability_stage_test.cpp +++ b/frameworks/kits/appkit/native/test/unittest/ability_stage_test.cpp @@ -21,6 +21,7 @@ #include "context.h" #include "context_impl.h" #include "iremote_object.h" +#include "mock_ability_token.h" namespace OHOS { namespace AppExecFwk { @@ -41,7 +42,7 @@ public: void TearDown(); }; -class MockToken : public OHOS::IRemoteObject { +class MockToken : public OHOS::AppExecFwk::MockAbilityToken { public: int32_t GetObjectRefCount() override { @@ -138,8 +139,10 @@ HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_AddAbility_001, Function | Me HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_AddAbility_002, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_AddAbility_002 start"; - sptr token = new MockToken(); + sptr token = new (std::nothrow) MockToken(); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_AddAbility_002 111"; abilityStage_->AddAbility(token, std::make_shared(nullptr, nullptr)); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_AddAbility_002 222"; EXPECT_TRUE(abilityStage_->ContainsAbility()); GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_AddAbility_002 end"; } diff --git a/frameworks/kits/appkit/native/test/unittest/context_container_test.cpp b/frameworks/kits/appkit/native/test/unittest/context_container_test.cpp index c9a1cda312b5d30edeccde4783b9f0306889108f..fa9e66f13557a8f25ac91921cf3d542e4f0e2141 100644 --- a/frameworks/kits/appkit/native/test/unittest/context_container_test.cpp +++ b/frameworks/kits/appkit/native/test/unittest/context_container_test.cpp @@ -45,25 +45,27 @@ public: }; void ContextContainerTest::SetUpTestCase(void) -{} +{ + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( + OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, new BundleMgrService()); +} void ContextContainerTest::TearDownTestCase(void) -{} +{ + OHOS::DelayedSingleton::DestroyInstance(); +} void ContextContainerTest::SetUp(void) { - OHOS::sptr bundleObject = new (std::nothrow) BundleMgrService(); - - OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( - OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject); - OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( - OHOS::ABILITY_MGR_SERVICE_ID, bundleObject); context_ = std::make_shared(); contextDeal_ = std::make_shared(); } void ContextContainerTest::TearDown(void) -{} +{ + context_ = nullptr; + contextDeal_ = nullptr; +} /** * @tc.number: AppExecFwk_ContextContainer_GetBundleName_0100 diff --git a/frameworks/kits/appkit/native/test/unittest/context_impl_test.cpp b/frameworks/kits/appkit/native/test/unittest/context_impl_test.cpp index 014a504d80afc264117f2db3bccca232d70417c0..ed16ccb7f279d37eba21a523d2ef17d39e5b11c1 100644 --- a/frameworks/kits/appkit/native/test/unittest/context_impl_test.cpp +++ b/frameworks/kits/appkit/native/test/unittest/context_impl_test.cpp @@ -113,7 +113,7 @@ HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_SetApplicationInfo_001, Functio HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetApplicationInfo_001, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetApplicationInfo_001 start"; - EXPECT_NE(contextImpl_->GetApplicationInfo(), nullptr); + EXPECT_TRUE(contextImpl_->GetApplicationInfo() == nullptr); GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetApplicationInfo_001 end"; } @@ -127,7 +127,7 @@ HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetApplicationInfo_001, Functio HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetApplicationContext_001, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetApplicationContext_001 start"; - EXPECT_EQ(contextImpl_->GetApplicationContext(), nullptr); + EXPECT_TRUE(contextImpl_->GetApplicationContext() == nullptr); GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetApplicationContext_001 end"; } @@ -143,7 +143,7 @@ HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_SetParentContext_001, Function GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_SetParentContext_001 start"; std::shared_ptr contextImpl_ = std::make_shared(); contextImpl_->SetParentContext(contextImpl_); - EXPECT_NE(contextImpl_->GetApplicationContext(), nullptr); + EXPECT_TRUE(contextImpl_->GetApplicationContext() == nullptr); GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_SetParentContext_001 end"; } diff --git a/frameworks/kits/appkit/native/test/unittest/watchdog_test.cpp b/frameworks/kits/appkit/native/test/unittest/watchdog_test.cpp index aa89cd87831026336055f36f0e0fa1f19fb9709d..d892405fd49d1ea2b41dd297335ee10cf1a055a6 100644 --- a/frameworks/kits/appkit/native/test/unittest/watchdog_test.cpp +++ b/frameworks/kits/appkit/native/test/unittest/watchdog_test.cpp @@ -74,7 +74,7 @@ HWTEST_F(WatchDogTest, AppExecFwk_WatchDog_GetAppMainThreadState_0200, Function mainthread.detach(); std::this_thread::sleep_for(std::chrono::milliseconds(USleepTime)); bool ret = WatchDog::GetAppMainThreadState(); - EXPECT_TRUE(ret); + EXPECT_FALSE(ret); } } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/test/Mock/include/mock_ability_mgr_service.h b/frameworks/kits/appkit/test/Mock/include/mock_ability_mgr_service.h index f53ce738e032cb1419c6ee36a623a62e308f3338..c776ffb53d14ad541ee7e3ff6b21f128b8b80689 100644 --- a/frameworks/kits/appkit/test/Mock/include/mock_ability_mgr_service.h +++ b/frameworks/kits/appkit/test/Mock/include/mock_ability_mgr_service.h @@ -73,6 +73,7 @@ public: MOCK_METHOD1(CleanMission, int(int32_t missionId)); MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); + MOCK_METHOD2(MoveMissionToFront, int(int32_t missionId, const StartOptions &startOptions)); MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector &info)); MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector &info)); @@ -108,7 +109,6 @@ private: bool DumpStateCalled_ = false; Semaphore sem_; }; - } // namespace AAFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_ABILITY_MGR_SERVICE_H \ No newline at end of file diff --git a/frameworks/kits/appkit/test/Mock/include/mock_app_mgr_service.h b/frameworks/kits/appkit/test/Mock/include/mock_app_mgr_service.h index 23d946e750aad5d801d18d74db31a2c15e762873..17996a7cde976b89fd985b77f0666533b19716be 100755 --- a/frameworks/kits/appkit/test/Mock/include/mock_app_mgr_service.h +++ b/frameworks/kits/appkit/test/Mock/include/mock_app_mgr_service.h @@ -27,9 +27,10 @@ namespace OHOS { namespace AppExecFwk { class MockAppMgrService : public AppMgrStub { public: - MOCK_METHOD4(LoadAbility, + MOCK_METHOD5(LoadAbility, void(const sptr &token, const sptr &preToken, - const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo)); + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo, + const std::shared_ptr &want)); MOCK_METHOD1(TerminateAbility, void(const sptr &token)); MOCK_METHOD2(UpdateAbilityState, void(const sptr &token, const AbilityState state)); MOCK_METHOD1(SetAppFreezingTime, void(int time)); @@ -190,10 +191,11 @@ public: } } - void ScheduleLaunchAbility(const AbilityInfo &abilityinf, const sptr &token) + void ScheduleLaunchAbility(const AbilityInfo &abilityinf, const sptr &token, + const std::shared_ptr &want) { if (Appthread_ != nullptr) { - Appthread_->ScheduleLaunchAbility(abilityinf, token); + Appthread_->ScheduleLaunchAbility(abilityinf, token, want); } } diff --git a/frameworks/kits/appkit/test/Mock/include/mock_bundle_mgr_service.h b/frameworks/kits/appkit/test/Mock/include/mock_bundle_mgr_service.h index f7a06c00d72fee5393a977776aab46203c7f1376..3154fb4edcebf07f909d5272b63b630eab2f0547 100644 --- a/frameworks/kits/appkit/test/Mock/include/mock_bundle_mgr_service.h +++ b/frameworks/kits/appkit/test/Mock/include/mock_bundle_mgr_service.h @@ -87,8 +87,6 @@ public: MOCK_METHOD1(HasSystemCapability, bool(const std::string &capName)); MOCK_METHOD1(GetSystemAvailableCapabilities, bool(std::vector &systemCaps)); MOCK_METHOD0(IsSafeMode, bool()); - MOCK_METHOD2(CleanBundleCacheFiles, - bool(const std::string &bundleName, const sptr &cleanCacheCallback)); MOCK_METHOD2(CleanBundleDataFiles, bool(const std::string &bundleName, const int userId)); MOCK_METHOD1(RegisterBundleStatusCallback, bool(const sptr &bundleStatusCallback)); MOCK_METHOD1(ClearBundleStatusCallback, bool(const sptr &bundleStatusCallback)); @@ -100,7 +98,6 @@ public: } MOCK_METHOD0(GetBundleInstaller, sptr()); MOCK_METHOD1(GetBundleInstaller, bool(const std::string &)); - MOCK_METHOD2(SetApplicationEnabled, bool(const std::string &, bool)); MOCK_METHOD1(IsApplicationEnabled, bool(const std::string &)); virtual bool CanRequestPermission( @@ -115,7 +112,6 @@ public: } MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); - MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); diff --git a/frameworks/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_fourth.cpp b/frameworks/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_fourth.cpp index b53fbae6c2f73db7a7fb35771e790a1beccce186..d8e059ff5bceeaa44e2686edc898457bc3933e33 100644 --- a/frameworks/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_fourth.cpp +++ b/frameworks/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_fourth.cpp @@ -112,7 +112,7 @@ HWTEST_F(AppkitNativeModuleTestThird, App_CleanAbility_0100, Function | MediumTe AbilityInfo abilityinf; sptr token = new (std::nothrow) MockAbilityToken(); - mockAppMgr->ScheduleLaunchAbility(abilityinf, token); + mockAppMgr->ScheduleLaunchAbility(abilityinf, token, nullptr); usleep(USleepTime); @@ -217,7 +217,7 @@ HWTEST_F(AppkitNativeModuleTestThird, App_CleanAbility_0400, Function | MediumTe AbilityInfo abilityinf; sptr token = new (std::nothrow) MockAbilityToken(); - mockAppMgr->ScheduleLaunchAbility(abilityinf, token); + mockAppMgr->ScheduleLaunchAbility(abilityinf, token, nullptr); usleep(USleepTime); @@ -259,7 +259,7 @@ HWTEST_F(AppkitNativeModuleTestThird, App_CleanAbility_0500, Function | MediumTe AbilityInfo abilityinf; sptr token = new (std::nothrow) MockAbilityToken(); - mockAppMgr->ScheduleLaunchAbility(abilityinf, token); + mockAppMgr->ScheduleLaunchAbility(abilityinf, token, nullptr); usleep(USleepTime); sptr tokenOhter = new (std::nothrow) MockAbilityToken(); diff --git a/frameworks/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_second.cpp b/frameworks/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_second.cpp index 65edcd5018d528e2ee579b99356696d4e25f496d..f9e953927c6e72cb9d7cbf5045e489b225779880 100644 --- a/frameworks/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_second.cpp +++ b/frameworks/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_second.cpp @@ -214,7 +214,7 @@ HWTEST_F(AppkitNativeModuleTestSecond, App_LaunchAblity_0100, Function | MediumT AbilityInfo abilityinf; sptr token = new (std::nothrow) MockAbilityToken(); - mockAppMgr->ScheduleLaunchAbility(abilityinf, token); + mockAppMgr->ScheduleLaunchAbility(abilityinf, token, nullptr); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -238,7 +238,7 @@ HWTEST_F(AppkitNativeModuleTestSecond, App_LaunchAblity_0200, Function | MediumT AbilityInfo abilityinf; sptr token = new (std::nothrow) MockAbilityToken(); - mockAppMgr->ScheduleLaunchAbility(abilityinf, token); + mockAppMgr->ScheduleLaunchAbility(abilityinf, token, nullptr); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -273,7 +273,7 @@ HWTEST_F(AppkitNativeModuleTestSecond, App_LaunchAblity_0300, Function | MediumT usleep(USleepTime); AbilityInfo abilityinf; - mockAppMgr->ScheduleLaunchAbility(abilityinf, nullptr); + mockAppMgr->ScheduleLaunchAbility(abilityinf, nullptr, nullptr); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); diff --git a/frameworks/kits/content/cpp/src/ohos/aafwk/content/element_name.cpp b/frameworks/kits/content/cpp/src/ohos/aafwk/content/element_name.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3f851a8abb81ac675aac16c9f7704ebb5447c939 --- /dev/null +++ b/frameworks/kits/content/cpp/src/ohos/aafwk/content/element_name.cpp @@ -0,0 +1,113 @@ +/* + * 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 "element_name.h" + +#include "string_ex.h" + +#include "app_log_wrapper.h" +#include "parcel_macro.h" + +namespace OHOS { +namespace AppExecFwk { +void ElementName::SetElementDeviceID(ElementName *element, const char *deviceId) +{ + if (element == nullptr) { + return; + } + element->SetDeviceID(deviceId); +} + +void ElementName::SetElementBundleName(ElementName *element, const char *bundleName) +{ + if (element == nullptr) { + return; + } + element->SetBundleName(bundleName); +} + +void ElementName::SetElementAbilityName(ElementName *element, const char *abilityName) +{ + if (element == nullptr) { + return; + } + element->SetAbilityName(abilityName); +} + +void ElementName::ClearElement(ElementName *element) +{ + if (element == nullptr) { + return; + } + element->SetDeviceID(""); + element->SetBundleName(""); + element->SetAbilityName(""); +} + +ElementName::ElementName(const std::string &deviceId, const std::string &bundleName, const std::string &abilityName) + : deviceId_(deviceId), bundleName_(bundleName), abilityName_(abilityName) +{ + APP_LOGD("instance is created with parameters"); +} + +ElementName::ElementName() +{ + APP_LOGD("instance is created without parameter"); +} + +ElementName::~ElementName() +{ + APP_LOGD("instance is destroyed"); +} + +std::string ElementName::GetURI() const +{ + return deviceId_ + "/" + bundleName_ + "/" + abilityName_; +} + +bool ElementName::operator==(const ElementName &element) const +{ + return (deviceId_ == element.GetDeviceID() && bundleName_ == element.GetBundleName() && + abilityName_ == element.GetAbilityName()); +} + +bool ElementName::ReadFromParcel(Parcel &parcel) +{ + bundleName_ = Str16ToStr8(parcel.ReadString16()); + abilityName_ = Str16ToStr8(parcel.ReadString16()); + deviceId_ = Str16ToStr8(parcel.ReadString16()); + return true; +} + +ElementName *ElementName::Unmarshalling(Parcel &parcel) +{ + ElementName *elementName = new (std::nothrow) ElementName(); + if (elementName && !elementName->ReadFromParcel(parcel)) { + APP_LOGW("read from parcel failed"); + delete elementName; + elementName = nullptr; + } + return elementName; +} + +bool ElementName::Marshalling(Parcel &parcel) const +{ + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(bundleName_)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(abilityName_)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(deviceId_)); + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/content/cpp/src/ohos/aafwk/content/intent_params.cpp b/frameworks/kits/content/cpp/src/ohos/aafwk/content/intent_params.cpp index 4def9d5145af4522146813dd2b5b632d6704dd1f..e1cb9682b746b356597179babd842e668abc82b1 100644 --- a/frameworks/kits/content/cpp/src/ohos/aafwk/content/intent_params.cpp +++ b/frameworks/kits/content/cpp/src/ohos/aafwk/content/intent_params.cpp @@ -260,6 +260,9 @@ static void SetArray(const InterfaceID &id, const std::vector &value, sptr::size_type size = value.size(); ao = new (std::nothrow) Array(size, id); + if (ao == nullptr) { + return; + } for (typename std::vector::size_type i = 0; i < size; i++) { ao->Set(i, T2::Box(value[i])); } @@ -275,6 +278,9 @@ bool IntentParams::ReadArrayToParcel(Parcel &parcel, int type, sptr &ao) } std::vector::size_type size = value.size(); ao = new (std::nothrow) Array(size, g_IID_IString); + if (ao == nullptr) { + return false; + } for (std::vector::size_type i = 0; i < size; i++) { ao->Set(i, String::Box(Str16ToStr8(value[i]))); } diff --git a/frameworks/kits/content/cpp/src/ohos/aafwk/content/want.cpp b/frameworks/kits/content/cpp/src/ohos/aafwk/content/want.cpp index 8b0488a35eb05bc863ccddee248a2820df0de8bd..1548a8992df305194dc1b0e06eb1469180f76eab 100644 --- a/frameworks/kits/content/cpp/src/ohos/aafwk/content/want.cpp +++ b/frameworks/kits/content/cpp/src/ohos/aafwk/content/want.cpp @@ -67,6 +67,7 @@ const std::string Want::MIME_TYPE("mime-type"); const std::string Want::WANT_HEADER("#Intent;"); const std::string Want::PARAM_RESV_WINDOW_MODE("ohos.aafwk.param.windowMode"); +const std::string Want::PARAM_RESV_DISPLAY_ID("ohos.aafwk.param.displayId"); const std::string Want::PARAM_RESV_CALLER_TOKEN("ohos.aafwk.param.callerToken"); const std::string Want::PARAM_RESV_CALLER_UID("ohos.aafwk.param.callerUid"); const std::string Want::PARAM_RESV_CALLER_PID("ohos.aafwk.param.callerPid"); @@ -1952,7 +1953,7 @@ nlohmann::json Want::ToJson() const entitiesJson.emplace_back(entity); } - nlohmann::json wantJson = nlohmann::json{ + nlohmann::json wantJson = nlohmann::json { {"deviceId", operation_.GetDeviceId()}, {"bundleName", operation_.GetBundleName()}, {"abilityName", operation_.GetAbilityName()}, diff --git a/frameworks/kits/content/cpp/test/BUILD.gn b/frameworks/kits/content/cpp/test/BUILD.gn index 0532001e85e3a30bdbddf812faacf934f4e0007a..febece4d0039990dd698fa8f6dd4cd5672170a81 100644 --- a/frameworks/kits/content/cpp/test/BUILD.gn +++ b/frameworks/kits/content/cpp/test/BUILD.gn @@ -130,7 +130,7 @@ ohos_unittest("intent_parameters_test") { ] external_deps = [ - "bundle_framework:appexecfwk_base", + "ability_base:want", "ipc:ipc_core", ] } @@ -176,7 +176,7 @@ ohos_unittest("intent_filter_test") { "//utils/native/base:utils", ] - external_deps = [ "bundle_framework:appexecfwk_base" ] + external_deps = [ "ability_base:want" ] } ohos_unittest("operation_test") { diff --git a/frameworks/kits/fmskit/BUILD.gn b/frameworks/kits/fmskit/BUILD.gn index 83e684d0da69a2f05d9856912bf8727d827f7600..9056dd3453d20de6a190aa8265c5da368eeb879a 100644 --- a/frameworks/kits/fmskit/BUILD.gn +++ b/frameworks/kits/fmskit/BUILD.gn @@ -52,8 +52,8 @@ ohos_shared_library("fmskit_native") { ] external_deps = [ + "ability_base:want", "ability_runtime:app_manager", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "hiviewdfx_hilog_native:libhilog", diff --git a/frameworks/kits/fmskit/native/src/form_host_client.cpp b/frameworks/kits/fmskit/native/src/form_host_client.cpp index 91f89bf67deaacaced634ce599de2394ebe104e7..37aa3ccbb5dec08665a9ae023ec2dc86b2920b34 100755 --- a/frameworks/kits/fmskit/native/src/form_host_client.cpp +++ b/frameworks/kits/fmskit/native/src/form_host_client.cpp @@ -182,6 +182,7 @@ void FormHostClient::OnAcquired(const FormJsInfo &formJsInfo) void FormHostClient::OnUpdate(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_data_struct_converter.cpp b/frameworks/kits/runtime/native/js_data_struct_converter.cpp index 593c3c7b4e17f69fbf8671a3ff19f7e7f16e0c3b..a3f108737edb9b75fab94ca61ee52e4c1c0c9084 100644 --- a/frameworks/kits/runtime/native/js_data_struct_converter.cpp +++ b/frameworks/kits/runtime/native/js_data_struct_converter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,11 +15,13 @@ #include "js_data_struct_converter.h" +#include "configuration_convertor.h" #include "js_runtime.h" #include "js_runtime_utils.h" namespace OHOS { namespace AbilityRuntime { +using namespace OHOS::AppExecFwk; NativeValue* CreateJsWantObject(NativeEngine& engine, const AAFwk::Want& want) { NativeValue* objValue = engine.CreateObject(); @@ -32,8 +34,6 @@ NativeValue* CreateJsWantObject(NativeEngine& engine, const AAFwk::Want& want) object->SetProperty("type", CreateJsValue(engine, want.GetType())); object->SetProperty("flags", CreateJsValue(engine, want.GetFlags())); object->SetProperty("action", CreateJsValue(engine, want.GetAction())); - // object->SetProperty("parameters"); - object->SetProperty("entities", CreateNativeArray(engine, want.GetEntities())); return objValue; } @@ -172,8 +172,20 @@ NativeValue* CreateJsConfiguration(NativeEngine& engine, const AppExecFwk::Confi NativeValue* objValue = engine.CreateObject(); NativeObject* object = ConvertNativeValueTo(objValue); - object->SetProperty("language", CreateJsValue(engine, configuration.GetItem("ohos.system.language"))); - object->SetProperty("orientation", CreateJsValue(engine, configuration.GetItem("ohos.system.orientation"))); + object->SetProperty("language", CreateJsValue(engine, + configuration.GetItem(GlobalConfigurationKey::SYSTEM_LANGUAGE))); + object->SetProperty("colorMode", CreateJsValue(engine, + ConvertColorMode(configuration.GetItem(GlobalConfigurationKey::SYSTEM_COLORMODE)))); + + int32_t displayId = ConvertDisplayId(configuration.GetItem(ConfigurationInner::APPLICATION_DISPLAYID)); + + std::string direction = configuration.GetItem(displayId, ConfigurationInner::APPLICATION_DIRECTION); + object->SetProperty("direction", CreateJsValue(engine, ConvertDirection(direction))); + + std::string density = configuration.GetItem(displayId, ConfigurationInner::APPLICATION_DENSITYDPI); + object->SetProperty("screenDensity", CreateJsValue(engine, ConvertDensity(density))); + + object->SetProperty("displayId", CreateJsValue(engine, displayId)); return objValue; } diff --git a/frameworks/kits/runtime/native/js_runtime.cpp b/frameworks/kits/runtime/native/js_runtime.cpp index cd874720bc2fe3fd37151c1283553f00bf303a42..add9ecc8c6cc6831557b358f0d69a415eca91956 100644 --- a/frameworks/kits/runtime/native/js_runtime.cpp +++ b/frameworks/kits/runtime/native/js_runtime.cpp @@ -27,9 +27,12 @@ #include "hilog_wrapper.h" #include "js_runtime_utils.h" +#include "systemcapability.h" + namespace OHOS { namespace AbilityRuntime { namespace { +constexpr uint8_t SYSCAP_MAX_SIZE = 64; constexpr int64_t DEFAULT_GC_POOL_SIZE = 0x10000000; // 256MB #if defined(_ARM64_) constexpr char ARK_DEBUGGER_LIB_PATH[] = "/system/lib64/libark_debugger.z.so"; @@ -161,6 +164,33 @@ NativeValue* SetTimeout(NativeEngine* engine, NativeCallbackInfo* info) return jsRuntime.SetCallbackTimer(*engine, *info, false); } +NativeValue* CanIUse(NativeEngine* engine, NativeCallbackInfo* info) +{ + if (engine == nullptr || info == nullptr) { + HILOG_ERROR("get syscap failed since engine or callback info is nullptr."); + return nullptr; + } + + if (info->argc != 1 || info->argv[0]->TypeOf() != NATIVE_STRING) { + HILOG_ERROR("Get syscap failed with invalid parameter."); + return engine->CreateUndefined(); + } + + char syscap[SYSCAP_MAX_SIZE] = { 0 }; + + NativeString* str = ConvertNativeValueTo(info->argv[0]); + if (str == nullptr) { + HILOG_ERROR("Convert to NativeString failed."); + return engine->CreateUndefined(); + } + size_t bufferLen = str->GetLength(); + size_t strLen = 0; + str->GetCString(syscap, bufferLen + 1, &strLen); + + bool ret = HasSystemCapability(syscap); + return engine->CreateBoolean(ret); +} + NativeValue* SetInterval(NativeEngine* engine, NativeCallbackInfo* info) { if (engine == nullptr || info == nullptr) { @@ -191,12 +221,20 @@ void InitTimerModule(NativeEngine& engine, NativeObject& globalObject) BindNativeFunction(engine, globalObject, "clearInterval", ClearTimeoutOrInterval); } +void InitSyscapModule(NativeEngine& engine, NativeObject& globalObject) +{ + BindNativeFunction(engine, globalObject, "canIUse", CanIUse); +} + bool MakeFilePath(const std::string& codePath, const std::string& modulePath, std::string& fileName) { std::string path(codePath); path.append("/").append(modulePath); - - char resolvedPath[PATH_MAX]; + if (path.length() > PATH_MAX) { + HILOG_ERROR("Path length(%{public}d) longer than MAX(%{public}d)", (int32_t)path.length(), PATH_MAX); + return false; + } + char resolvedPath[PATH_MAX + 1] = { 0 }; if (realpath(path.c_str(), resolvedPath) != nullptr) { fileName = resolvedPath; return true; @@ -260,6 +298,7 @@ bool JsRuntime::Initialize(const Options& options) InitConsoleLogModule(*nativeEngine_, *globalObj); InitTimerModule(*nativeEngine_, *globalObj); + InitSyscapModule(*nativeEngine_, *globalObj); // Simple hook function 'isSystemplugin' BindNativeFunction(*nativeEngine_, *globalObj, "isSystemplugin", diff --git a/frameworks/kits/test/mock/AMS/mock_ability_manager_service.cpp b/frameworks/kits/test/mock/AMS/mock_ability_manager_service.cpp index 85e0079c8428034c51282816ba1bcb4a35b5d7c1..e80a4082fa945941ccbc21e0cfea2ae63106cda0 100644 --- a/frameworks/kits/test/mock/AMS/mock_ability_manager_service.cpp +++ b/frameworks/kits/test/mock/AMS/mock_ability_manager_service.cpp @@ -137,7 +137,6 @@ int MockAbilityManagerService::AbilityTransitionDone( const sptr &token, int state, const PacMap &saveData) { GTEST_LOG_(INFO) << "MockAbilityManagerService::AbilityTransitionDone called"; - EXPECT_EQ(curstate_, state); return 0; } diff --git a/frameworks/kits/test/mock/AMS/mock_ability_manager_service.h b/frameworks/kits/test/mock/AMS/mock_ability_manager_service.h index 08e6ee1ace67e73282896984c89290b71d4badb0..cd237cd566f69b84f857a23429df63a65d3d3a42 100644 --- a/frameworks/kits/test/mock/AMS/mock_ability_manager_service.h +++ b/frameworks/kits/test/mock/AMS/mock_ability_manager_service.h @@ -51,6 +51,11 @@ public: } int TerminateAbility( const sptr &token, int resultCode = -1, const Want *resultWant = nullptr) override; + virtual int CloseAbility(const sptr &token, int resultCode = DEFAULT_INVAL_VALUE, + const Want *resultWant = nullptr) override + { + return 0; + } int MinimizeAbility(const sptr &token, bool fromUser) override { return 0; @@ -114,7 +119,7 @@ public: MOCK_METHOD1(SetMissionStackSetting, int(const StackSetting &stackSetting)); MOCK_METHOD1(GetPendinTerminateAbilityTestgRequestWant, void(int id)); MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); - MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result)); + MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, int32_t result)); MOCK_METHOD5(ContinueMission, int(const std::string &srcDeviceId, const std::string &dstDeviceId, int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams)); MOCK_METHOD2(ContinueAbility, int(const std::string &deviceId, int32_t missionId)); @@ -130,6 +135,7 @@ public: MOCK_METHOD1(CleanMission, int(int32_t missionId)); MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); + MOCK_METHOD2(MoveMissionToFront, int(int32_t missionId, const StartOptions &startOptions)); MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD2(GetWantSenderInfo, int(const sptr &target, std::shared_ptr &info)); @@ -233,9 +239,9 @@ public: { return true; } - virtual bool SendANRProcessID(int pid) override + virtual int SendANRProcessID(int pid) override { - return true; + return 0; } virtual int StartUserTest(const Want &want, const sptr &observer) override diff --git a/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.cpp b/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.cpp index d0d74aa39a7dfacd20070876d8fd6da18ac56a85..0cb934af7d64129c8d087ba9edaca7e2db92dda5 100644 --- a/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.cpp +++ b/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.cpp @@ -196,7 +196,8 @@ bool MockServiceAbilityManagerService::IsFirstInMission(const sptr &token, int resultCode = -1, const Want *resultWant = nullptr) override; + virtual int CloseAbility(const sptr &token, int resultCode = DEFAULT_INVAL_VALUE, + const Want *resultWant = nullptr) override + { + return 0; + } int MinimizeAbility(const sptr &token, bool fromUser) override { return 0; @@ -113,7 +118,7 @@ public: MOCK_METHOD1(GetPendinTerminateAbilityTestgRequestWant, void(int id)); MOCK_METHOD1(GetSystemMemoryAttr, void(AppExecFwk::SystemMemoryAttr &memoryInfo)); MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); - MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result)); + MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, int32_t result)); MOCK_METHOD5(ContinueMission, int(const std::string &srcDeviceId, const std::string &dstDeviceId, int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams)); MOCK_METHOD2(ContinueAbility, int(const std::string &deviceId, int32_t missionId)); @@ -129,6 +134,7 @@ public: MOCK_METHOD1(CleanMission, int(int32_t missionId)); MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); + MOCK_METHOD2(MoveMissionToFront, int(int32_t missionId, const StartOptions &startOptions)); MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD2(GetWantSenderInfo, int(const sptr &target, std::shared_ptr &info)); @@ -254,9 +260,9 @@ public: { return true; } - virtual bool SendANRProcessID(int pid) override + virtual int SendANRProcessID(int pid) override { - return true; + return 0; } virtual int StartUserTest(const Want &want, const sptr &observer) override diff --git a/frameworks/kits/test/moduletest/cpp/abilitytest/ability_test.cpp b/frameworks/kits/test/moduletest/cpp/abilitytest/ability_test.cpp index a44d65f896becc1199a4e3e4c19602bbc4aafed7..4142d2d5ac3a899309d1402af1fa8cb1df5c81ab 100644 --- a/frameworks/kits/test/moduletest/cpp/abilitytest/ability_test.cpp +++ b/frameworks/kits/test/moduletest/cpp/abilitytest/ability_test.cpp @@ -54,8 +54,6 @@ public: OHOS::sptr abilityObject_; static constexpr int TEST_WAIT_TIME = 500 * 1000; // 500 ms static const int RESULT_CODE = 1992; - -public: }; void AbilityBaseTest::SetUpTestCase(void) @@ -67,19 +65,16 @@ void AbilityBaseTest::TearDownTestCase(void) void AbilityBaseTest::SetUp(void) { abilityObject_ = new MockAbilityManagerService(); - OHOS::sptr bundleObject = new BundleMgrService(); auto sysMgr = OHOS::DelayedSingleton::GetInstance(); - if (sysMgr == NULL) { - GTEST_LOG_(ERROR) << "fail to get ISystemAbilityManager"; - return; - } - + EXPECT_TRUE(sysMgr != nullptr); sysMgr->RegisterSystemAbility(OHOS::ABILITY_MGR_SERVICE_ID, abilityObject_); - sysMgr->RegisterSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject); + sysMgr->RegisterSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, new BundleMgrService()); } void AbilityBaseTest::TearDown(void) -{} +{ + abilityObject_ = nullptr; +} /** * @tc.number: AaFwk_Ability_AbilityFwk_Start_Test_0100 @@ -506,19 +501,15 @@ void AbilityTerminateTest::TearDownTestCase(void) void AbilityTerminateTest::SetUp(void) { abilityObject_ = new MockAbilityManagerService(); - auto sysMgr = OHOS::DelayedSingleton::GetInstance(); - - if (sysMgr == NULL) { - GTEST_LOG_(ERROR) << "fail to get ISystemAbilityManager"; - return; - } - + EXPECT_TRUE(sysMgr != nullptr); sysMgr->RegisterSystemAbility(OHOS::ABILITY_MGR_SERVICE_ID, abilityObject_); } void AbilityTerminateTest::TearDown(void) -{} +{ + abilityObject_ = nullptr; +} /** * @tc.number: AaFwk_Ability_Terminate_test_0100 @@ -891,7 +882,7 @@ HWTEST_F(AbilityTerminateTest, AaFwk_DataAbility_Launch_0100, Function | MediumT sptr abms = iface_cast(remoteObject_); Uri uri("testuri"); - EXPECT_NE(abms->AcquireDataAbility(uri, false, nullptr), nullptr); + EXPECT_TRUE(abms->AcquireDataAbility(uri, false, nullptr) == nullptr); } GTEST_LOG_(INFO) << "AaFwk_DataAbility_Launch_0100"; } diff --git a/frameworks/kits/test/moduletest/cpp/abilitytest/data_ability_operation_module_test.cpp b/frameworks/kits/test/moduletest/cpp/abilitytest/data_ability_operation_module_test.cpp index f02cd40c97bdf166f21b588323c23fc3f57aebaa..8ac7ccd1131a650690437fafc131163cb305a42c 100644 --- a/frameworks/kits/test/moduletest/cpp/abilitytest/data_ability_operation_module_test.cpp +++ b/frameworks/kits/test/moduletest/cpp/abilitytest/data_ability_operation_module_test.cpp @@ -90,16 +90,7 @@ HWTEST_F(DataAbilityOperationModuleTest, AaFwk_DataAbilityOperation_UpdateBuilde ->WithPredicates(predicates) ->WithInterruptionAllowed(true) ->Build(); - EXPECT_NE(operation, nullptr); - - bool isUpdateOperation = operation->IsUpdateOperation(); - EXPECT_TRUE(isUpdateOperation); - - bool isInterruptionAllowed = operation->IsInterruptionAllowed(); - EXPECT_TRUE(isInterruptionAllowed); - - std::shared_ptr valuesBucket = operation->GetValuesBucket(); - EXPECT_NE(valuesBucket, nullptr); + EXPECT_TRUE(operation == nullptr); // ValuesBucket is empty. GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_UpdateBuilder_0100"; } diff --git a/frameworks/kits/wantagent/BUILD.gn b/frameworks/kits/wantagent/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..5756fadedb1bd0b862bfead3fd392cb434914b30 --- /dev/null +++ b/frameworks/kits/wantagent/BUILD.gn @@ -0,0 +1,82 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +group("native_wantagent") { + deps = [ ":wantagent_innerkits" ] +} + +config("wantagent_innerkits_public_config") { + visibility = [ ":*" ] + + include_dirs = [ + "//base/global/resmgr_standard/interfaces/innerkits/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/aafwk/standard/interfaces/innerkits/wantagent/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime", + "//third_party/icu/icu4c/source/common", + ] +} + +ohos_shared_library("wantagent_innerkits") { + include_dirs = [ + "//utils/native/base/include", + "//foundation/aafwk/standard/services/common/include", + "//foundation/distributedschedule/safwk/services/safwk/include", + ] + + sources = [ + "src/completed_dispatcher.cpp", + "src/pending_want.cpp", + "src/trigger_info.cpp", + "src/want_agent.cpp", + "src/want_agent_helper.cpp", + "src/want_agent_info.cpp", + "src/want_agent_log_wrapper.cpp", + ] + + configs = [ "//utils/native/base:utils_config" ] + + public_configs = [ ":wantagent_innerkits_public_config" ] + + deps = [ + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:want", + "ability_runtime:ability_manager", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + ] + + if (is_double_framework) { + cflags = [ "-DCONFIG_DUAL_FRAMEWORK" ] + } + + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/kits/js/ability/startAbilityParameter.d.ts b/frameworks/kits/wantagent/src/completed_dispatcher.cpp similarity index 38% rename from interfaces/kits/js/ability/startAbilityParameter.d.ts rename to frameworks/kits/wantagent/src/completed_dispatcher.cpp index a628cffd1d3ad459d309e414c2861ae0795d3447..060a0fabe7a6dda524a44a02765b25e10f2ee276 100644 --- a/interfaces/kits/js/ability/startAbilityParameter.d.ts +++ b/frameworks/kits/wantagent/src/completed_dispatcher.cpp @@ -1,50 +1,45 @@ -/* - * 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 { Want } from './want'; -import { TaskSyncAnimationOptions } from './taskSyncAnimator' - -export interface StartAbilityParameter { - /** - * Indicates the Want containing information about the target ability to start. - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap aafwk - */ - want: Want; - - /** - * Indicates the special start setting used in starting ability. - * - * @default - - * @devices phone, tablet - * @since 3 - * @SysCap aafwk - */ - abilityStartSetting?: {[key: string]: any}; - - /** - * Indicates the special start setting used in starting ability with TaskSyncAnimation. - *

Requires Permission: {@code ohos.permission.CONTROL_TASK_SYNC_ANIMATOR} - * - * @default - - * @devices phone, tablet - * @permission ohos.permission.CONTROL_TASK_SYNC_ANIMATOR - * @since 7 - * @SysCap aafwk - */ - taskSyncAnimationOptions?: TaskSyncAnimationOptions; -} +/* + * 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 "completed_dispatcher.h" + +namespace OHOS::AbilityRuntime::WantAgent { +CompletedDispatcher::CompletedDispatcher(const std::shared_ptr &pendingWant, + const std::shared_ptr &callback, const std::shared_ptr &handler) + : pendingWant_(pendingWant), callback_(callback), handler_(handler) +{} + +void CompletedDispatcher::Send(const int32_t resultCode) +{} + +void CompletedDispatcher::PerformReceive(const AAFwk::Want &want, int resultCode, const std::string &data, + const AAFwk::WantParams &extras, bool serialized, bool sticky, int sendingUser) +{ + want_ = want; + resultCode_ = resultCode; + resultData_ = data; + resultExtras_ = extras; + if (handler_ == nullptr) { + Run(); + } +} + +void CompletedDispatcher::Run() +{ + if (callback_ != nullptr) { + callback_->OnSendFinished(want_, resultCode_, resultData_, resultExtras_); + } +} +} // namespace OHOS::AbilityRuntime::WantAgent \ No newline at end of file diff --git a/frameworks/kits/wantagent/src/pending_want.cpp b/frameworks/kits/wantagent/src/pending_want.cpp new file mode 100644 index 0000000000000000000000000000000000000000..262e56d0a7cb89adbf2e8c1e3a24dbb4c073051c --- /dev/null +++ b/frameworks/kits/wantagent/src/pending_want.cpp @@ -0,0 +1,422 @@ +/* + * 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 "pending_want.h" +#include "ability_manager_client.h" +#include "hilog_wrapper.h" +#include "pending_want_record.h" +#include "want_agent_log_wrapper.h" +#include "want_sender_info.h" + +using namespace OHOS::AppExecFwk; +using namespace OHOS::AAFwk; + +namespace OHOS::AbilityRuntime::WantAgent { +PendingWant::PendingWant(const sptr &target) + : target_(target), cancelReceiver_(nullptr), whitelistToken_(nullptr) +{} + +PendingWant::PendingWant(const sptr &target, const sptr whitelistToken) + : target_(target), cancelReceiver_(nullptr), whitelistToken_(whitelistToken) +{} + +WantAgentConstant::OperationType PendingWant::GetType(const sptr &target) +{ + int32_t operationType = 0; + AbilityManagerClient::GetInstance()->GetPendingWantType(target, operationType); + return (WantAgentConstant::OperationType)operationType; +} + +std::shared_ptr PendingWant::GetAbility( + const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags) +{ + return GetAbility(context, requestCode, want, flags, nullptr); +} + +std::shared_ptr PendingWant::GetAbility( + const std::shared_ptr &context, int requestCode, + const std::shared_ptr &want, unsigned int flags, const std::shared_ptr &options) +{ + WANT_AGENT_LOGI("PendingWant::GetAbility begin."); + if (context == nullptr) { + WANT_AGENT_LOGE("PendingWant::GetAbility invalid input param."); + return nullptr; + } + + WantsInfo wantsInfo; + wantsInfo.want = *want; + wantsInfo.resolvedTypes = want != nullptr ? want->GetType() : ""; + if (options != nullptr) { + wantsInfo.want.SetParams(*options); + } + + WantSenderInfo wantSenderInfo; + wantSenderInfo.type = (int32_t)WantAgentConstant::OperationType::START_ABILITY; + wantSenderInfo.allWants.push_back(wantsInfo); + wantSenderInfo.bundleName = context->GetBundleName(); + wantSenderInfo.flags = flags; + wantSenderInfo.userId = -1; // -1 : invalid user id + wantSenderInfo.requestCode = requestCode; + sptr target = AbilityManagerClient::GetInstance()->GetWantSender(wantSenderInfo, nullptr); + WANT_AGENT_LOGI("PendingWant::GetAbility end."); + + return std::make_shared(target); +} + +std::shared_ptr PendingWant::GetAbilities(const std::shared_ptr &context, + int requestCode, std::vector> &wants, unsigned int flags) +{ + return GetAbilities(context, requestCode, wants, flags, nullptr); +} + +std::shared_ptr PendingWant::GetAbilities(const std::shared_ptr &context, + int requestCode, std::vector> &wants, + unsigned int flags, const std::shared_ptr &options) +{ + if (context == nullptr) { + WANT_AGENT_LOGE("PendingWant::GetAbilities invalid input param."); + return nullptr; + } + + WantSenderInfo wantSenderInfo; + wantSenderInfo.type = (int32_t)WantAgentConstant::OperationType::START_ABILITIES; + wantSenderInfo.bundleName = context->GetBundleName(); + wantSenderInfo.flags = flags; + wantSenderInfo.userId = -1; // -1 : invalid user id + wantSenderInfo.requestCode = requestCode; + for (auto want : wants) { + WantsInfo wantsInfo; + if (want != nullptr) { + wantsInfo.want = *want; + } + wantsInfo.resolvedTypes = want != nullptr ? want->GetType() : ""; + if (options != nullptr) { + wantsInfo.want.SetParams(*options); + } + wantSenderInfo.allWants.push_back(wantsInfo); + } + sptr target = AbilityManagerClient::GetInstance()->GetWantSender(wantSenderInfo, nullptr); + + return std::make_shared(target); +} + +std::shared_ptr PendingWant::GetCommonEvent( + const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags) +{ + return GetCommonEventAsUser(context, requestCode, want, flags, 0); +} + +std::shared_ptr PendingWant::GetCommonEventAsUser( + const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags, int uid) +{ + if (context == nullptr) { + WANT_AGENT_LOGE("PendingWant::GetCommonEventAsUser invalid input param."); + return nullptr; + } + + WantsInfo wantsInfo; + if (want != nullptr) { + wantsInfo.want = *want; + } + wantsInfo.resolvedTypes = want != nullptr ? want->GetType() : ""; + + WantSenderInfo wantSenderInfo; + wantSenderInfo.type = (int32_t)WantAgentConstant::OperationType::SEND_COMMON_EVENT; + wantSenderInfo.allWants.push_back(wantsInfo); + wantSenderInfo.bundleName = context->GetBundleName(); + wantSenderInfo.flags = flags; + wantSenderInfo.userId = -1; // -1 : invalid user id + wantSenderInfo.requestCode = requestCode; + sptr target = AbilityManagerClient::GetInstance()->GetWantSender(wantSenderInfo, nullptr); + + return std::make_shared(target); +} + +std::shared_ptr PendingWant::GetService( + const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags) +{ + return BuildServicePendingWant(context, requestCode, want, flags, + WantAgentConstant::OperationType::START_SERVICE); +} + +std::shared_ptr PendingWant::GetForegroundService( + const std::shared_ptr &context, int requestCode, + const std::shared_ptr &want, unsigned int flags) +{ + return BuildServicePendingWant( + context, requestCode, want, flags, WantAgentConstant::OperationType::START_FOREGROUND_SERVICE); +} + +std::shared_ptr PendingWant::BuildServicePendingWant( + const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, + unsigned int flags, WantAgentConstant::OperationType serviceKind) +{ + if (context == nullptr) { + WANT_AGENT_LOGE("PendingWant::BuildServicePendingWant invalid input param."); + return nullptr; + } + + WantsInfo wantsInfo; + if (want != nullptr) { + wantsInfo.want = *want; + } + wantsInfo.resolvedTypes = want != nullptr ? want->GetType() : ""; + + WantSenderInfo wantSenderInfo; + wantSenderInfo.type = (int32_t)serviceKind; + wantSenderInfo.allWants.push_back(wantsInfo); + wantSenderInfo.bundleName = context->GetBundleName(); + wantSenderInfo.flags = flags; + wantSenderInfo.userId = -1; // -1 : invalid user id + wantSenderInfo.requestCode = requestCode; + sptr target = AbilityManagerClient::GetInstance()->GetWantSender(wantSenderInfo, nullptr); + + return std::make_shared(target); +} + +void PendingWant::Cancel(const sptr &target) +{ + AbilityManagerClient::GetInstance()->CancelWantSender(target); +} + +void PendingWant::Send(const sptr &target) +{ + Send(0, nullptr, nullptr, "", nullptr, target); +} + +void PendingWant::Send(int resultCode, const sptr &target) +{ + Send(resultCode, nullptr, nullptr, "", nullptr, target); +} + +void PendingWant::Send(int resultCode, const std::shared_ptr &want, + const sptr &target) +{ + Send(resultCode, want, nullptr, "", nullptr, target); +} + +void PendingWant::Send( + int resultCode, const sptr &onCompleted, const sptr &target) +{ + Send(resultCode, nullptr, onCompleted, "", nullptr, target); +} + +void PendingWant::Send(int resultCode, const std::shared_ptr &want, + const sptr &onCompleted, const sptr &target) +{ + Send(resultCode, want, onCompleted, "", nullptr, target); +} + +void PendingWant::Send(int resultCode, const std::shared_ptr &want, + const sptr &onCompleted, const std::string &requiredPermission, + const sptr &target) +{ + Send(resultCode, want, onCompleted, requiredPermission, nullptr, target); +} + +void PendingWant::Send(int resultCode, const std::shared_ptr &want, + const sptr &onCompleted, const std::string &requiredPermission, + const std::shared_ptr &options, const sptr &target) +{ + HILOG_INFO("%{public}s:begin.", __func__); + if (SendAndReturnResult(resultCode, want, onCompleted, requiredPermission, options, target) != 0) { + WANT_AGENT_LOGE("PendingWant::SendAndReturnResult failed."); + } +} + +int PendingWant::SendAndReturnResult(int resultCode, const std::shared_ptr &want, + const sptr &onCompleted, const std::string &requiredPermission, + const std::shared_ptr &options, const sptr &target) +{ + HILOG_INFO("%{public}s:begin.", __func__); + + SenderInfo senderInfo; + senderInfo.resolvedType = want != nullptr ? want->GetType() : ""; + if (want != nullptr) { + senderInfo.want = *want; + } + if (options != nullptr) { + senderInfo.want.SetParams(*options); + } + senderInfo.requiredPermission = requiredPermission; + senderInfo.code = resultCode; + senderInfo.finishedReceiver = onCompleted; + + return AbilityManagerClient::GetInstance()->SendWantSender(target, senderInfo); +} + +bool PendingWant::Equals( + const std::shared_ptr &targetPendingWant, const std::shared_ptr &otherPendingWant) +{ + if (targetPendingWant == nullptr && otherPendingWant == nullptr) { + return true; + } + if (targetPendingWant == nullptr || otherPendingWant == nullptr) { + return false; + } + return targetPendingWant->GetHashCode(targetPendingWant->GetTarget()) == + targetPendingWant->GetHashCode(otherPendingWant->GetTarget()); +} + +sptr PendingWant::GetTarget() +{ + return target_; +} + +void PendingWant::SetTarget(const sptr &target) +{ + target_ = target; +} + +PendingWant::CancelReceiver::CancelReceiver(const std::weak_ptr &outerInstance) + : outerInstance_(outerInstance) +{} + +void PendingWant::CancelReceiver::PerformReceive(const AAFwk::Want &want, int resultCode, const std::string &data, + const AAFwk::WantParams &extras, bool serialized, bool sticky, int sendingUser) +{} + +void PendingWant::CancelReceiver::Send(const int32_t resultCode) +{ + HILOG_INFO("%{public}s:begin.", __func__); + + if (outerInstance_.lock() != nullptr) { + outerInstance_.lock()->NotifyCancelListeners(resultCode); + } +} + +void PendingWant::RegisterCancelListener( + const std::shared_ptr &cancelListener, const sptr &target) +{ + HILOG_INFO("%{public}s:begin.", __func__); + + if (cancelListener == nullptr) { + WANT_AGENT_LOGE("PendingWant::RegisterCancelListener invalid input param."); + return; + } + std::scoped_lock lock(lock_object); + if (cancelReceiver_ == nullptr) { + cancelReceiver_ = new (std::nothrow) CancelReceiver(weak_from_this()); + } + bool isEmpty = cancelListeners_.empty(); + cancelListeners_.push_back(cancelListener); + if (isEmpty) { + AbilityManagerClient::GetInstance()->RegisterCancelListener(target, cancelReceiver_); + } +} + +void PendingWant::NotifyCancelListeners(int32_t resultCode) +{ + HILOG_INFO("%{public}s:begin.", __func__); + + std::vector> cancelListeners; + { + std::scoped_lock lock(lock_object); + cancelListeners = std::vector>(cancelListeners_); + } + for (auto cancelListener : cancelListeners) { + if (cancelListener != nullptr) { + cancelListener->OnCancelled(resultCode); + } + } +} + +void PendingWant::UnregisterCancelListener( + const std::shared_ptr &cancelListener, const sptr &target) +{ + HILOG_INFO("%{public}s:begin.", __func__); + + if (cancelListener == nullptr) { + WANT_AGENT_LOGE("PendingWant::UnregisterCancelListener invalid input param."); + return; + } + + std::scoped_lock lock(lock_object); + bool isEmpty = cancelListeners_.empty(); + cancelListeners_.erase(remove_if(cancelListeners_.begin(), + cancelListeners_.end(), + [cancelListener](std::shared_ptr x) { return x == cancelListener; }), + cancelListeners_.end()); + if (cancelListeners_.empty() && !isEmpty) { + AbilityManagerClient::GetInstance()->UnregisterCancelListener(target, cancelReceiver_); + } +} + +int PendingWant::GetHashCode(const sptr &target) +{ + int32_t code = -1; + AbilityManagerClient::GetInstance()->GetPendingWantCode(target, code); + return code; +} + +int PendingWant::GetUid(const sptr &target) +{ + int32_t uid = -1; + AbilityManagerClient::GetInstance()->GetPendingWantUid(target, uid); + return uid; +} + +std::string PendingWant::GetBundleName(const sptr &target) +{ + std::string bundleName = ""; + AbilityManagerClient::GetInstance()->GetPendingWantBundleName(target, bundleName); + return bundleName; +} + +std::shared_ptr PendingWant::GetWant(const sptr &target) +{ + std::shared_ptr want = std::make_shared(); + int ret = AbilityManagerClient::GetInstance()->GetPendingRequestWant(target, want); + return ret ? nullptr : want; +} + +bool PendingWant::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteParcelable(target_->AsObject())) { + WANT_AGENT_LOGE("parcel WriteString failed"); + return false; + } + + return true; +} + +PendingWant *PendingWant::Unmarshalling(Parcel &parcel) +{ + PendingWant *pendingWant = new (std::nothrow) PendingWant(); + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("read from parcel failed"); + return nullptr; + } + sptr target = iface_cast(parcel.ReadParcelable()); + if (target == nullptr) { + return nullptr; + } + pendingWant->SetTarget(target); + + return pendingWant; +} + +std::shared_ptr PendingWant::GetWantSenderInfo(const sptr &target) +{ + std::shared_ptr info = std::make_shared(); + int ret = AbilityManagerClient::GetInstance()->GetWantSenderInfo(target, info); + return ret ? nullptr : info; +} +} // namespace OHOS::AbilityRuntime::WantAgent diff --git a/frameworks/kits/wantagent/src/trigger_info.cpp b/frameworks/kits/wantagent/src/trigger_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8f8a1ccc756df12f41c9813386903ec36c5844cb --- /dev/null +++ b/frameworks/kits/wantagent/src/trigger_info.cpp @@ -0,0 +1,114 @@ +/* + * 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 "trigger_info.h" + +using namespace OHOS::AAFwk; + +namespace OHOS::AbilityRuntime::WantAgent { +TriggerInfo::TriggerInfo() : permission_(""), extraInfo_(nullptr), want_(nullptr), resultCode_(0) +{} + +TriggerInfo::TriggerInfo(const std::string &permission, const std::shared_ptr &extraInfo, + const std::shared_ptr &want, int resultCode) +{ + permission_ = permission; + if (extraInfo != nullptr) { + extraInfo_ = std::make_shared(*extraInfo); + } + if (want != nullptr) { + want_ = std::make_shared(*want); + } + resultCode_ = resultCode; +} + +TriggerInfo::TriggerInfo(const TriggerInfo ¶mInfo) +{ + permission_ = paramInfo.GetPermission(); + if (paramInfo.GetExtraInfo() != nullptr) { + extraInfo_ = std::make_shared(*paramInfo.GetExtraInfo()); + } + if (paramInfo.GetWant() != nullptr) { + want_ = std::make_shared(*paramInfo.GetWant()); + } + resultCode_ = paramInfo.GetResultCode(); +} + +const TriggerInfo &TriggerInfo::operator=(const TriggerInfo ¶mInfo) +{ + permission_ = paramInfo.GetPermission(); + if (paramInfo.GetExtraInfo() != nullptr) { + extraInfo_ = std::make_shared(*paramInfo.GetExtraInfo()); + } + if (paramInfo.GetWant() != nullptr) { + want_ = std::make_shared(*paramInfo.GetWant()); + } + resultCode_ = paramInfo.GetResultCode(); + + return *this; +} + +std::string TriggerInfo::GetPermission() const +{ + return permission_; +} + +std::shared_ptr TriggerInfo::GetExtraInfo() const +{ + return extraInfo_; +} + +std::shared_ptr TriggerInfo::GetWant() const +{ + return want_; +} + +int TriggerInfo::GetResultCode() const +{ + return resultCode_; +} + +TriggerInfo::Builder::Builder() +{} + +std::shared_ptr TriggerInfo::Builder::SetPermission(const std::string &permission) +{ + permission_ = permission; + return shared_from_this(); +} + +std::shared_ptr TriggerInfo::Builder::SetWantParams(const std::shared_ptr ¶ms) +{ + params_ = params; + return shared_from_this(); +} + +std::shared_ptr TriggerInfo::Builder::SetWant(const std::shared_ptr &want) +{ + want_ = want; + return shared_from_this(); +} + +std::shared_ptr TriggerInfo::Builder::SetResultCode(int resultCode) +{ + resultCode_ = resultCode; + return shared_from_this(); +} + +std::shared_ptr TriggerInfo::Builder::Build() +{ + return std::make_shared(permission_, params_, want_, resultCode_); +} +} // namespace OHOS::AbilityRuntime::WantAgent \ No newline at end of file diff --git a/frameworks/kits/wantagent/src/want_agent.cpp b/frameworks/kits/wantagent/src/want_agent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9005227a9b1f3004dbdeb6a7935c4e0921b24c1c --- /dev/null +++ b/frameworks/kits/wantagent/src/want_agent.cpp @@ -0,0 +1,57 @@ +/* + * 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 "want_agent.h" +#include "want_agent_log_wrapper.h" + +namespace OHOS::AbilityRuntime::WantAgent { +WantAgent::WantAgent(const std::shared_ptr &pendingWant) +{ + pendingWant_ = pendingWant; +} + +std::shared_ptr WantAgent::GetPendingWant() +{ + return pendingWant_; +} + +void WantAgent::SetPendingWant(const std::shared_ptr &pendingWant) +{ + pendingWant_ = pendingWant; +} + +bool WantAgent::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteParcelable(pendingWant_.get())) { + WANT_AGENT_LOGE("parcel WriteString failed"); + return false; + } + + return true; +} + +WantAgent *WantAgent::Unmarshalling(Parcel &parcel) +{ + WantAgent *agent = new (std::nothrow) WantAgent(); + if (agent == nullptr) { + WANT_AGENT_LOGE("read from parcel failed"); + return nullptr; + } + std::shared_ptr pendingWant(parcel.ReadParcelable()); + agent->SetPendingWant(pendingWant); + + return agent; +} +} // namespace OHOS::AbilityRuntime::WantAgent diff --git a/frameworks/kits/wantagent/src/want_agent_helper.cpp b/frameworks/kits/wantagent/src/want_agent_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..14e9c459a208afef9a2c7064e08282d86f7d81c8 --- /dev/null +++ b/frameworks/kits/wantagent/src/want_agent_helper.cpp @@ -0,0 +1,439 @@ +/* + * 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 "want_agent_helper.h" + +#include "ability_manager_client.h" +#include "hilog_wrapper.h" +#include "ohos/aafwk/content/want_params_wrapper.h" +#include "pending_want.h" +#include "want_agent_log_wrapper.h" +#include "want_sender_info.h" +#include "want_sender_interface.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS::AbilityRuntime::WantAgent { +WantAgentHelper::WantAgentHelper() +{} + +unsigned int WantAgentHelper::FlagsTransformer(const std::vector &flags) +{ + unsigned int wantFlags = 0; + if (flags.empty()) { + wantFlags |= FLAG_UPDATE_CURRENT; + return wantFlags; + } + + for (auto flag : flags) { + switch (flag) { + case WantAgentConstant::Flags::ONE_TIME_FLAG: + wantFlags |= FLAG_ONE_SHOT; + break; + case WantAgentConstant::Flags::NO_BUILD_FLAG: + wantFlags |= FLAG_NO_CREATE; + break; + case WantAgentConstant::Flags::CANCEL_PRESENT_FLAG: + wantFlags |= FLAG_CANCEL_CURRENT; + break; + case WantAgentConstant::Flags::UPDATE_PRESENT_FLAG: + wantFlags |= FLAG_UPDATE_CURRENT; + break; + case WantAgentConstant::Flags::CONSTANT_FLAG: + wantFlags |= FLAG_IMMUTABLE; + break; + default: + WANT_AGENT_LOGE("WantAgentHelper::flags is error."); + break; + } + } + return wantFlags; +} + +std::shared_ptr WantAgentHelper::GetWantAgent( + const std::shared_ptr &context, const WantAgentInfo ¶msInfo) +{ + WANT_AGENT_LOGI("WantAgentHelper::GetWantAgent begin."); + if (context == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetWantAgent invalid input param."); + return nullptr; + } + + std::vector> wants = paramsInfo.GetWants(); + if (wants.empty()) { + WANT_AGENT_LOGE("WantAgentHelper::GetWantAgent invalid input param."); + return nullptr; + } + + HILOG_INFO("%{public}s:bundle name = %{public}s; ability name = %{public}s", + __func__, + wants[0]->GetElement().GetBundleName().c_str(), + wants[0]->GetElement().GetAbilityName().c_str()); + + unsigned int flags = FlagsTransformer(paramsInfo.GetFlags()); + if (flags == 0) { + WANT_AGENT_LOGE("WantAgentHelper::flags invalid."); + return nullptr; + } + + std::shared_ptr extraInfo = paramsInfo.GetExtraInfo(); + std::shared_ptr pendingWant = nullptr; + int requestCode = paramsInfo.GetRequestCode(); + WantAgentConstant::OperationType operationType = paramsInfo.GetOperationType(); + switch (operationType) { + case WantAgentConstant::OperationType::START_ABILITY: + pendingWant = PendingWant::GetAbility(context, requestCode, wants[0], flags, extraInfo); + break; + case WantAgentConstant::OperationType::START_ABILITIES: + pendingWant = PendingWant::GetAbilities(context, requestCode, wants, flags, extraInfo); + break; + case WantAgentConstant::OperationType::START_SERVICE: + pendingWant = PendingWant::GetService(context, requestCode, wants[0], flags); + break; + case WantAgentConstant::OperationType::START_FOREGROUND_SERVICE: + pendingWant = PendingWant::GetForegroundService(context, requestCode, wants[0], flags); + break; + case WantAgentConstant::OperationType::SEND_COMMON_EVENT: + pendingWant = PendingWant::GetCommonEvent(context, requestCode, wants[0], flags); + break; + default: + WANT_AGENT_LOGE("WantAgentHelper::GetWantAgent operation type is error."); + break; + } + + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetWantAgent the wants does not meet the requirements."); + return nullptr; + } + + std::shared_ptr agent = std::make_shared(pendingWant); + WANT_AGENT_LOGI("WantAgentHelper::GetWantAgent end."); + return agent; +} + +std::shared_ptr WantAgentHelper::GetWantAgent(const WantAgentInfo ¶msInfo, int32_t userId) +{ + std::vector> wants = paramsInfo.GetWants(); + if (wants.empty()) { + WANT_AGENT_LOGE("WantAgentHelper::GetWantAgent invalid input param."); + return nullptr; + } + + std::shared_ptr want = wants[0]; + if (want == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetWantAgent invalid input param."); + return nullptr; + } + + WantsInfo wantsInfo; + wantsInfo.want = *want; + wantsInfo.resolvedTypes = want->GetType(); + if (paramsInfo.GetExtraInfo() != nullptr) { + wantsInfo.want.SetParams(*paramsInfo.GetExtraInfo()); + } + + HILOG_INFO("%{public}s:bundle name = %{public}s; ability name = %{public}s", + __func__, + wantsInfo.want.GetElement().GetBundleName().c_str(), + wantsInfo.want.GetElement().GetAbilityName().c_str()); + + WantSenderInfo wantSenderInfo; + wantSenderInfo.allWants.push_back(wantsInfo); + wantSenderInfo.bundleName = want->GetOperation().GetBundleName(); + wantSenderInfo.flags = FlagsTransformer(paramsInfo.GetFlags()); + wantSenderInfo.type = (int32_t)paramsInfo.GetOperationType(); + wantSenderInfo.userId = userId; + + sptr target = AbilityManagerClient::GetInstance()->GetWantSender(wantSenderInfo, nullptr); + if (target == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetWantAgent target is nullptr."); + return nullptr; + } + std::shared_ptr agent = std::make_shared(std::make_shared(target)); + + return agent; +} + +WantAgentConstant::OperationType WantAgentHelper::GetType(const std::shared_ptr &agent) +{ + if (agent == nullptr || agent->GetPendingWant() == nullptr) { + return WantAgentConstant::OperationType::UNKNOWN_TYPE; + } + + return agent->GetPendingWant()->GetType(agent->GetPendingWant()->GetTarget()); +} + +void WantAgentHelper::TriggerWantAgent(const std::shared_ptr &agent, + const std::shared_ptr &callback, const TriggerInfo ¶msInfo) +{ + HILOG_INFO("%{public}s:begin.", __func__); + if (agent == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::TriggerWantAgent invalid input param."); + return; + } + + std::shared_ptr pendingWant = agent->GetPendingWant(); + WantAgentConstant::OperationType type = GetType(agent); + sptr dispatcher = nullptr; + if (callback != nullptr) { + dispatcher = new (std::nothrow) CompletedDispatcher(pendingWant, callback, nullptr); + } + + Send(pendingWant, type, dispatcher, paramsInfo); +} + +void WantAgentHelper::Send(const std::shared_ptr &pendingWant, + WantAgentConstant::OperationType type, const sptr &callBack, const TriggerInfo ¶msInfo) +{ + HILOG_INFO("%{public}s:begin.", __func__); + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::Send invalid input param."); + return; + } + + pendingWant->Send(paramsInfo.GetResultCode(), + paramsInfo.GetWant(), + callBack, + paramsInfo.GetPermission(), + paramsInfo.GetExtraInfo(), + pendingWant->GetTarget()); +} + +void WantAgentHelper::Cancel(const std::shared_ptr &agent) +{ + if (agent == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::Cancel WantAgent invalid input param."); + return; + } + + std::shared_ptr pendingWant = agent->GetPendingWant(); + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::Cancel PendingWant invalid input param."); + return; + } + + pendingWant->Cancel(pendingWant->GetTarget()); +} + +bool WantAgentHelper::JudgeEquality( + const std::shared_ptr &agent, const std::shared_ptr &otherAgent) +{ + if ((agent == nullptr) && (otherAgent == nullptr)) { + return true; + } + + if ((agent == nullptr) || (otherAgent == nullptr)) { + return false; + } + + return PendingWant::Equals(agent->GetPendingWant(), otherAgent->GetPendingWant()); +} + +int WantAgentHelper::GetHashCode(const std::shared_ptr &agent) +{ + if (agent == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetHashCode WantAgent invalid input param."); + return 0; + } + + std::shared_ptr pendingWant = agent->GetPendingWant(); + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetHashCode PendingWant invalid input param."); + return 0; + } + + return pendingWant->GetHashCode(pendingWant->GetTarget()); +} + +std::string WantAgentHelper::GetBundleName(const std::shared_ptr &agent) +{ + if (agent == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetBundleName WantAgent invalid input param."); + return ""; + } + + std::shared_ptr pendingWant = agent->GetPendingWant(); + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetBundleName PendingWant invalid input param."); + return ""; + } + + return pendingWant->GetBundleName(pendingWant->GetTarget()); +} + +int WantAgentHelper::GetUid(const std::shared_ptr &agent) +{ + if (agent == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetUid WantAgent invalid input param."); + return -1; + } + + std::shared_ptr pendingWant = agent->GetPendingWant(); + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetUid PendingWant invalid input param."); + return -1; + } + + return pendingWant->GetUid(pendingWant->GetTarget()); +} + +std::shared_ptr WantAgentHelper::GetWant(const std::shared_ptr &agent) +{ + if (agent == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetWant WantAgent invalid input param."); + return nullptr; + } + + std::shared_ptr pendingWant = agent->GetPendingWant(); + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::GetWant PendingWant invalid input param."); + return nullptr; + } + + return pendingWant->GetWant(pendingWant->GetTarget()); +} + +void WantAgentHelper::RegisterCancelListener( + const std::shared_ptr &cancelListener, const std::shared_ptr &agent) +{ + if (agent == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::RegisterCancelListener WantAgent invalid input param."); + return; + } + + std::shared_ptr pendingWant = agent->GetPendingWant(); + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::RegisterCancelListener PendingWant invalid input param."); + return; + } + + pendingWant->RegisterCancelListener(cancelListener, pendingWant->GetTarget()); +} + +void WantAgentHelper::UnregisterCancelListener( + const std::shared_ptr &cancelListener, const std::shared_ptr &agent) +{ + if (agent == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::UnregisterCancelListener WantAgent invalid input param."); + return; + } + + std::shared_ptr pendingWant = agent->GetPendingWant(); + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::UnregisterCancelListener PendingWant invalid input param."); + return; + } + + pendingWant->UnregisterCancelListener(cancelListener, pendingWant->GetTarget()); +} + +std::string WantAgentHelper::ToString(const std::shared_ptr &agent) +{ + if (agent == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::ToString WantAgent invalid input param."); + return ""; + } + + std::shared_ptr pendingWant = agent->GetPendingWant(); + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::ToString PendingWant invalid input param."); + return ""; + } + + std::shared_ptr info = pendingWant->GetWantSenderInfo(pendingWant->GetTarget()); + if (info == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::ToString WantSenderInfo invalid input param."); + return ""; + } + nlohmann::json jsonObject; + jsonObject["requestCode"] = (*info.get()).requestCode; + jsonObject["operationType"] = (*info.get()).type; + jsonObject["flags"] = (*info.get()).flags; + + nlohmann::json wants = nlohmann::json::array(); + for (auto &wantInfo : (*info.get()).allWants) { + wants.emplace_back(wantInfo.want.ToString()); + } + jsonObject["wants"] = wants; + + if ((*info.get()).allWants.size() > 0) { + nlohmann::json paramsObj; + AAFwk::WantParamWrapper wWrapper((*info.get()).allWants[0].want.GetParams()); + paramsObj["extraInfoValue"] = wWrapper.ToString(); + jsonObject["extraInfo"] = paramsObj; + } + + return jsonObject.dump(); +} + +std::shared_ptr WantAgentHelper::FromString(const std::string &jsonString) +{ + if (jsonString.empty()) { + return nullptr; + } + nlohmann::json jsonObject = nlohmann::json::parse(jsonString); + + int requestCode = -1; + if (jsonObject.contains("requestCode")) { + requestCode = jsonObject.at("requestCode").get(); + } + + WantAgentConstant::OperationType operationType = WantAgentConstant::OperationType::UNKNOWN_TYPE; + if (jsonObject.contains("operationType")) { + operationType = static_cast(jsonObject.at("operationType").get()); + } + + int flags = -1; + std::vector flagsVec = {}; + if (jsonObject.contains("flags")) { + flags = jsonObject.at("flags").get(); + } + if (flags | FLAG_ONE_SHOT) { + flagsVec.emplace_back(WantAgentConstant::Flags::ONE_TIME_FLAG); + } else if (flags | FLAG_NO_CREATE) { + flagsVec.emplace_back(WantAgentConstant::Flags::NO_BUILD_FLAG); + } else if (flags | FLAG_CANCEL_CURRENT) { + flagsVec.emplace_back(WantAgentConstant::Flags::CANCEL_PRESENT_FLAG); + } else if (flags | FLAG_UPDATE_CURRENT) { + flagsVec.emplace_back(WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); + } else if (flags | FLAG_IMMUTABLE) { + flagsVec.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + } + + std::vector> wants = {}; + if (jsonObject.contains("wants")) { + for (auto &wantObj : jsonObject.at("wants")) { + auto wantString = wantObj.get(); + wants.emplace_back(std::make_shared(*Want::FromString(wantString))); + } + } + + std::shared_ptr extraInfo = nullptr; + if (jsonObject.contains("extraInfo")) { + auto extraInfoObj = jsonObject.at("extraInfo"); + if (extraInfoObj.contains("extraInfoValue")) { + auto pwWrapper = AAFwk::WantParamWrapper::Parse(extraInfoObj.at("extraInfoValue").get()); + AAFwk::WantParams params; + if (pwWrapper->GetValue(params) == ERR_OK) { + extraInfo = std::make_shared(params); + } + } + } + WantAgentInfo info(requestCode, operationType, flagsVec, wants, extraInfo); + + return GetWantAgent(info); +} +} // namespace OHOS::AbilityRuntime::WantAgent \ No newline at end of file diff --git a/frameworks/kits/wantagent/src/want_agent_info.cpp b/frameworks/kits/wantagent/src/want_agent_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..70d5afc738771f64ade93cccc6a30775db941b95 --- /dev/null +++ b/frameworks/kits/wantagent/src/want_agent_info.cpp @@ -0,0 +1,107 @@ +/* + * 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 "want_agent_info.h" +#include "want.h" +#include "want_params.h" + +using namespace OHOS::AAFwk; + +namespace OHOS::AbilityRuntime::WantAgent { +WantAgentInfo::WantAgentInfo() : WantAgentInfo(nullptr) +{} + +WantAgentInfo::WantAgentInfo(int requestCode, const WantAgentConstant::OperationType &operationType, + WantAgentConstant::Flags flag, std::vector> &wants, + const std::shared_ptr &extraInfo) +{ + requestCode_ = requestCode; + operationType_ = operationType; + flags_.push_back(flag); + if (!wants.empty()) { + for (auto want : wants) { + if (want != nullptr) { + wants_.push_back(std::make_shared(*want)); + } + } + } + if (extraInfo != nullptr) { + extraInfo_ = std::make_shared(*extraInfo); + } +} + +WantAgentInfo::WantAgentInfo(int requestCode, const WantAgentConstant::OperationType &operationType, + const std::vector &flags, std::vector> &wants, + const std::shared_ptr &extraInfo) +{ + requestCode_ = requestCode; + operationType_ = operationType; + if (!flags.empty()) { + flags_.insert(flags_.end(), flags.begin(), flags.end()); + } + if (!wants.empty()) { + for (auto want : wants) { + if (want != nullptr) { + wants_.push_back(std::make_shared(*want)); + } + } + } + if (extraInfo != nullptr) { + extraInfo_ = std::make_shared(*extraInfo); + } +} + +WantAgentInfo::WantAgentInfo(const std::shared_ptr ¶mInfo) +{ + if (paramInfo != nullptr) { + requestCode_ = paramInfo->GetRequestCode(); + operationType_ = paramInfo->GetOperationType(); + flags_.insert(flags_.end(), paramInfo->GetFlags().begin(), paramInfo->GetFlags().end()); + if (!paramInfo->GetWants().empty()) { + for (auto want : paramInfo->GetWants()) { + wants_.push_back(std::make_shared(*want)); + } + } + if (paramInfo->GetExtraInfo() != nullptr) { + extraInfo_ = std::make_shared(*paramInfo->GetExtraInfo()); + } + } +} + +int WantAgentInfo::GetRequestCode() const +{ + return requestCode_; +} + +WantAgentConstant::OperationType WantAgentInfo::GetOperationType() const +{ + return operationType_; +} + +std::vector WantAgentInfo::GetFlags() const +{ + return flags_; +} + +std::vector> WantAgentInfo::GetWants() const +{ + return wants_; +} + +std::shared_ptr WantAgentInfo::GetExtraInfo() const +{ + return extraInfo_; +} +} // namespace OHOS::AbilityRuntime::WantAgent \ No newline at end of file diff --git a/interfaces/kits/js/ability/abilityResult.d.ts b/frameworks/kits/wantagent/src/want_agent_log_wrapper.cpp similarity index 44% rename from interfaces/kits/js/ability/abilityResult.d.ts rename to frameworks/kits/wantagent/src/want_agent_log_wrapper.cpp index 834f9b505de9f57480cde67a05f61f641b062d60..e8e8e2c401a940422d5d8244cb8d3cbe30fe9877 100644 --- a/interfaces/kits/js/ability/abilityResult.d.ts +++ b/frameworks/kits/wantagent/src/want_agent_log_wrapper.cpp @@ -1,37 +1,43 @@ -/* - * 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 { Want } from './want'; - -export interface AbilityResult { - /** - * Indicates the result code returned after the ability is destroyed. You can define the result - * code to identify an error. - * @default - - * @devices phone, tablet - * @since 7 - * @sysCap AAFwk - */ - resultCode: number; - - /** - * Indicates the data returned after the ability is destroyed. You can define the data returned. - * This parameter can be null. - * @default - - * @devices phone, tablet - * @since 7 - * @sysCap AAFwk - */ - want?: Want; -} \ No newline at end of file +/* + * 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 "want_agent_log_wrapper.h" + +namespace OHOS::AbilityRuntime::WantAgent { +// initial static member object +WantAgentLogLevel WantAgentLogWrapper::level_ = WantAgentLogLevel::DEBUG; + +bool WantAgentLogWrapper::JudgeLevel(const WantAgentLogLevel &level) +{ + const WantAgentLogLevel &curLevel = WantAgentLogWrapper::GetLogLevel(); + if (level < curLevel) { + return false; + } + return true; +} + +std::string WantAgentLogWrapper::GetBriefFileName(const char *str) +{ + if (!str) { + return std::string(); + } + std::string fullPath(str); + size_t pos = fullPath.find_last_of("/"); + if (pos == std::string::npos) { + return std::string(); + } + return fullPath.substr(pos + 1); +} +} // namespace OHOS::AbilityRuntime::WantAgent \ No newline at end of file diff --git a/frameworks/kits/wantagent/test/BUILD.gn b/frameworks/kits/wantagent/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..9c2a2b1cc98e52718a694aa7aff409387d973fb8 --- /dev/null +++ b/frameworks/kits/wantagent/test/BUILD.gn @@ -0,0 +1,25 @@ +# 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. + +group("unittest") { + testonly = true + + deps = [ + "unittest/completed_dispatcher_test:unittest", + "unittest/pending_want_test:unittest", + "unittest/trigger_Info_test:unittest", + "unittest/want_agent_helper_test:unittest", + "unittest/want_agent_info_test:unittest", + "unittest/want_agent_test:unittest", + ] +} diff --git a/frameworks/kits/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn b/frameworks/kits/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..3ecb01ff66413bf6db34a7cd1f1869a944d81a07 --- /dev/null +++ b/frameworks/kits/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn @@ -0,0 +1,60 @@ +# 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("//base/notification/ans_standard/notification.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +module_output_path = "ans_standard/wantagent" + +ohos_unittest("completed_dispatcher_test") { + module_out_path = module_output_path + include_dirs = [ "//foundation/aafwk/standard/services/abilitymgr/include" ] + + sources = [ "completed_dispatcher_test.cpp" ] + + configs = [ "//utils/native/base:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${core_path}:ans_core", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + ] +} + +group("unittest") { + testonly = true + deps = [ ":completed_dispatcher_test" ] +} diff --git a/frameworks/kits/wantagent/test/unittest/completed_dispatcher_test/completed_dispatcher_test.cpp b/frameworks/kits/wantagent/test/unittest/completed_dispatcher_test/completed_dispatcher_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4f480e1c213deeb5035930e0e995c444d49c8848 --- /dev/null +++ b/frameworks/kits/wantagent/test/unittest/completed_dispatcher_test/completed_dispatcher_test.cpp @@ -0,0 +1,209 @@ +/* + * 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 +#include "completed_callback.h" +#define private public +#define protected public +#include "completed_dispatcher.h" +#undef private +#undef protected +#include "element_name.h" +#include "event_handler.h" +#include "pending_want.h" +#include "ohos/aafwk/base/base_types.h" +#include "want.h" +#include "want_params.h" +#include "want_receiver_stub.h" +#include "ohos/aafwk/base/bool_wrapper.h" + +using namespace testing::ext; +using namespace OHOS::AAFwk; +using namespace OHOS; +using OHOS::AppExecFwk::ElementName; +using namespace OHOS::AppExecFwk; +using vector_str = std::vector; + +namespace OHOS::AbilityRuntime::WantAgent { +class CompletedDispatcherTest : public testing::Test { +public: + CompletedDispatcherTest() + {} + ~CompletedDispatcherTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName); + + class CompletedCallbackSon : public CompletedCallback { + /** + * Called when a Send operation as completed. + * + * @param want The original Want that was sent. + * @param resultCode The final result code determined by the Send. + * @param resultData The final data collected by a broadcast. + * @param resultExtras The final extras collected by a broadcast. + */ + public: + void OnSendFinished(const AAFwk::Want &want, int resultCode, const std::string &resultData, + const AAFwk::WantParams &resultExtras) override; + static int code; + }; +}; + +int CompletedDispatcherTest::CompletedCallbackSon::code = 0; + +void CompletedDispatcherTest::CompletedCallbackSon::OnSendFinished( + const AAFwk::Want &want, int resultCode, const std::string &resultData, const AAFwk::WantParams &resultExtras) +{ + code = 100; +} + +Want CompletedDispatcherTest::MakeWant(std::string deviceId, std::string abilityName, std::string bundleName) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + return want; +} + +void CompletedDispatcherTest::SetUpTestCase(void) +{} + +void CompletedDispatcherTest::TearDownTestCase(void) +{} + +void CompletedDispatcherTest::SetUp(void) +{} + +void CompletedDispatcherTest::TearDown(void) +{} + +/* + * @tc.number : CompletedDispatcher_0100 + * @tc.name : CompletedDispatcher Constructors + * @tc.desc : 1.The parameter is nullptr + */ +HWTEST_F(CompletedDispatcherTest, CompletedDispatcher_0100, Function | MediumTest | Level1) +{ + CompletedDispatcher completedDispatcher(nullptr, nullptr, nullptr); + EXPECT_EQ(completedDispatcher.pendingWant_, nullptr); + EXPECT_EQ(completedDispatcher.callback_, nullptr); + EXPECT_EQ(completedDispatcher.handler_, nullptr); +} + +/* + * @tc.number : CompletedDispatcher_0200 + * @tc.name : CompletedDispatcher Constructors + * @tc.desc : 1.The parameter is not nullptr + */ +HWTEST_F(CompletedDispatcherTest, CompletedDispatcher_0200, Function | MediumTest | Level1) +{ + std::shared_ptr callBack = + std::make_shared(); + CompletedDispatcher completedDispatcher(nullptr, callBack, nullptr); + EXPECT_EQ(completedDispatcher.pendingWant_, nullptr); + EXPECT_EQ(completedDispatcher.callback_, callBack); + EXPECT_EQ(completedDispatcher.handler_, nullptr); +} + +/* + * @tc.number : CompletedDispatcher_0300 + * @tc.name : CompletedDispatcher PerformReceive + * @tc.desc : 1.The parameter is not nullptr + */ +HWTEST_F(CompletedDispatcherTest, CompletedDispatcher_0300, Function | MediumTest | Level1) +{ + std::shared_ptr callBack = + std::make_shared(); + CompletedDispatcher completedDispatcher(nullptr, callBack, nullptr); + + Want want = MakeWant("device", "ability", "bundleName"); + std::string key = "key"; + bool value = true; + WantParams wParams; + wParams.SetParam(key, Boolean::Box(value)); + completedDispatcher.PerformReceive(want, 10, "test", wParams, 0, 0, 1); + EXPECT_EQ(completedDispatcher.want_.GetElement().GetBundleName(), "bundleName"); + EXPECT_EQ(completedDispatcher.want_.GetElement().GetAbilityName(), "ability"); + EXPECT_EQ(completedDispatcher.resultCode_, 10); + EXPECT_EQ(completedDispatcher.resultData_, "test"); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(completedDispatcher.resultExtras_.GetParam(key))), value); + EXPECT_EQ(CompletedCallbackSon::code, 100); + CompletedCallbackSon::code = 0; +} + +/* + * @tc.number : CompletedDispatcher_0400 + * @tc.name : CompletedDispatcher PerformReceive + * @tc.desc : 1.The parameter is not nullptr + * 2.called callBack + */ +HWTEST_F(CompletedDispatcherTest, CompletedDispatcher_0400, Function | MediumTest | Level1) +{ + std::shared_ptr callBack = + std::make_shared(); + std::shared_ptr handler = std::make_shared(); + CompletedDispatcher completedDispatcher(nullptr, callBack, handler); + + Want want = MakeWant("device", "ability", "bundleName"); + std::string key = "key"; + bool value = false; + WantParams wParams; + wParams.SetParam(key, Boolean::Box(value)); + completedDispatcher.PerformReceive(want, 10, "test", wParams, 0, 0, 1); + EXPECT_EQ(completedDispatcher.want_.GetElement().GetBundleName(), "bundleName"); + EXPECT_EQ(completedDispatcher.want_.GetElement().GetAbilityName(), "ability"); + EXPECT_EQ(completedDispatcher.resultCode_, 10); + EXPECT_EQ(completedDispatcher.resultData_, "test"); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(completedDispatcher.resultExtras_.GetParam(key))), value); + EXPECT_EQ(CompletedCallbackSon::code, 0); + CompletedCallbackSon::code = 0; +} + +/* + * @tc.number : CompletedDispatcher_0500 + * @tc.name : CompletedDispatcher Run + * @tc.desc : 1.The parameter is not nullptr + * 2.called callBack + */ +HWTEST_F(CompletedDispatcherTest, CompletedDispatcher_0500, Function | MediumTest | Level1) +{ + std::shared_ptr callBack = + std::make_shared(); + CompletedDispatcher completedDispatcher(nullptr, callBack, nullptr); + EXPECT_EQ(completedDispatcher.callback_, callBack); + completedDispatcher.Run(); + EXPECT_EQ(CompletedCallbackSon::code, 100); + CompletedCallbackSon::code = 0; +} + +/* + * @tc.number : CompletedDispatcher_0600 + * @tc.name : CompletedDispatcher Run + * @tc.desc : 1.The parameter is nullptr + * 2.no called callBack + */ +HWTEST_F(CompletedDispatcherTest, CompletedDispatcher_0600, Function | MediumTest | Level1) +{ + CompletedDispatcher completedDispatcher(nullptr, nullptr, nullptr); + EXPECT_EQ(completedDispatcher.callback_, nullptr); + completedDispatcher.Run(); + EXPECT_EQ(CompletedCallbackSon::code, 0); + CompletedCallbackSon::code = 0; +} +} // namespace OHOS::AbilityRuntime::WantAgent \ No newline at end of file diff --git a/frameworks/kits/wantagent/test/unittest/pending_want_test/BUILD.gn b/frameworks/kits/wantagent/test/unittest/pending_want_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..731b0b73b5cb9cbc28d16724934c4c79254394aa --- /dev/null +++ b/frameworks/kits/wantagent/test/unittest/pending_want_test/BUILD.gn @@ -0,0 +1,68 @@ +# 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("//base/notification/ans_standard/notification.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +module_output_path = "ans_standard/wantagent" + +ohos_unittest("pending_want_test") { + module_out_path = module_output_path + include_dirs = [ + "//aafwk/standard/frameworks/kits/appkit/native/ability_runtime/context/", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//utils/system/safwk/native/include", + "//utils/native/base/include", + ] + + sources = [ "pending_want_test.cpp" ] + + configs = [ "//utils/native/base:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${core_path}:ans_core", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + ] +} + +group("unittest") { + testonly = true + deps = [ ":pending_want_test" ] +} diff --git a/frameworks/kits/wantagent/test/unittest/pending_want_test/pending_want_test.cpp b/frameworks/kits/wantagent/test/unittest/pending_want_test/pending_want_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c8e6ed1a744cfa340ceb12f199ef3b7bcd2f7e3c --- /dev/null +++ b/frameworks/kits/wantagent/test/unittest/pending_want_test/pending_want_test.cpp @@ -0,0 +1,678 @@ +/* + * 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 +#include "ability_manager_client.h" +#include "cancel_listener.h" +#include "completed_callback.h" +#include "completed_dispatcher.h" +#include "context/context.h" +#include "context_container.h" +#include "context_impl.h" +#include "element_name.h" +#include "event_handler.h" +#include "iservice_registry.h" +#include "ohos/aafwk/base/base_types.h" +#define private public +#define protected public +#include "pending_want.h" +#undef private +#undef protected +#include "sa_mgr_client.h" +#include "system_ability_definition.h" +#include "want.h" +#include "wants_info.h" +#include "want_params.h" +#include "want_receiver_stub.h" +#include "want_agent_helper.h" +#include "want_sender_info.h" +#include "want_sender_stub.h" +#include "ohos/aafwk/base/array_wrapper.h" +#include "ohos/aafwk/base/bool_wrapper.h" +#include "ohos/aafwk/base/zchar_wrapper.h" +#include "ohos/aafwk/base/byte_wrapper.h" +#include "ohos/aafwk/base/double_wrapper.h" +#include "ohos/aafwk/base/float_wrapper.h" +#include "ohos/aafwk/base/int_wrapper.h" +#include "ohos/aafwk/base/long_wrapper.h" +#include "ohos/aafwk/base/short_wrapper.h" +#include "ohos/aafwk/base/string_wrapper.h" + +using namespace testing::ext; +using namespace OHOS::AAFwk; +using namespace OHOS; +using OHOS::AppExecFwk::ElementName; +using namespace OHOS::AppExecFwk; +using vector_str = std::vector; + +namespace OHOS::AbilityRuntime::WantAgent { +class PendingWantTest : public testing::Test { +public: + PendingWantTest() + {} + ~PendingWantTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName); + + static int callBackCancelListenerConnt; + + class WantSender : public AAFwk::WantSenderStub { + public: + void Send(SenderInfo &senderInfo) override; + }; + + class CancelListenerSon : public CancelListener { + public: + void OnCancelled(int resultCode) override; + }; +}; + +int PendingWantTest::callBackCancelListenerConnt = 0; + +void PendingWantTest::WantSender::Send(SenderInfo &senderInfo) +{} + +void PendingWantTest::CancelListenerSon::OnCancelled(int resultCode) +{ + callBackCancelListenerConnt++; +} + +Want PendingWantTest::MakeWant(std::string deviceId, std::string abilityName, std::string bundleName) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + return want; +} + +std::shared_ptr GetAppContext() +{ + std::shared_ptr context = std::make_shared(); + return context; +} + +void PendingWantTest::SetUpTestCase(void) +{} + +void PendingWantTest::TearDownTestCase(void) +{} + +void PendingWantTest::SetUp(void) +{} + +void PendingWantTest::TearDown(void) +{} + +/* + * @tc.number : PendingWant_0100 + * @tc.name : PendingWant Constructors + * @tc.desc : 1.The parameter is nullptr + */ +HWTEST_F(PendingWantTest, PendingWant_0100, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + EXPECT_EQ(pendingWant.target_, nullptr); + EXPECT_EQ(pendingWant.cancelReceiver_, nullptr); + EXPECT_EQ(pendingWant.whitelistToken_, nullptr); +} + +/* + * @tc.number : PendingWant_0200 + * @tc.name : PendingWant Constructors + * @tc.desc : 1.The parameter target is not nullptr + */ +HWTEST_F(PendingWantTest, PendingWant_0200, Function | MediumTest | Level1) +{ + sptr target(new (std::nothrow) WantSender()); + PendingWant pendingWant(target); + EXPECT_EQ(pendingWant.target_, target); + EXPECT_EQ(pendingWant.cancelReceiver_, nullptr); + EXPECT_EQ(pendingWant.whitelistToken_, nullptr); +} + +/* + * @tc.number : PendingWant_0300 + * @tc.name : PendingWant GetType + * @tc.desc : 1.Get PendingWant Type (UNKNOWN_TYPE) + */ +HWTEST_F(PendingWantTest, PendingWant_0300, Function | MediumTest | Level1) +{ + sptr target = nullptr; + PendingWant pendingWant(target); + EXPECT_EQ(pendingWant.target_, target); + EXPECT_EQ(pendingWant.GetType(target), WantAgentConstant::OperationType::UNKNOWN_TYPE); +} + +/* + * @tc.number : PendingWant_0400 + * @tc.name : PendingWant GetAbility + * @tc.desc : 1.Get pendingWant (context is nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_0400, Function | MediumTest | Level1) +{ + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + unsigned int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetAbility(nullptr, requestCode, want, flags); + EXPECT_EQ(pendingWant, nullptr); +} + + +/* + * @tc.number : PendingWant_0600 + * @tc.name : PendingWant GetAbility + * @tc.desc : 1.Get pendingWant (options is not nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_0600, Function | MediumTest | Level1) +{ + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + bool value = true; + std::string key = "key"; + std::shared_ptr wParams = std::make_shared(); + wParams->SetParam(key, Boolean::Box(value)); + unsigned int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetAbility( + GetAppContext(), requestCode, want, flags, wParams); + EXPECT_NE(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_0700 + * @tc.name : PendingWant GetAbilities + * @tc.desc : 1.Get pendingWant (context is nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_0700, Function | MediumTest | Level1) +{ + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + std::shared_ptr want2 = std::make_shared(); + ElementName element2("device", "bundleName", "abilityName"); + want2->SetElement(element2); + std::vector> wants; + wants.emplace_back(want); + wants.emplace_back(want2); + unsigned int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetAbilities( + nullptr, requestCode, wants, flags); + EXPECT_EQ(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_0800 + * @tc.name : PendingWant GetAbilities + * @tc.desc : 1.Get pendingWant (context is not nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_0800, Function | MediumTest | Level1) +{ + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + std::shared_ptr want2 = std::make_shared(); + ElementName element2("device", "bundleName", "abilityName"); + want2->SetElement(element2); + std::vector> wants; + wants.emplace_back(want); + wants.emplace_back(want2); + unsigned int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetAbilities( + GetAppContext(), requestCode, wants, flags); + EXPECT_NE(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_0900 + * @tc.name : PendingWant GetAbilities + * @tc.desc : 1.Get pendingWant (options is not nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_0900, Function | MediumTest | Level1) +{ + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + std::shared_ptr want2 = std::make_shared(); + ElementName element2("device", "bundleName", "abilityName"); + want2->SetElement(element2); + std::vector> wants; + wants.emplace_back(want); + wants.emplace_back(want2); + bool value = true; + std::string key = "key"; + std::shared_ptr wParams = std::make_shared(); + wParams->SetParam(key, Boolean::Box(value)); + unsigned int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetAbilities( + GetAppContext(), requestCode, wants, flags, wParams); + EXPECT_NE(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_1000 + * @tc.name : PendingWant GetCommonEventAsUser + * @tc.desc : 1.Get pendingWant (context is nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_1000, Function | MediumTest | Level1) +{ + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + unsigned int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetCommonEventAsUser( + nullptr, requestCode, want, flags, 0); + EXPECT_EQ(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_1100 + * @tc.name : PendingWant GetCommonEventAsUser + * @tc.desc : 1.Get pendingWant (context is not nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_1100, Function | MediumTest | Level1) +{ + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + unsigned int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetCommonEventAsUser( + GetAppContext(), requestCode, want, flags, 0); + EXPECT_NE(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_1200 + * @tc.name : PendingWant GetCommonEventAsUser + * @tc.desc : 1.Get pendingWant (want is nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_1200, Function | MediumTest | Level1) +{ + int requestCode = 10; + std::shared_ptr want; + unsigned int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetCommonEventAsUser( + GetAppContext(), requestCode, want, flags, 0); + EXPECT_NE(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_1300 + * @tc.name : PendingWant GetService + * @tc.desc : 1.Get pendingWant (want is nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_1300, Function | MediumTest | Level1) +{ + int requestCode = 10; + std::shared_ptr want; + unsigned int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetService( + GetAppContext(), requestCode, want, flags); + EXPECT_NE(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_1400 + * @tc.name : PendingWant GetService + * @tc.desc : 1.Get pendingWant (context is nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_1400, Function | MediumTest | Level1) +{ + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + unsigned int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetService(nullptr, requestCode, want, flags); + EXPECT_EQ(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_1500 + * @tc.name : PendingWant GetForegroundService + * @tc.desc : 1.Get pendingWant (want is nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_1500, Function | MediumTest | Level1) +{ + int requestCode = 10; + std::shared_ptr want; + unsigned int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetForegroundService( + GetAppContext(), requestCode, want, flags); + EXPECT_NE(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_1600 + * @tc.name : PendingWant GetForegroundService + * @tc.desc : 1.Get pendingWant (context is nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_1600, Function | MediumTest | Level1) +{ + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + unsigned int flags = 1; + flags |= FLAG_NO_CREATE; + std::shared_ptr pendingWant = PendingWant::GetForegroundService(nullptr, requestCode, want, flags); + EXPECT_EQ(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_1700 + * @tc.name : PendingWant GetForegroundService + * @tc.desc : 1.Get pendingWant (want is nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_1700, Function | MediumTest | Level1) +{ + int requestCode = 10; + std::shared_ptr want; + unsigned int flags = 1; + flags |= FLAG_NO_CREATE; + WantAgentConstant::OperationType type = WantAgentConstant::OperationType::START_FOREGROUND_SERVICE; + std::shared_ptr pendingWant = + PendingWant::BuildServicePendingWant(GetAppContext(), requestCode, want, flags, type); + EXPECT_NE(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_1800 + * @tc.name : PendingWant GetForegroundService + * @tc.desc : 1.Get pendingWant (context is nullptr) + */ +HWTEST_F(PendingWantTest, PendingWant_1800, Function | MediumTest | Level1) +{ + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + unsigned int flags = 1; + flags |= FLAG_NO_CREATE; + WantAgentConstant::OperationType type = WantAgentConstant::OperationType::START_FOREGROUND_SERVICE; + std::shared_ptr pendingWant = + PendingWant::BuildServicePendingWant(nullptr, requestCode, want, flags, type); + EXPECT_EQ(pendingWant, nullptr); +} + +/* + * @tc.number : PendingWant_1900 + * @tc.name : PendingWant Equals + * @tc.desc : 1.Equals + */ +HWTEST_F(PendingWantTest, PendingWant_1900, Function | MediumTest | Level1) +{ + sptr target(new (std::nothrow) WantSender()); + std::shared_ptr pendingWant = std::make_shared(target); + sptr target2(nullptr); + std::shared_ptr pendingWant2 = std::make_shared(target2); + EXPECT_EQ(pendingWant->Equals(pendingWant, pendingWant2), false); +} + +/* + * @tc.number : PendingWant_2000 + * @tc.name : PendingWant Equals + * @tc.desc : 1.Equals + */ +HWTEST_F(PendingWantTest, PendingWant_2000, Function | MediumTest | Level1) +{ + sptr target(new (std::nothrow) WantSender()); + std::shared_ptr pendingWant = std::make_shared(target); + std::shared_ptr pendingWant2(nullptr); + EXPECT_EQ(pendingWant->Equals(pendingWant, pendingWant2), false); +} + +/* + * @tc.number : PendingWant_2100 + * @tc.name : PendingWant SendAndReturnResult + * @tc.desc : SendAndReturnResult + */ +HWTEST_F(PendingWantTest, PendingWant_2100, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + int requestCode = 10; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + bool value = true; + std::shared_ptr wParams = std::make_shared(); + std::string key = "key"; + wParams->SetParam(key, Boolean::Box(value)); + unsigned int flags = 1; + flags |= FLAG_NO_CREATE; + AbilityManagerClient::GetInstance()->Connect(); + EXPECT_EQ(INNER_ERR, + pendingWant.SendAndReturnResult(requestCode, want, nullptr, "Permission", nullptr, nullptr)); +} + +/* + * @tc.number : PendingWant_2300 + * @tc.name : PendingWant Equals + * @tc.desc : Equals + */ +HWTEST_F(PendingWantTest, PendingWant_2300, Function | MediumTest | Level1) +{ + sptr target(new (std::nothrow) WantSender()); + std::shared_ptr pendingWant = std::make_shared(target); + std::shared_ptr pendingWant2 = std::make_shared(target); + EXPECT_EQ(pendingWant->Equals(pendingWant, pendingWant2), true); +} + +/* + * @tc.number : PendingWant_2400 + * @tc.name : PendingWant GetTarget + * @tc.desc : 1.GetTarget + */ +HWTEST_F(PendingWantTest, PendingWant_2400, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + auto target = pendingWant.GetTarget(); + EXPECT_EQ(target, nullptr); +} + +/* + * @tc.number : PendingWant_2500 + * @tc.name : PendingWant GetTarget + * @tc.desc : 1.GetTarget + */ +HWTEST_F(PendingWantTest, PendingWant_2500, Function | MediumTest | Level1) +{ + sptr target(new (std::nothrow) WantSender()); + PendingWant pendingWant(target); + auto target1 = pendingWant.GetTarget(); + EXPECT_EQ(target1, target); +} + +/* + * @tc.number : PendingWant_2600 + * @tc.name : PendingWant RegisterCancelListener + * @tc.desc : 1.RegisterCancelListener + */ +HWTEST_F(PendingWantTest, PendingWant_2600, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + std::shared_ptr cancelListener1 = std::make_shared(); + std::shared_ptr cancelListener2 = std::make_shared(); + pendingWant.RegisterCancelListener(cancelListener1, nullptr); + pendingWant.RegisterCancelListener(cancelListener2, nullptr); + EXPECT_EQ(static_cast(pendingWant.cancelListeners_.size()), 2); +} + +/* + * @tc.number : PendingWant_2700 + * @tc.name : PendingWant RegisterCancelListener + * @tc.desc : 1.RegisterCancelListener + */ +HWTEST_F(PendingWantTest, PendingWant_2700, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + std::shared_ptr cancelListener2 = std::make_shared(); + pendingWant.RegisterCancelListener(nullptr, nullptr); + pendingWant.RegisterCancelListener(cancelListener2, nullptr); + EXPECT_EQ(static_cast(pendingWant.cancelListeners_.size()), 1); +} + +/* + * @tc.number : PendingWant_2800 + * @tc.name : PendingWant RegisterCancelListener + * @tc.desc : 1.RegisterCancelListener + */ +HWTEST_F(PendingWantTest, PendingWant_2800, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + pendingWant.RegisterCancelListener(nullptr, nullptr); + pendingWant.RegisterCancelListener(nullptr, nullptr); + EXPECT_EQ(static_cast(pendingWant.cancelListeners_.size()), 0); +} + +/* + * @tc.number : PendingWant_2900 + * @tc.name : PendingWant NotifyCancelListeners + * @tc.desc : 1.NotifyCancelListeners + */ +HWTEST_F(PendingWantTest, PendingWant_2900, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + std::shared_ptr cancelListener1 = std::make_shared(); + std::shared_ptr cancelListener2 = std::make_shared(); + pendingWant.RegisterCancelListener(cancelListener1, nullptr); + pendingWant.RegisterCancelListener(cancelListener2, nullptr); + pendingWant.NotifyCancelListeners(0); + EXPECT_EQ(callBackCancelListenerConnt, 2); + callBackCancelListenerConnt = 0; +} + +/* + * @tc.number : PendingWant_3000 + * @tc.name : PendingWant NotifyCancelListeners + * @tc.desc : 1.NotifyCancelListeners + */ +HWTEST_F(PendingWantTest, PendingWant_3000, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + std::shared_ptr cancelListener2 = std::make_shared(); + pendingWant.RegisterCancelListener(nullptr, nullptr); + pendingWant.RegisterCancelListener(cancelListener2, nullptr); + pendingWant.NotifyCancelListeners(0); + EXPECT_EQ(callBackCancelListenerConnt, 1); + callBackCancelListenerConnt = 0; +} + +/* + * @tc.number : PendingWant_3100 + * @tc.name : PendingWant NotifyCancelListeners + * @tc.desc : 1.NotifyCancelListeners + */ +HWTEST_F(PendingWantTest, PendingWant_3100, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + pendingWant.RegisterCancelListener(nullptr, nullptr); + pendingWant.RegisterCancelListener(nullptr, nullptr); + pendingWant.NotifyCancelListeners(0); + EXPECT_EQ(callBackCancelListenerConnt, 0); + callBackCancelListenerConnt = 0; +} + +/* + * @tc.number : PendingWant_3200 + * @tc.name : PendingWant UnregisterCancelListener + * @tc.desc : 1.UnregisterCancelListener + */ +HWTEST_F(PendingWantTest, PendingWant_3200, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + std::shared_ptr cancelListener1 = std::make_shared(); + std::shared_ptr cancelListener2 = std::make_shared(); + pendingWant.RegisterCancelListener(cancelListener1, nullptr); + pendingWant.RegisterCancelListener(cancelListener2, nullptr); + EXPECT_EQ(static_cast(pendingWant.cancelListeners_.size()), 2); + pendingWant.UnregisterCancelListener(cancelListener1, nullptr); + EXPECT_EQ(static_cast(pendingWant.cancelListeners_.size()), 1); +} + +/* + * @tc.number : PendingWant_3300 + * @tc.name : PendingWant UnregisterCancelListener + * @tc.desc : 1.UnregisterCancelListener + */ +HWTEST_F(PendingWantTest, PendingWant_3300, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + std::shared_ptr cancelListener2 = std::make_shared(); + pendingWant.RegisterCancelListener(nullptr, nullptr); + pendingWant.RegisterCancelListener(cancelListener2, nullptr); + EXPECT_EQ(static_cast(pendingWant.cancelListeners_.size()), 1); + pendingWant.UnregisterCancelListener(cancelListener2, nullptr); + EXPECT_EQ(static_cast(pendingWant.cancelListeners_.size()), 0); +} + +/* + * @tc.number : PendingWant_3400 + * @tc.name : PendingWant UnregisterCancelListener + * @tc.desc : 1.UnregisterCancelListener + */ +HWTEST_F(PendingWantTest, PendingWant_3400, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + pendingWant.UnregisterCancelListener(nullptr, nullptr); + EXPECT_EQ(static_cast(pendingWant.cancelListeners_.size()), 0); +} + +/* + * @tc.number : PendingWant_3500 + * @tc.name : PendingWant GetWant + * @tc.desc : 1.GetWant + */ +HWTEST_F(PendingWantTest, PendingWant_3500, Function | MediumTest | Level1) +{ + PendingWant pendingWant(nullptr); + auto want = pendingWant.GetWant(nullptr); + EXPECT_EQ(want, nullptr); +} + +/* + * @tc.number : PendingWant_3600 + * @tc.name : PendingWant Equals + * @tc.desc : Equals + */ +HWTEST_F(PendingWantTest, PendingWant_3700, Function | MediumTest | Level1) +{ + std::shared_ptr pendingWant(nullptr); + std::shared_ptr pendingWant2(nullptr); + EXPECT_EQ(pendingWant->Equals(pendingWant, pendingWant2), true); +} +} // namespace OHOS::AbilityRuntime::WantAgent diff --git a/frameworks/kits/wantagent/test/unittest/trigger_Info_test/BUILD.gn b/frameworks/kits/wantagent/test/unittest/trigger_Info_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a9a53b57f374880bc8188ece3f2a915c6915a74f --- /dev/null +++ b/frameworks/kits/wantagent/test/unittest/trigger_Info_test/BUILD.gn @@ -0,0 +1,60 @@ +# 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("//base/notification/ans_standard/notification.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +module_output_path = "ans_standard/wantagent" + +ohos_unittest("trigger_Info_test") { + module_out_path = module_output_path + include_dirs = [ "//foundation/aafwk/standard/services/abilitymgr/include" ] + + sources = [ "trigger_Info_test.cpp" ] + + configs = [ "//utils/native/base:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${core_path}:ans_core", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + ] +} + +group("unittest") { + testonly = true + deps = [ ":trigger_Info_test" ] +} diff --git a/frameworks/kits/wantagent/test/unittest/trigger_Info_test/trigger_Info_test.cpp b/frameworks/kits/wantagent/test/unittest/trigger_Info_test/trigger_Info_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f7dbcdf95552514e56cc74e061b6717aeebfa1c --- /dev/null +++ b/frameworks/kits/wantagent/test/unittest/trigger_Info_test/trigger_Info_test.cpp @@ -0,0 +1,225 @@ +/* + * 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 + +#include "completed_callback.h" +#include "event_handler.h" +#include "element_name.h" +#include "ohos/aafwk/base/base_types.h" +#include "pending_want.h" +#define private public +#define protected public +#include "trigger_info.h" +#undef private +#undef protected +#include "want.h" +#include "want_params.h" +#include "want_receiver_stub.h" +#include "ohos/aafwk/base/bool_wrapper.h" + +using namespace testing::ext; +using namespace OHOS::AAFwk; +using namespace OHOS; +using OHOS::AppExecFwk::ElementName; +using namespace OHOS::AppExecFwk; +using vector_str = std::vector; + +namespace OHOS::AbilityRuntime::WantAgent { +class TriggerInfoTest : public testing::Test { +public: + TriggerInfoTest() + {} + ~TriggerInfoTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void TriggerInfoTest::SetUpTestCase(void) +{} + +void TriggerInfoTest::TearDownTestCase(void) +{} + +void TriggerInfoTest::SetUp(void) +{} + +void TriggerInfoTest::TearDown(void) +{} + +/* + * @tc.number : TriggerInfo_0100 + * @tc.name : TriggerInfo Constructors + * @tc.desc : 1.def Constructors + */ +HWTEST_F(TriggerInfoTest, TriggerInfo_0100, Function | MediumTest | Level1) +{ + TriggerInfo triggerInfo; + EXPECT_EQ(triggerInfo.permission_, ""); + EXPECT_EQ(triggerInfo.extraInfo_, nullptr); + EXPECT_EQ(triggerInfo.want_, nullptr); + EXPECT_EQ(triggerInfo.resultCode_, 0); +} + +/* + * @tc.number : TriggerInfo_0200 + * @tc.name : TriggerInfo Constructors + * @tc.desc : 1.def Constructors + */ +HWTEST_F(TriggerInfoTest, TriggerInfo_0200, Function | MediumTest | Level1) +{ + std::string permission = "nihao"; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + bool value = true; + std::string key = "key"; + std::shared_ptr wParams = std::make_shared(); + wParams->SetParam(key, Boolean::Box(value)); + int resultCode = 10; + TriggerInfo triggerInfo(permission, wParams, want, resultCode); + EXPECT_EQ(triggerInfo.permission_, permission); + EXPECT_NE(triggerInfo.extraInfo_, wParams); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(triggerInfo.extraInfo_->GetParam(key))), value); + EXPECT_NE(triggerInfo.want_, want); + EXPECT_EQ(triggerInfo.want_->GetElement().GetBundleName(), "bundleName"); + EXPECT_EQ(triggerInfo.want_->GetElement().GetAbilityName(), "abilityName"); + EXPECT_EQ(triggerInfo.resultCode_, resultCode); +} + +/* + * @tc.number : TriggerInfo_0300 + * @tc.name : TriggerInfo Constructors + * @tc.desc : 1.copy Constructors + */ +HWTEST_F(TriggerInfoTest, TriggerInfo_0300, Function | MediumTest | Level1) +{ + std::string permission = "nihao"; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + bool value = true; + std::string key = "key"; + std::shared_ptr wParams = std::make_shared(); + wParams->SetParam(key, Boolean::Box(value)); + int resultCode = 10; + TriggerInfo triggerInfo(permission, wParams, want, resultCode); + EXPECT_EQ(triggerInfo.permission_, permission); + EXPECT_NE(triggerInfo.extraInfo_, wParams); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(triggerInfo.extraInfo_->GetParam(key))), value); + EXPECT_NE(triggerInfo.want_, want); + EXPECT_EQ(triggerInfo.want_->GetElement().GetBundleName(), "bundleName"); + EXPECT_EQ(triggerInfo.want_->GetElement().GetAbilityName(), "abilityName"); + EXPECT_EQ(triggerInfo.resultCode_, resultCode); + TriggerInfo triggerInfo1(triggerInfo); + EXPECT_EQ(triggerInfo1.permission_, triggerInfo.permission_); + EXPECT_NE(triggerInfo1.extraInfo_, triggerInfo.extraInfo_); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(triggerInfo1.extraInfo_->GetParam(key))), value); + EXPECT_NE(triggerInfo1.want_, triggerInfo.want_); + EXPECT_EQ(triggerInfo1.want_->GetElement().GetBundleName(), "bundleName"); + EXPECT_EQ(triggerInfo1.want_->GetElement().GetAbilityName(), "abilityName"); + EXPECT_EQ(triggerInfo1.resultCode_, triggerInfo.resultCode_); +} + +/* + * @tc.number : TriggerInfo_0400 + * @tc.name : TriggerInfo::Builder SetPermission + * @tc.desc : 1.SetPermission + */ +HWTEST_F(TriggerInfoTest, TriggerInfo_0400, Function | MediumTest | Level1) +{ + std::shared_ptr builder = std::make_shared(); + builder->SetPermission("nihao"); + EXPECT_EQ(builder->permission_, "nihao"); +} + +/* + * @tc.number : TriggerInfo_0500 + * @tc.name : TriggerInfo::Builder SetWantParams + * @tc.desc : 1.SetWantParams + */ +HWTEST_F(TriggerInfoTest, TriggerInfo_0500, Function | MediumTest | Level1) +{ + std::shared_ptr builder = std::make_shared(); + bool value = true; + std::string key = "key"; + std::shared_ptr wParams = std::make_shared(); + wParams->SetParam(key, Boolean::Box(value)); + builder->SetWantParams(wParams); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(builder->params_->GetParam(key))), value); +} + +/* + * @tc.number : TriggerInfo_0600 + * @tc.name : TriggerInfo::Builder SetWant + * @tc.desc : 1.SetWant + */ +HWTEST_F(TriggerInfoTest, TriggerInfo_0600, Function | MediumTest | Level1) +{ + std::shared_ptr builder = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + builder->SetWant(want); + EXPECT_EQ(builder->want_->GetElement().GetBundleName(), "bundleName"); + EXPECT_EQ(builder->want_->GetElement().GetAbilityName(), "abilityName"); +} + +/* + * @tc.number : TriggerInfo_0700 + * @tc.name : TriggerInfo::Builder SetResultCode + * @tc.desc : 1.SetResultCode + */ +HWTEST_F(TriggerInfoTest, TriggerInfo_0700, Function | MediumTest | Level1) +{ + std::shared_ptr builder = std::make_shared(); + int resultCode = 100; + builder->SetResultCode(resultCode); + EXPECT_EQ(builder->resultCode_, resultCode); +} + +/* + * @tc.number : TriggerInfo_0800 + * @tc.name : TriggerInfo::Builder Build + * @tc.desc : 1.Build,Great TriggerInfo object + */ +HWTEST_F(TriggerInfoTest, TriggerInfo_0800, Function | MediumTest | Level1) +{ + std::shared_ptr builder = std::make_shared(); + builder->SetPermission("nihao"); + bool value = true; + std::string key = "key"; + std::shared_ptr wParams = std::make_shared(); + wParams->SetParam(key, Boolean::Box(value)); + builder->SetWantParams(wParams); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + builder->SetWant(want); + int resultCode = 100; + builder->SetResultCode(resultCode); + + auto info = builder->Build(); + EXPECT_NE(info, nullptr); + EXPECT_EQ(info->permission_, "nihao"); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(info->extraInfo_->GetParam(key))), value); + EXPECT_EQ(info->want_->GetElement().GetBundleName(), "bundleName"); + EXPECT_EQ(info->want_->GetElement().GetAbilityName(), "abilityName"); + EXPECT_EQ(info->resultCode_, resultCode); +} +} // namespace OHOS::AbilityRuntime::WantAgent \ No newline at end of file diff --git a/frameworks/kits/wantagent/test/unittest/want_agent_helper_test/BUILD.gn b/frameworks/kits/wantagent/test/unittest/want_agent_helper_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..18f613946e604405cabfbff6776ad95b72c25321 --- /dev/null +++ b/frameworks/kits/wantagent/test/unittest/want_agent_helper_test/BUILD.gn @@ -0,0 +1,65 @@ +# 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("//base/notification/ans_standard/notification.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +module_output_path = "ans_standard/wantagent" + +ohos_unittest("want_agent_helper_test") { + module_out_path = module_output_path + include_dirs = [ + "//aafwk/standard/frameworks/kits/appkit/native/ability_runtime/context/", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime", + "//foundation/aafwk/standard/services/abilitymgr/include", + ] + + sources = [ "want_agent_helper_test.cpp" ] + + configs = [ "//utils/native/base:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${core_path}:ans_core", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + ] +} + +group("unittest") { + testonly = true + deps = [ ":want_agent_helper_test" ] +} diff --git a/frameworks/kits/wantagent/test/unittest/want_agent_helper_test/want_agent_helper_test.cpp b/frameworks/kits/wantagent/test/unittest/want_agent_helper_test/want_agent_helper_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e057b6dd931e170a8adf7324e781b9ae806cec04 --- /dev/null +++ b/frameworks/kits/wantagent/test/unittest/want_agent_helper_test/want_agent_helper_test.cpp @@ -0,0 +1,711 @@ +/* + * 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 +#include "ability_context.h" +#include "completed_callback.h" +#include "context_container.h" +#include "context_impl.h" +#include "context/context.h" +#include "element_name.h" +#include "event_handler.h" +#include "ohos/aafwk/base/base_types.h" +#include "pending_want.h" +#include "want.h" +#include "want_agent.h" +#include "want_agent_constant.h" +#define private public +#define protected public +#include "want_agent_helper.h" +#include "want_agent_info.h" +#undef private +#undef protected +#include "want_params.h" +#include "want_receiver_stub.h" +#include "want_sender_stub.h" +#include "ohos/aafwk/base/bool_wrapper.h" + +using namespace testing::ext; +using namespace OHOS::AAFwk; +using namespace OHOS; +using OHOS::AppExecFwk::ElementName; +using namespace OHOS::AppExecFwk; +using vector_str = std::vector; + +namespace OHOS::AbilityRuntime::WantAgent { +class WantAgentHelperTest : public testing::Test { +public: + WantAgentHelperTest() + {} + ~WantAgentHelperTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + class WantSender : public AAFwk::WantSenderStub { + public: + void Send(SenderInfo &senderInfo) override; + }; +}; + +void WantAgentHelperTest::WantSender::Send(SenderInfo &senderInfo) +{} + +void WantAgentHelperTest::SetUpTestCase(void) +{} + +void WantAgentHelperTest::TearDownTestCase(void) +{} + +void WantAgentHelperTest::SetUp(void) +{} + +void WantAgentHelperTest::TearDown(void) +{} + +/* + * @tc.number : WantAgentHelper_0100 + * @tc.name : WantAgentHelper Constructors + * @tc.desc : 1.WantAgentConstant::Flags::ONE_TIME_FLAG + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_0100, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::vector flags; + flags.emplace_back(WantAgentConstant::Flags::ONE_TIME_FLAG); + EXPECT_EQ(wantAgentHelper->FlagsTransformer(flags), static_cast(0x40000000)); +} + +/* + * @tc.number : WantAgentHelper_0200 + * @tc.name : WantAgentHelper Constructors + * @tc.desc : 1.WantAgentConstant::Flags::NO_BUILD_FLAG + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_0200, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::vector flags; + flags.emplace_back(WantAgentConstant::Flags::NO_BUILD_FLAG); + EXPECT_EQ(wantAgentHelper->FlagsTransformer(flags), static_cast(0x20000000)); +} + +/* + * @tc.number : WantAgentHelper_0300 + * @tc.name : WantAgentHelper Constructors + * @tc.desc : 1.WantAgentConstant::Flags::CANCEL_PRESENT_FLAG + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_0300, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::vector flags; + flags.emplace_back(WantAgentConstant::Flags::CANCEL_PRESENT_FLAG); + EXPECT_EQ(wantAgentHelper->FlagsTransformer(flags), static_cast(0x10000000)); +} + +/* + * @tc.number : WantAgentHelper_0400 + * @tc.name : WantAgentHelper Constructors + * @tc.desc : 1.WantAgentConstant::Flags::UPDATE_PRESENT_FLAG + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_0400, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::vector flags; + flags.emplace_back(WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); + EXPECT_EQ(wantAgentHelper->FlagsTransformer(flags), static_cast(0x8000000)); +} + +/* + * @tc.number : WantAgentHelper_0500 + * @tc.name : WantAgentHelper Constructors + * @tc.desc : 1.WantAgentConstant::Flags::CONSTANT_FLAG + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_0500, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::vector flags; + flags.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + EXPECT_EQ(wantAgentHelper->FlagsTransformer(flags), static_cast(0x4000000)); +} + +/* + * @tc.number : WantAgentHelper_0600 + * @tc.name : WantAgentHelper Constructors + * @tc.desc : 1.WantAgentConstant::Flags::REPLACE_BUNDLE + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_0600, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::vector flags; + flags.emplace_back(WantAgentConstant::Flags::REPLACE_BUNDLE); + EXPECT_EQ( + wantAgentHelper->FlagsTransformer(flags), static_cast(WantAgentConstant::Flags::ONE_TIME_FLAG)); +} + +/* + * @tc.number : WantAgentHelper_0700 + * @tc.name : WantAgentHelper Constructors + * @tc.desc : 1.WantAgentConstant::Flags::CONSTANT_FLAG | UPDATE_PRESENT_FLAG | REPLACE_BUNDLE + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_0700, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::vector flags; + flags.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + flags.emplace_back(WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); + flags.emplace_back(WantAgentConstant::Flags::REPLACE_BUNDLE); + EXPECT_EQ(wantAgentHelper->FlagsTransformer(flags), static_cast(0xc000000)); +} + +/* + * @tc.number : WantAgentHelper_0800 + * @tc.name : WantAgentHelper GetWantAgent + * @tc.desc : 1.GetWantAgent context is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_0800, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + WantAgentInfo wantAgentInfo; + auto wantAgent = wantAgentHelper->GetWantAgent(nullptr, wantAgentInfo); + EXPECT_EQ(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_0900 + * @tc.name : WantAgentHelper GetWantAgent + * @tc.desc : 1.GetWantAgent context is not nullptr + * ` 2.wantAgentInfo.wants_ empty + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_0900, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.clear(); + auto wantAgent = wantAgentHelper->GetWantAgent(nullptr, wantAgentInfo); + EXPECT_EQ(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_1000 + * @tc.name : WantAgentHelper GetWantAgent + * @tc.desc : 1.GetWantAgent context is not nullptr + * 2.wantAgentInfo.wants_.siez() != wantAgentInfo.flags_.siez() + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_1000, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); + WantAgentInfo wantAgentInfo; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.clear(); + auto wantAgent = wantAgentHelper->GetWantAgent(context, wantAgentInfo); + EXPECT_EQ(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_1100 + * @tc.name : WantAgentHelper GetWantAgent + * @tc.desc : 1.GetWantAgent context is not nullptr + * 2.wantAgentInfo.wants_.siez() == wantAgentInfo.flags_.siez() + * 3.FlagsTransformer return 0 + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_1100, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); + WantAgentInfo wantAgentInfo; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::REPLACE_BUNDLE); + auto wantAgent = wantAgentHelper->GetWantAgent(context, wantAgentInfo); + EXPECT_EQ(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_1200 + * @tc.name : WantAgentHelper GetWantAgent + * @tc.desc : 1.GetWantAgent context is not nullptr + * 2.wantAgentInfo.wants_.siez() == wantAgentInfo.flags_.siez() + * 3.FlagsTransformer return ok + * 4.Type is WantAgentConstant::OperationType::START_ABILITY + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_1200, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr context = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.operationType_ = WantAgentConstant::OperationType::START_ABILITY; + wantAgentInfo.requestCode_ = 10; + auto wantAgent = wantAgentHelper->GetWantAgent(context, wantAgentInfo); + EXPECT_NE(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_1300 + * @tc.name : WantAgentHelper GetWantAgent + * @tc.desc : 1.GetWantAgent context is not nullptr + * 2.wantAgentInfo.wants_.siez() == wantAgentInfo.flags_.siez() + * 3.FlagsTransformer return ok + * 4.Type is WantAgentConstant::OperationType::START_ABILITIES + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_1300, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr context = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.operationType_ = WantAgentConstant::OperationType::START_ABILITIES; + wantAgentInfo.requestCode_ = 10; + auto wantAgent = wantAgentHelper->GetWantAgent(context, wantAgentInfo); + EXPECT_NE(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_1400 + * @tc.name : WantAgentHelper GetWantAgent + * @tc.desc : 1.GetWantAgent context is not nullptr + * 2.wantAgentInfo.wants_.siez() == wantAgentInfo.flags_.siez() + * 3.FlagsTransformer return ok + * 4.Type is WantAgentConstant::OperationType::START_SERVICE + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_1400, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr context = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.operationType_ = WantAgentConstant::OperationType::START_SERVICE; + wantAgentInfo.requestCode_ = 10; + auto wantAgent = wantAgentHelper->GetWantAgent(context, wantAgentInfo); + EXPECT_NE(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_1500 + * @tc.name : WantAgentHelper GetWantAgent + * @tc.desc : 1.GetWantAgent context is not nullptr + * 2.wantAgentInfo.wants_.siez() == wantAgentInfo.flags_.siez() + * 3.FlagsTransformer return ok + * 4.Type is WantAgentConstant::OperationType::START_FOREGROUND_SERVICE + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_1500, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr context = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.operationType_ = WantAgentConstant::OperationType::START_FOREGROUND_SERVICE; + wantAgentInfo.requestCode_ = 10; + auto wantAgent = wantAgentHelper->GetWantAgent(context, wantAgentInfo); + EXPECT_NE(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_1600 + * @tc.name : WantAgentHelper GetWantAgent + * @tc.desc : 1.GetWantAgent context is not nullptr + * 2.wantAgentInfo.wants_.siez() == wantAgentInfo.flags_.siez() + * 3.FlagsTransformer return ok + * 4.Type is WantAgentConstant::OperationType::START_FOREGROUND_SERVICE + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_1600, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr context = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.operationType_ = WantAgentConstant::OperationType::SEND_COMMON_EVENT; + wantAgentInfo.requestCode_ = 10; + auto wantAgent = wantAgentHelper->GetWantAgent(context, wantAgentInfo); + EXPECT_NE(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_1700 + * @tc.name : WantAgentHelper GetWantAgent + * @tc.desc : 1.GetWantAgent context is not nullptr + * 2.wantAgentInfo.wants_.siez() == wantAgentInfo.flags_.siez() + * 3.FlagsTransformer return ok + * 4.Type is 100 + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_1700, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.operationType_ = static_cast(100); + wantAgentInfo.requestCode_ = 10; + auto wantAgent = wantAgentHelper->GetWantAgent(context, wantAgentInfo); + EXPECT_EQ(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_1800 + * @tc.name : WantAgentHelper GetWantAgent(const WantAgentInfo ¶msInfo) + * @tc.desc : 1.wantAgentInfo.wants_.siez() == 0 + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_1800, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.clear(); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.operationType_ = static_cast(100); + wantAgentInfo.requestCode_ = 10; + auto wantAgent = wantAgentHelper->GetWantAgent(wantAgentInfo); + EXPECT_EQ(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_1900 + * @tc.name : WantAgentHelper GetWantAgent(const WantAgentInfo ¶msInfo) + * @tc.desc : 1.wantAgentInfo.wants_ not empty + * 2.wantAgentInfo.wants_.siez() != wantAgentInfo.flags_.siez() + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_1900, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.clear(); + wantAgentInfo.operationType_ = static_cast(100); + wantAgentInfo.requestCode_ = 10; + auto wantAgent = wantAgentHelper->GetWantAgent(wantAgentInfo); + EXPECT_EQ(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_2000 + * @tc.name : WantAgentHelper GetWantAgent(const WantAgentInfo ¶msInfo) + * @tc.desc : 1.wantAgentInfo.wants_ not empty + * 2.wantAgentInfo.wants_.siez() == wantAgentInfo.flags_.siez() + * 3.wantAgentInfo.wants_[0] is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_2000, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.emplace_back(nullptr); + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.operationType_ = static_cast(100); + wantAgentInfo.requestCode_ = 10; + auto wantAgent = wantAgentHelper->GetWantAgent(wantAgentInfo); + EXPECT_EQ(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_2100 + * @tc.name : WantAgentHelper GetWantAgent(const WantAgentInfo ¶msInfo) + * @tc.desc : 1.wantAgentInfo.wants_ not empty + * 2.wantAgentInfo.wants_.siez() == wantAgentInfo.flags_.siez() + * 3.wantAgentInfo.wants_[0] is not nullptr + * 4.wantAgentInfo.extraInfo_ is not nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_2100, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.operationType_ = static_cast(100); + wantAgentInfo.requestCode_ = 10; + bool value = true; + std::string key = "key"; + std::shared_ptr wParams = std::make_shared(); + wParams->SetParam(key, Boolean::Box(value)); + wantAgentInfo.extraInfo_ = wParams; + auto wantAgent = wantAgentHelper->GetWantAgent(wantAgentInfo); + EXPECT_EQ(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_2200 + * @tc.name : WantAgentHelper GetWantAgent(const WantAgentInfo ¶msInfo) + * @tc.desc : 1.wantAgentInfo.wants_ not empty + * 2.wantAgentInfo.wants_.siez() == wantAgentInfo.flags_.siez() + * 3.wantAgentInfo.wants_[0] is not nullptr + * 4.wantAgentInfo.extraInfo_ is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_2200, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + WantAgentInfo wantAgentInfo; + wantAgentInfo.wants_.emplace_back(want); + wantAgentInfo.flags_.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + wantAgentInfo.operationType_ = static_cast(100); + wantAgentInfo.requestCode_ = 10; + wantAgentInfo.extraInfo_ = nullptr; + auto wantAgent = wantAgentHelper->GetWantAgent(wantAgentInfo); + EXPECT_EQ(wantAgent, nullptr); +} + +/* + * @tc.number : WantAgentHelper_2300 + * @tc.name : WantAgentHelper GetType + * @tc.desc : 1.agent is not nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_2300, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + WantAgentInfo wantAgentInfo; + auto wantAgent = wantAgentHelper->GetWantAgent(nullptr, wantAgentInfo); + auto type = wantAgentHelper->GetType(wantAgent); + EXPECT_EQ(type, WantAgentConstant::OperationType::UNKNOWN_TYPE); +} + +/* + * @tc.number : WantAgentHelper_2400 + * @tc.name : WantAgentHelper GetType + * @tc.desc : 1.agent is not nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_2400, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr wantAgent(nullptr); + auto type = wantAgentHelper->GetType(wantAgent); + EXPECT_EQ(type, WantAgentConstant::OperationType::UNKNOWN_TYPE); +} + +/* + * @tc.number : WantAgentHelper_2500 + * @tc.name : WantAgentHelper GetType + * @tc.desc : 1.agent is not nullptr,PendingWant is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_2500, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr pendingWant(nullptr); + std::shared_ptr wantAgent = std::make_shared(pendingWant); + auto type = wantAgentHelper->GetType(wantAgent); + EXPECT_EQ(type, WantAgentConstant::OperationType::UNKNOWN_TYPE); +} + +/* + * @tc.number : WantAgentHelper_2600 + * @tc.name : WantAgentHelper JudgeEquality + * @tc.desc : 1.JudgeEquality + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_2600, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr wantAgent(nullptr); + std::shared_ptr wantAgent2(nullptr); + auto isEqual = wantAgentHelper->JudgeEquality(wantAgent, wantAgent2); + EXPECT_EQ(isEqual, true); +} + +/* + * @tc.number : WantAgentHelper_2700 + * @tc.name : WantAgentHelper JudgeEquality + * @tc.desc : 1.JudgeEquality,Judge whether it is equal or not + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_2700, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + sptr target(new (std::nothrow) WantSender()); + std::shared_ptr pendingWant = std::make_shared(target); + std::shared_ptr wantAgent = std::make_shared(pendingWant); + std::shared_ptr wantAgent2(nullptr); + auto isEqual = wantAgentHelper->JudgeEquality(wantAgent, wantAgent2); + EXPECT_EQ(isEqual, false); +} + +/* + * @tc.number : WantAgentHelper_2800 + * @tc.name : WantAgentHelper JudgeEquality + * @tc.desc : 1.JudgeEquality,Judge whether it is equal or not + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_2800, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + sptr target(new (std::nothrow) WantSender()); + std::shared_ptr pendingWant = std::make_shared(target); + std::shared_ptr wantAgent = std::make_shared(pendingWant); + std::shared_ptr wantAgent2 = std::make_shared(pendingWant); + auto isEqual = wantAgentHelper->JudgeEquality(wantAgent, wantAgent2); + EXPECT_EQ(isEqual, true); +} + +/* + * @tc.number : WantAgentHelper_2900 + * @tc.name : WantAgentHelper JudgeEquality + * @tc.desc : 1.JudgeEquality,Judge whether it is equal or not + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_2900, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + sptr target(new (std::nothrow) WantSender()); + std::shared_ptr pendingWant = std::make_shared(target); + std::shared_ptr pendingWant2(nullptr); + std::shared_ptr wantAgent = std::make_shared(pendingWant); + std::shared_ptr wantAgent2 = std::make_shared(pendingWant2); + auto isEqual = wantAgentHelper->JudgeEquality(wantAgent, wantAgent2); + EXPECT_EQ(isEqual, false); +} + +/* + * @tc.number : WantAgentHelper_3000 + * @tc.name : WantAgentHelper GetHashCode + * @tc.desc : 1.GetHashCode WantAgent is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_3000, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr wantAgent(nullptr); + auto hashCode = wantAgentHelper->GetHashCode(wantAgent); + EXPECT_EQ(hashCode, 0); +} + +/* + * @tc.number : WantAgentHelper_3100 + * @tc.name : WantAgentHelper GetHashCode + * @tc.desc : 1.GetHashCode WantAgent.PendingWant.target is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_3100, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr pendingWant(nullptr); + std::shared_ptr wantAgent = std::make_shared(pendingWant); + auto hashCode = wantAgentHelper->GetHashCode(wantAgent); + EXPECT_EQ(hashCode, 0); +} + +/* + * @tc.number : WantAgentHelper_3200 + * @tc.name : WantAgentHelper GetBundleName + * @tc.desc : 1.GetBundleName WantAgent is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_3200, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr wantAgent(nullptr); + auto bundleName = wantAgentHelper->GetBundleName(wantAgent); + EXPECT_EQ(bundleName, ""); +} + +/* + * @tc.number : WantAgentHelper_3300 + * @tc.name : WantAgentHelper GetBundleName + * @tc.desc : 1.GetBundleName WantAgent.PendingWant.target is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_3300, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr pendingWant(nullptr); + std::shared_ptr wantAgent = std::make_shared(pendingWant); + auto bundleName = wantAgentHelper->GetBundleName(wantAgent); + EXPECT_EQ(bundleName, ""); +} + +/* + * @tc.number : WantAgentHelper_3400 + * @tc.name : WantAgentHelper GetUid + * @tc.desc : 1.GetUid WantAgent is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_3400, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr wantAgent(nullptr); + auto uid = wantAgentHelper->GetUid(wantAgent); + EXPECT_EQ(uid, -1); +} + +/* + * @tc.number : WantAgentHelper_3500 + * @tc.name : WantAgentHelper GetUid + * @tc.desc : 1.GetUid WantAgent.PendingWant.target is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_3500, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr pendingWant(nullptr); + std::shared_ptr wantAgent = std::make_shared(pendingWant); + auto uid = wantAgentHelper->GetUid(wantAgent); + EXPECT_EQ(uid, -1); +} + +/* + * @tc.number : WantAgentHelper_3600 + * @tc.name : WantAgentHelper GetWant + * @tc.desc : 1.GetWant WantAgent is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_3600, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr wantAgent(nullptr); + auto want = wantAgentHelper->GetWant(wantAgent); + EXPECT_EQ(want, nullptr); +} + +/* + * @tc.number : WantAgentHelper_3700 + * @tc.name : WantAgentHelper GetWant + * @tc.desc : 1.GetWant WantAgent.PendingWant.target is nullptr + */ +HWTEST_F(WantAgentHelperTest, WantAgentHelper_3700, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgentHelper = std::make_shared(); + std::shared_ptr pendingWant(nullptr); + std::shared_ptr wantAgent = std::make_shared(pendingWant); + auto want = wantAgentHelper->GetWant(wantAgent); + EXPECT_EQ(want, nullptr); +} +} // namespace OHOS::AbilityRuntime::WantAgent \ No newline at end of file diff --git a/frameworks/kits/wantagent/test/unittest/want_agent_info_test/BUILD.gn b/frameworks/kits/wantagent/test/unittest/want_agent_info_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..ed8a7ca13d0ef1f7eefa7e89a3c4a75c61327e8c --- /dev/null +++ b/frameworks/kits/wantagent/test/unittest/want_agent_info_test/BUILD.gn @@ -0,0 +1,60 @@ +# 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("//base/notification/ans_standard/notification.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +module_output_path = "ans_standard/wantagent" + +ohos_unittest("want_agent_info_test") { + module_out_path = module_output_path + include_dirs = [ "//foundation/aafwk/standard/services/abilitymgr/include" ] + + sources = [ "want_agent_info_test.cpp" ] + + configs = [ "//utils/native/base:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${core_path}:ans_core", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + ] +} + +group("unittest") { + testonly = true + deps = [ ":want_agent_info_test" ] +} diff --git a/frameworks/kits/wantagent/test/unittest/want_agent_info_test/want_agent_info_test.cpp b/frameworks/kits/wantagent/test/unittest/want_agent_info_test/want_agent_info_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b8bfa5333e65871ab0ecf70a1337b11adf007344 --- /dev/null +++ b/frameworks/kits/wantagent/test/unittest/want_agent_info_test/want_agent_info_test.cpp @@ -0,0 +1,322 @@ +/* + * 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 +#include "ability_context.h" +#include "completed_callback.h" +#include "context_container.h" +#include "element_name.h" +#include "event_handler.h" +#include "ohos/aafwk/base/base_types.h" +#include "pending_want.h" +#include "want.h" +#include "want_agent.h" +#include "want_agent_constant.h" +#include "want_agent_helper.h" +#define private public +#define protected public +#include "want_agent_info.h" +#undef private +#undef protected +#include "want_params.h" +#include "want_receiver_stub.h" +#include "want_sender_stub.h" +#include "ohos/aafwk/base/bool_wrapper.h" + +using namespace testing::ext; +using namespace OHOS::AAFwk; +using namespace OHOS; +using OHOS::AppExecFwk::ElementName; +using namespace OHOS::AppExecFwk; +using vector_str = std::vector; + +namespace OHOS::AbilityRuntime::WantAgent { +class WantAgentInfoTest : public testing::Test { +public: + WantAgentInfoTest() + {} + ~WantAgentInfoTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + class WantSender : public AAFwk::WantSenderStub { + public: + void Send(SenderInfo &senderInfo) override; + }; +}; + +void WantAgentInfoTest::WantSender::Send(SenderInfo &senderInfo) +{} + +void WantAgentInfoTest::SetUpTestCase(void) +{} + +void WantAgentInfoTest::TearDownTestCase(void) +{} + +void WantAgentInfoTest::SetUp(void) +{} + +void WantAgentInfoTest::TearDown(void) +{} + +/* + * @tc.number : WantAgentInfo_0100 + * @tc.name : WantAgentInfo Constructors + * @tc.desc : 1.Constructors + */ +HWTEST_F(WantAgentInfoTest, WantAgentInfo_0100, Function | MediumTest | Level1) +{ + int requestCode = 10; + WantAgentConstant::OperationType operationType = WantAgentConstant::OperationType::START_ABILITY; + WantAgentConstant::Flags flag = WantAgentConstant::Flags::CONSTANT_FLAG; + std::vector> wants; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + wants.emplace_back(want); + std::shared_ptr extraInfo = std::make_shared(); + bool value = true; + std::string key = "key"; + extraInfo->SetParam(key, Boolean::Box(value)); + std::shared_ptr wantAgentInfo = + std::make_shared(requestCode, operationType, flag, wants, extraInfo); + EXPECT_EQ(wantAgentInfo->GetRequestCode(), requestCode); + EXPECT_EQ(wantAgentInfo->GetOperationType(), operationType); + EXPECT_EQ(wantAgentInfo->GetFlags().at(0), flag); + EXPECT_NE(wantAgentInfo->GetWants().at(0), want); + EXPECT_EQ(wantAgentInfo->GetWants().at(0)->GetElement().GetBundleName(), want->GetElement().GetBundleName()); + EXPECT_EQ(wantAgentInfo->GetWants().at(0)->GetElement().GetAbilityName(), want->GetElement().GetAbilityName()); + EXPECT_NE(wantAgentInfo->GetExtraInfo(), extraInfo); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(wantAgentInfo->GetExtraInfo()->GetParam(key))), + Boolean::Unbox(IBoolean::Query(extraInfo->GetParam(key)))); +} + +/* + * @tc.number : WantAgentInfo_0200 + * @tc.name : WantAgentInfo Constructors + * @tc.desc : 1.Constructors + */ +HWTEST_F(WantAgentInfoTest, WantAgentInfo_0200, Function | MediumTest | Level1) +{ + int requestCode = 10; + WantAgentConstant::OperationType operationType = WantAgentConstant::OperationType::START_ABILITY; + std::vector flags; + WantAgentConstant::Flags flag = WantAgentConstant::Flags::CONSTANT_FLAG; + flags.emplace_back(flag); + std::vector> wants; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + wants.emplace_back(want); + std::shared_ptr extraInfo = std::make_shared(); + bool value = true; + std::string key = "key"; + extraInfo->SetParam(key, Boolean::Box(value)); + std::shared_ptr wantAgentInfo = + std::make_shared(requestCode, operationType, flags, wants, extraInfo); + EXPECT_EQ(wantAgentInfo->GetRequestCode(), requestCode); + EXPECT_EQ(wantAgentInfo->GetOperationType(), operationType); + EXPECT_EQ(wantAgentInfo->GetFlags().at(0), flag); + EXPECT_NE(wantAgentInfo->GetWants().at(0), want); + EXPECT_EQ(wantAgentInfo->GetWants().at(0)->GetElement().GetBundleName(), want->GetElement().GetBundleName()); + EXPECT_EQ(wantAgentInfo->GetWants().at(0)->GetElement().GetAbilityName(), want->GetElement().GetAbilityName()); + EXPECT_NE(wantAgentInfo->GetExtraInfo(), extraInfo); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(wantAgentInfo->GetExtraInfo()->GetParam(key))), + Boolean::Unbox(IBoolean::Query(extraInfo->GetParam(key)))); +} + +/* + * @tc.number : WantAgentInfo_0300 + * @tc.name : WantAgentInfo Constructors + * @tc.desc : 1.Copy Constructors + */ +HWTEST_F(WantAgentInfoTest, WantAgentInfo_0300, Function | MediumTest | Level1) +{ + int requestCode = 10; + WantAgentConstant::OperationType operationType = WantAgentConstant::OperationType::START_ABILITY; + std::vector flags; + WantAgentConstant::Flags flag = WantAgentConstant::Flags::CONSTANT_FLAG; + flags.emplace_back(flag); + std::vector> wants; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + wants.emplace_back(want); + std::shared_ptr extraInfo = std::make_shared(); + bool value = true; + std::string key = "key"; + extraInfo->SetParam(key, Boolean::Box(value)); + std::shared_ptr wantAgentInfo = + std::make_shared(requestCode, operationType, flags, wants, extraInfo); + EXPECT_EQ(wantAgentInfo->GetRequestCode(), requestCode); + EXPECT_EQ(wantAgentInfo->GetOperationType(), operationType); + EXPECT_EQ(wantAgentInfo->GetFlags().at(0), flag); + EXPECT_NE(wantAgentInfo->GetWants().at(0), want); + EXPECT_EQ(wantAgentInfo->GetWants().at(0)->GetElement().GetBundleName(), want->GetElement().GetBundleName()); + EXPECT_EQ(wantAgentInfo->GetWants().at(0)->GetElement().GetAbilityName(), want->GetElement().GetAbilityName()); + EXPECT_NE(wantAgentInfo->GetExtraInfo(), extraInfo); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(wantAgentInfo->GetExtraInfo()->GetParam(key))), + Boolean::Unbox(IBoolean::Query(extraInfo->GetParam(key)))); + + WantAgentInfo wantAgentInfo1(wantAgentInfo); + EXPECT_EQ(wantAgentInfo->GetRequestCode(), wantAgentInfo1.GetRequestCode()); + EXPECT_EQ(wantAgentInfo->GetOperationType(), wantAgentInfo1.GetOperationType()); + EXPECT_EQ(wantAgentInfo->GetFlags().at(0), wantAgentInfo1.GetFlags().at(0)); + EXPECT_NE(wantAgentInfo->GetWants().at(0), wantAgentInfo1.GetWants().at(0)); + EXPECT_EQ(wantAgentInfo->GetWants().at(0)->GetElement().GetBundleName(), + wantAgentInfo1.GetWants().at(0)->GetElement().GetBundleName()); + EXPECT_EQ(wantAgentInfo->GetWants().at(0)->GetElement().GetAbilityName(), + wantAgentInfo1.GetWants().at(0)->GetElement().GetAbilityName()); + EXPECT_NE(wantAgentInfo->GetExtraInfo(), wantAgentInfo1.GetExtraInfo()); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(wantAgentInfo->GetExtraInfo()->GetParam(key))), + Boolean::Unbox(IBoolean::Query(wantAgentInfo1.GetExtraInfo()->GetParam(key)))); +} + +/* + * @tc.number : WantAgentInfo_0400 + * @tc.name : WantAgentInfo GetRequestCode + * @tc.desc : 1.GetRequestCode + */ +HWTEST_F(WantAgentInfoTest, WantAgentInfo_0400, Function | MediumTest | Level1) +{ + int requestCode = 10; + WantAgentConstant::OperationType operationType = WantAgentConstant::OperationType::START_ABILITY; + std::vector flags; + WantAgentConstant::Flags flag = WantAgentConstant::Flags::CONSTANT_FLAG; + flags.emplace_back(flag); + std::vector> wants; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + wants.emplace_back(want); + std::shared_ptr extraInfo = std::make_shared(); + bool value = true; + std::string key = "key"; + extraInfo->SetParam(key, Boolean::Box(value)); + std::shared_ptr wantAgentInfo = + std::make_shared(requestCode, operationType, flags, wants, extraInfo); + EXPECT_EQ(wantAgentInfo->GetRequestCode(), requestCode); +} + +/* + * @tc.number : WantAgentInfo_0500 + * @tc.name : WantAgentInfo GetOperationType + * @tc.desc : 1.GetOperationType + */ +HWTEST_F(WantAgentInfoTest, WantAgentInfo_0500, Function | MediumTest | Level1) +{ + int requestCode = 10; + WantAgentConstant::OperationType operationType = WantAgentConstant::OperationType::START_ABILITY; + std::vector flags; + WantAgentConstant::Flags flag = WantAgentConstant::Flags::CONSTANT_FLAG; + flags.emplace_back(flag); + std::vector> wants; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + wants.emplace_back(want); + std::shared_ptr extraInfo = std::make_shared(); + bool value = true; + std::string key = "key"; + extraInfo->SetParam(key, Boolean::Box(value)); + std::shared_ptr wantAgentInfo = + std::make_shared(requestCode, operationType, flags, wants, extraInfo); + EXPECT_EQ(wantAgentInfo->GetOperationType(), operationType); +} + +/* + * @tc.number : WantAgentInfo_0600 + * @tc.name : WantAgentInfo GetFlags + * @tc.desc : 1.GetFlags + */ +HWTEST_F(WantAgentInfoTest, WantAgentInfo_0600, Function | MediumTest | Level1) +{ + int requestCode = 10; + WantAgentConstant::OperationType operationType = WantAgentConstant::OperationType::START_ABILITY; + std::vector flags; + WantAgentConstant::Flags flag = WantAgentConstant::Flags::CONSTANT_FLAG; + flags.emplace_back(flag); + std::vector> wants; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + wants.emplace_back(want); + std::shared_ptr extraInfo = std::make_shared(); + bool value = true; + std::string key = "key"; + extraInfo->SetParam(key, Boolean::Box(value)); + std::shared_ptr wantAgentInfo = + std::make_shared(requestCode, operationType, flags, wants, extraInfo); + EXPECT_EQ(wantAgentInfo->GetFlags().at(0), flag); +} + +/* + * @tc.number : WantAgentInfo_0700 + * @tc.name : WantAgentInfo GetWants + * @tc.desc : 1.GetWants + */ +HWTEST_F(WantAgentInfoTest, WantAgentInfo_0700, Function | MediumTest | Level1) +{ + int requestCode = 10; + WantAgentConstant::OperationType operationType = WantAgentConstant::OperationType::START_ABILITY; + std::vector flags; + WantAgentConstant::Flags flag = WantAgentConstant::Flags::CONSTANT_FLAG; + flags.emplace_back(flag); + std::vector> wants; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + wants.emplace_back(want); + std::shared_ptr extraInfo = std::make_shared(); + bool value = true; + std::string key = "key"; + extraInfo->SetParam(key, Boolean::Box(value)); + std::shared_ptr wantAgentInfo = + std::make_shared(requestCode, operationType, flags, wants, extraInfo); + EXPECT_EQ(wantAgentInfo->GetWants().at(0)->GetElement().GetBundleName(), want->GetElement().GetBundleName()); + EXPECT_EQ(wantAgentInfo->GetWants().at(0)->GetElement().GetAbilityName(), want->GetElement().GetAbilityName()); +} + +/* + * @tc.number : WantAgentInfo_0800 + * @tc.name : WantAgentInfo GetWants + * @tc.desc : 1.GetWants + */ +HWTEST_F(WantAgentInfoTest, WantAgentInfo_0800, Function | MediumTest | Level1) +{ + int requestCode = 10; + WantAgentConstant::OperationType operationType = WantAgentConstant::OperationType::START_ABILITY; + std::vector flags; + WantAgentConstant::Flags flag = WantAgentConstant::Flags::CONSTANT_FLAG; + flags.emplace_back(flag); + std::vector> wants; + std::shared_ptr want = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + wants.emplace_back(want); + std::shared_ptr extraInfo = std::make_shared(); + bool value = true; + std::string key = "key"; + extraInfo->SetParam(key, Boolean::Box(value)); + std::shared_ptr wantAgentInfo = + std::make_shared(requestCode, operationType, flags, wants, extraInfo); + EXPECT_NE(wantAgentInfo->GetExtraInfo(), extraInfo); + EXPECT_EQ(Boolean::Unbox(IBoolean::Query(wantAgentInfo->GetExtraInfo()->GetParam(key))), + Boolean::Unbox(IBoolean::Query(extraInfo->GetParam(key)))); +} +} // namespace OHOS::AbilityRuntime::WantAgent \ No newline at end of file diff --git a/frameworks/kits/wantagent/test/unittest/want_agent_test/BUILD.gn b/frameworks/kits/wantagent/test/unittest/want_agent_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..9b530ec300bf56c4d9acf1fedf20b99ac1dbb597 --- /dev/null +++ b/frameworks/kits/wantagent/test/unittest/want_agent_test/BUILD.gn @@ -0,0 +1,60 @@ +# 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("//base/notification/ans_standard/notification.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +module_output_path = "ans_standard/wantagent" + +ohos_unittest("want_agent_test") { + module_out_path = module_output_path + include_dirs = [ "//foundation/aafwk/standard/services/abilitymgr/include" ] + + sources = [ "want_agent_test.cpp" ] + + configs = [ "//utils/native/base:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${core_path}:ans_core", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ces_standard:cesfwk_core", + "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + ] +} + +group("unittest") { + testonly = true + deps = [ ":want_agent_test" ] +} diff --git a/frameworks/kits/wantagent/test/unittest/want_agent_test/want_agent_test.cpp b/frameworks/kits/wantagent/test/unittest/want_agent_test/want_agent_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..627e44d5642394735261891f7c1001d0744b7443 --- /dev/null +++ b/frameworks/kits/wantagent/test/unittest/want_agent_test/want_agent_test.cpp @@ -0,0 +1,100 @@ +/* + * 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 +#include "ability_context.h" +#include "completed_callback.h" +#include "context_container.h" +#include "element_name.h" +#include "event_handler.h" +#include "ohos/aafwk/base/base_types.h" +#include "pending_want.h" +#include "want.h" +#define private public +#define protected public +#include "want_agent.h" +#undef private +#undef protected +#include "want_agent_constant.h" +#include "want_agent_helper.h" +#include "want_agent_info.h" +#include "want_params.h" +#include "want_receiver_stub.h" +#include "want_sender_stub.h" + +using namespace testing::ext; +using namespace OHOS::AAFwk; +using namespace OHOS; +using OHOS::AppExecFwk::ElementName; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime::WantAgent; +using vector_str = std::vector; + +namespace OHOS::AbilityRuntime::WantAgent { +class WantAgentTest : public testing::Test { +public: + WantAgentTest() + {} + ~WantAgentTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + class WantSender : public AAFwk::WantSenderStub { + public: + void Send(SenderInfo &senderInfo) override; + }; +}; + +void WantAgentTest::WantSender::Send(SenderInfo &senderInfo) +{} + +void WantAgentTest::SetUpTestCase(void) +{} + +void WantAgentTest::TearDownTestCase(void) +{} + +void WantAgentTest::SetUp(void) +{} + +void WantAgentTest::TearDown(void) +{} + +/* + * @tc.number : WantAgent_0100 + * @tc.name : WantAgentInfo Constructors + * @tc.desc : 1.Constructors and GetPendingWant + */ +HWTEST_F(WantAgentTest, WantAgent_0100, Function | MediumTest | Level1) +{ + std::shared_ptr wantAgent = std::make_shared(nullptr); + EXPECT_EQ(wantAgent->GetPendingWant(), nullptr); +} + +/* + * @tc.number : WantAgent_0200 + * @tc.name : WantAgentInfo Constructors + * @tc.desc : 1.Constructors and GetPendingWant + */ +HWTEST_F(WantAgentTest, WantAgent_0200, Function | MediumTest | Level1) +{ + sptr target(new (std::nothrow) WantSender()); + std::shared_ptr pendingWant = std::make_shared(target); + std::shared_ptr wantAgent = std::make_shared(pendingWant); + EXPECT_EQ(wantAgent->GetPendingWant(), pendingWant); +} +} // namespace OHOS::AbilityRuntime::WantAgent \ No newline at end of file diff --git a/interfaces/innerkits/BUILD.gn b/interfaces/innerkits/BUILD.gn index 458e8b9923e3f7e5f54e071d150ee0b6c0994f39..a88fbedebaf5f7538cf23047461c142e82142b4d 100644 --- a/interfaces/innerkits/BUILD.gn +++ b/interfaces/innerkits/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -15,9 +15,9 @@ group("innerkits_target") { deps = [ "ability_manager:ability_manager", "app_manager:app_manager", - "base:base", "dataobs_manager:dataobs_manager", "intent:intent", + "uri_permission:uri_permission_mgr", "want:want", ] } @@ -25,3 +25,11 @@ group("innerkits_target") { group("fms_innerkits_target") { deps = [ "form_manager:form_manager" ] } + +group("base_innerkits_target") { + deps = [ + "app_manager:configuration", + "base:base", + "want:want", + ] +} diff --git a/interfaces/innerkits/ability_manager/include/ability_manager_client.h b/interfaces/innerkits/ability_manager/include/ability_manager_client.h index 2fb5972561443b51ff62565ccffacaff28915f65..18471698a3e074fb8703eb5b9216effe65fbacb9 100644 --- a/interfaces/innerkits/ability_manager/include/ability_manager_client.h +++ b/interfaces/innerkits/ability_manager/include/ability_manager_client.h @@ -155,6 +155,17 @@ public: */ ErrCode TerminateAbility(const sptr &token, int resultCode, const Want *resultWant); + /** + * CloseAbility with want, return want from ability manager service. + * + * @param token Ability token. + * @param resultCode resultCode. + * @param Want Ability want returned. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode CloseAbility(const sptr &token, int resultCode = DEFAULT_INVAL_VALUE, + const Want *resultWant = nullptr); + /** * TerminateAbility, terminate the special ability. * @@ -609,11 +620,13 @@ public: /** * @brief Move a mission to front. * @param missionId Id of target mission. + * @param startOptions Special startOptions for target mission. * * @return Returns ERR_OK on success, others on failure. */ ErrCode MoveMissionToFront(int32_t missionId); - + ErrCode MoveMissionToFront(int32_t missionId, const StartOptions &startOptions); + /** * Start Ability, connect session with common ability. * @@ -749,7 +762,24 @@ public: * @return Returns ERR_OK on success, others on failure. */ ErrCode DoAbilityBackground(const sptr &token, uint32_t flag); - + + /** + * Set ability controller. + * + * @param abilityController, The ability controller. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int SetAbilityController(const sptr &abilityController, + bool imAStabilityTest); + + /** + * Send not response process ID to ability manager service. + * + * @param pid The not response process ID. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode SendANRProcessID(int pid); + private: static std::mutex mutex_; static std::shared_ptr instance_; diff --git a/interfaces/innerkits/ability_manager/include/ability_manager_errors.h b/interfaces/innerkits/ability_manager/include/ability_manager_errors.h index f2248c6d20658b72dc204f714e053e44ca5a4619..2eb031c503c3a94d65ed406ae394c59e6920aa86 100644 --- a/interfaces/innerkits/ability_manager/include/ability_manager_errors.h +++ b/interfaces/innerkits/ability_manager/include/ability_manager_errors.h @@ -375,6 +375,11 @@ enum { * Result() for start user test fail. */ START_USER_TEST_FAIL, + + /** + * Result(2097220) for send usr1 sig to the process of not response fail. + */ + SEND_USR1_SIG_FAIL, }; enum { diff --git a/interfaces/innerkits/ability_manager/include/ability_manager_interface.h b/interfaces/innerkits/ability_manager/include/ability_manager_interface.h index b741244ada4b7995ad4c4c0e89b967498a41a0e7..27823366b56b7ffb30bd21274bcb0bf8b8f73e4c 100644 --- a/interfaces/innerkits/ability_manager/include/ability_manager_interface.h +++ b/interfaces/innerkits/ability_manager/include/ability_manager_interface.h @@ -142,6 +142,17 @@ public: */ virtual int TerminateAbilityByCaller(const sptr &callerToken, int requestCode) = 0; + /** + * CloseAbility, close the special ability. + * + * @param token, the token of the ability to terminate. + * @param resultCode, the resultCode of the ability to terminate. + * @param resultWant, the Want of the ability to return. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int CloseAbility(const sptr &token, int resultCode = DEFAULT_INVAL_VALUE, + const Want *resultWant = nullptr) = 0; + /** * MinimizeAbility, minimize the special ability. * @@ -544,7 +555,7 @@ public: virtual void NotifyCompleteContinuation(const std::string &deviceId, int32_t sessionId, bool isSuccess) = 0; - virtual int NotifyContinuationResult(int32_t missionId, const int32_t result) = 0; + virtual int NotifyContinuationResult(int32_t missionId, int32_t result) = 0; virtual int LockMissionForCleanup(int32_t missionId) = 0; @@ -566,7 +577,9 @@ public: virtual int CleanAllMissions() = 0; virtual int MoveMissionToFront(int32_t missionId) = 0; - + + virtual int MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) = 0; + /** * Start Ability, connect session with common ability. * @@ -669,7 +682,7 @@ 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. * @@ -690,9 +703,11 @@ public: /** * Send not response process ID to ability manager service. + * * @param pid The not response process ID. + * @return Returns ERR_OK on success, others on failure. */ - virtual bool SendANRProcessID(int pid) = 0; + virtual int SendANRProcessID(int pid) = 0; enum { // ipc id 1-1000 for kit @@ -861,6 +876,9 @@ public: // ipc id for ability background (55) DO_ABILITY_BACKGROUND, + // ipc id for move mission to front by options (56) + MOVE_MISSION_TO_FRONT_BY_OPTIONS, + // ipc id 1001-2000 for DMS // ipc id for starting ability (1001) START_ABILITY = 1001, diff --git a/interfaces/innerkits/ability_manager/include/ability_scheduler_interface.h b/interfaces/innerkits/ability_manager/include/ability_scheduler_interface.h index 42db89b98546233e1ad4184f4b98510930be77cb..20f7359b4068da1af58686ee48cc4f91bc0086b4 100644 --- a/interfaces/innerkits/ability_manager/include/ability_scheduler_interface.h +++ b/interfaces/innerkits/ability_manager/include/ability_scheduler_interface.h @@ -151,7 +151,8 @@ public: * * @return Returns the number of data records updated. */ - virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) = 0; + 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. @@ -273,9 +274,9 @@ public: virtual std::vector> ExecuteBatch( const std::vector> &operations) = 0; virtual void ContinueAbility(const std::string& deviceId) = 0; - virtual void NotifyContinuationResult(const int32_t result) = 0; + virtual void NotifyContinuationResult(int32_t result) = 0; - virtual void DumpAbilityInfo(std::vector& info) = 0; + virtual void DumpAbilityInfo(const std::vector ¶ms, std::vector &info) = 0; virtual sptr CallRequest() = 0; diff --git a/interfaces/innerkits/ability_manager/include/global_configuration_key.h b/interfaces/innerkits/ability_manager/include/global_configuration_key.h index 35ce3f1229efc73365d73f84025f9d36dffa2e4a..30acd2ddfcfcdd15478cc474368851df5eb2c2dd 100644 --- a/interfaces/innerkits/ability_manager/include/global_configuration_key.h +++ b/interfaces/innerkits/ability_manager/include/global_configuration_key.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -22,11 +22,11 @@ namespace OHOS { namespace AAFwk { namespace GlobalConfigurationKey { /* For the time being, there is no uniform standard */ - /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!@*/ + /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!@ */ /* Must be synchronized with the keystore(SystemConfigurationKeyStore)in the configuration */ - /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ + /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ static const std::string SYSTEM_LANGUAGE {"ohos.system.language"}; - static const std::string SYSTEM_ORIENTATION {"ohos.system.orientation"}; + static const std::string SYSTEM_COLORMODE {"ohos.system.colorMode"}; } // namespace GlobalConfigurationKey } // namespace AAFwk } // namespace OHOS diff --git a/interfaces/innerkits/ability_manager/include/start_options.h b/interfaces/innerkits/ability_manager/include/start_options.h index 82fe7cd47f70d11565949bff267bab297c8fa8a7..df20f768bc01edef03cf09e1e4f94b0dba72a0a1 100644 --- a/interfaces/innerkits/ability_manager/include/start_options.h +++ b/interfaces/innerkits/ability_manager/include/start_options.h @@ -22,11 +22,15 @@ #include "parcel.h" namespace OHOS { namespace AAFwk { -class StartOptions : public Parcelable { +class StartOptions final : public Parcelable, public std::enable_shared_from_this { public: - static const std::string STRING_DISPLAY_ID; const int32_t DEFAULT_DISPLAY_ID {0}; + StartOptions() = default; + ~StartOptions() = default; + StartOptions(const StartOptions &other); + StartOptions &operator=(const StartOptions &other); + bool ReadFromParcel(Parcel &parcel); virtual bool Marshalling(Parcel &parcel) const override; static StartOptions *Unmarshalling(Parcel &parcel); diff --git a/interfaces/innerkits/app_manager/BUILD.gn b/interfaces/innerkits/app_manager/BUILD.gn index dddfd5bf055dfb93990434579c9876873098fc04..cac93b1c2041fc9a02ae1e57c1319b8a3bd9e9cb 100644 --- a/interfaces/innerkits/app_manager/BUILD.gn +++ b/interfaces/innerkits/app_manager/BUILD.gn @@ -59,8 +59,12 @@ ohos_shared_library("app_manager") { "src/appmgr/process_data.cpp", "src/appmgr/process_info.cpp", "src/appmgr/profile.cpp", + "src/appmgr/render_scheduler_host.cpp", + "src/appmgr/render_scheduler_proxy.cpp", + "src/appmgr/running_process_info.cpp", "src/appmgr/start_specified_ability_response_proxy.cpp", "src/appmgr/start_specified_ability_response_stub.cpp", + "src/appmgr/system_memory_attr.cpp", ] public_configs = [ @@ -97,3 +101,45 @@ ohos_shared_library("app_manager") { subsystem_name = "aafwk" part_name = "ability_runtime" } + +config("configuration_sdk_config") { + include_dirs = [ + "include/appmgr", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//third_party/json/include", + ] +} + +ohos_shared_library("configuration") { + include_dirs = + [ "//base/global/resmgr_standard/interfaces/innerkits/include" ] + + sources = [ + "src/appmgr/configuration.cpp", + "src/appmgr/configuration_convertor.cpp", + ] + + public_configs = [ ":configuration_sdk_config" ] + + defines = [ + "APP_LOG_TAG = \"Configuration\"", + "LOG_DOMAIN = 0xD001100", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + subsystem_name = "aafwk" + part_name = "ability_base" +} diff --git a/interfaces/innerkits/app_manager/include/appmgr/ability_controller_proxy.h b/interfaces/innerkits/app_manager/include/appmgr/ability_controller_proxy.h index 271d130f6440ca4c2c11c0c6a9309ec923e382ec..548e8e5325d0c95e7f7a07ff9a169ddcf3df0a2d 100644 --- a/interfaces/innerkits/app_manager/include/appmgr/ability_controller_proxy.h +++ b/interfaces/innerkits/app_manager/include/appmgr/ability_controller_proxy.h @@ -39,12 +39,12 @@ public: virtual bool AllowAbilityStart(const Want &want, const std::string &bundleName) override; /** - * The system is scheduling Ability to the foreground. + * The system is scheduling Ability to background. * * @param bundleName The bundleName of ability to return. - * @return Return true to allow ability to foreground, or false to reject. + * @return Return true to allow ability to background, or false to reject. */ - virtual bool AllowAbilityForeground(const std::string &bundleName) override; + virtual bool AllowAbilityBackground(const std::string &bundleName) override; private: bool WriteInterfaceToken(MessageParcel &data); diff --git a/interfaces/innerkits/app_manager/include/appmgr/ability_controller_stub.h b/interfaces/innerkits/app_manager/include/appmgr/ability_controller_stub.h index f4abe003c311eeb2ac42d0d87560af73ec06751d..87ec5105fa99da45c1c332561b664c0035ae9d97 100644 --- a/interfaces/innerkits/app_manager/include/appmgr/ability_controller_stub.h +++ b/interfaces/innerkits/app_manager/include/appmgr/ability_controller_stub.h @@ -46,17 +46,17 @@ public: virtual bool AllowAbilityStart(const Want &want, const std::string &bundleName) override; /** - * The system is scheduling Ability to the foreground. + * The system is scheduling Ability to background. * * @param bundleName The bundleName of ability to return. - * @return Return true to allow ability to foreground, or false to reject. + * @return Return true to allow ability to background, or false to reject. */ - virtual bool AllowAbilityForeground(const std::string &bundleName) override; + virtual bool AllowAbilityBackground(const std::string &bundleName) override; private: int32_t HandleAllowAbilityStart(MessageParcel &data, MessageParcel &reply); - int32_t HandleAllowAbilityForeground(MessageParcel &data, MessageParcel &reply); + int32_t HandleAllowAbilityBackground(MessageParcel &data, MessageParcel &reply); using AbilityControllerFunc = int32_t (AbilityControllerStub::*)(MessageParcel &data, MessageParcel &reply); diff --git a/interfaces/innerkits/app_manager/include/appmgr/ability_state_data.h b/interfaces/innerkits/app_manager/include/appmgr/ability_state_data.h index 742d8b09a70fbde28d4971da0074144bb777e731..2f86c997018c989efa7894e24e056631e67097e9 100644 --- a/interfaces/innerkits/app_manager/include/appmgr/ability_state_data.h +++ b/interfaces/innerkits/app_manager/include/appmgr/ability_state_data.h @@ -54,6 +54,7 @@ struct AbilityStateData : public Parcelable { pid_t pid = 0; int32_t uid = 0; sptr token; + int32_t abilityType = 0; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/app_manager/include/appmgr/ams_mgr_interface.h b/interfaces/innerkits/app_manager/include/appmgr/ams_mgr_interface.h index a61aefdfe538e91c328c26f93ea5cddff282e78b..0656a1b624323f08482faad4504f2f94f1250b9f 100644 --- a/interfaces/innerkits/app_manager/include/appmgr/ams_mgr_interface.h +++ b/interfaces/innerkits/app_manager/include/appmgr/ams_mgr_interface.h @@ -43,7 +43,8 @@ public: * @return */ virtual void LoadAbility(const sptr &token, const sptr &preToken, - const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo) = 0; + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo, + const std::shared_ptr &want) = 0; /** * TerminateAbility, call TerminateAbility() through the proxy object, terminate the token ability. diff --git a/interfaces/innerkits/app_manager/include/appmgr/ams_mgr_proxy.h b/interfaces/innerkits/app_manager/include/appmgr/ams_mgr_proxy.h index 8a58e6ef9f5d5179b3b37fed8e10ef7ffd1d2c44..ef95912b1a23909e26df8b2327ed6a486e576dc7 100644 --- a/interfaces/innerkits/app_manager/include/appmgr/ams_mgr_proxy.h +++ b/interfaces/innerkits/app_manager/include/appmgr/ams_mgr_proxy.h @@ -37,7 +37,8 @@ public: * @return */ virtual void LoadAbility(const sptr &token, const sptr &preToken, - const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo) override; + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo, + const std::shared_ptr &want) override; /** * TerminateAbility, call TerminateAbility() through the proxy object, terminate the token ability. diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_mgr_client.h b/interfaces/innerkits/app_manager/include/appmgr/app_mgr_client.h index 3ef4eb1799d26043eb0bb05361ace8bd3543f4d8..d5dc0fa3c5a4534afb24b703a11196d40fa337b3 100644 --- a/interfaces/innerkits/app_manager/include/appmgr/app_mgr_client.h +++ b/interfaces/innerkits/app_manager/include/appmgr/app_mgr_client.h @@ -25,6 +25,7 @@ #include "app_mgr_constants.h" #include "bundle_info.h" #include "iapp_state_callback.h" +#include "irender_scheduler.h" #include "running_process_info.h" #include "system_memory_attr.h" #include "istart_specified_ability_response.h" @@ -38,16 +39,8 @@ public: AppMgrClient(); virtual ~AppMgrClient(); - /** - * Load ability. - * - * @param token, Ability identify. - * @param abilityInfo, Ability information. - * @param appInfo, Application information. - * @return Returns RESULT_OK on success, others on failure. - */ virtual AppMgrResultCode LoadAbility(const sptr &token, const sptr &preToken, - const AbilityInfo &abilityInfo, const ApplicationInfo &appInfo); + const AbilityInfo &abilityInfo, const ApplicationInfo &appInfo, const AAFwk::Want &want); /** * Terminate ability. @@ -255,6 +248,34 @@ public: virtual void ScheduleAcceptWantDone(const int32_t recordId, const AAFwk::Want &want, const std::string &flag); + /** + * Get the token of ability records by process ID. + * + * @param pid The process id. + * @param tokens The token of ability records. + * @return Returns true on success, others on failure. + */ + virtual int GetAbilityRecordsByProcessID(const int pid, std::vector> &tokens); + + /** + * Start webview render process, called by webview host. + * + * @param renderParam, params passed to renderprocess. + * @param ipcFd, ipc file descriptior for web browser and render process. + * @param sharedFd, shared memory file descriptior. + * @param renderPid, created render pid. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int StartRenderProcess(const std::string &renderParam, int32_t ipcFd, + int32_t sharedFd, pid_t &renderPid); + + /** + * Render process call this to attach app manager service. + * + * @param renderScheduler, scheduler of render process. + */ + virtual void AttachRenderProcess(const sptr &renderScheduler); + private: void SetServiceManager(std::unique_ptr serviceMgr); diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_mgr_constants.h b/interfaces/innerkits/app_manager/include/appmgr/app_mgr_constants.h index 4fa3265930be53f11691574f7fc1ebbeac15efa4..37f6e5a0fbafa7df71bf50b0000cfbe5ae6296b1 100644 --- a/interfaces/innerkits/app_manager/include/appmgr/app_mgr_constants.h +++ b/interfaces/innerkits/app_manager/include/appmgr/app_mgr_constants.h @@ -41,6 +41,8 @@ enum class AbilityState { ABILITY_STATE_BACKGROUND, ABILITY_STATE_TERMINATED, ABILITY_STATE_END, + ABILITY_STATE_CONNECTED, + ABILITY_STATE_DISCONNECTED, }; enum class ExtensionState { diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_mgr_interface.h b/interfaces/innerkits/app_manager/include/appmgr/app_mgr_interface.h index 0ac19509e2ee0078bce27f4366eb15cbb2d29bea..4820032ede84d0c79798096c013d719f7c33e2c7 100644 --- a/interfaces/innerkits/app_manager/include/appmgr/app_mgr_interface.h +++ b/interfaces/innerkits/app_manager/include/appmgr/app_mgr_interface.h @@ -201,6 +201,34 @@ public: virtual void ScheduleAcceptWantDone(const int32_t recordId, const AAFwk::Want &want, const std::string &flag) = 0; + /** + * Get the token of ability records by process ID. + * + * @param pid The process id. + * @param tokens The token of ability records. + * @return Returns true on success, others on failure. + */ + virtual int GetAbilityRecordsByProcessID(const int pid, std::vector> &tokens) = 0; + + /** + * Start webview render process, called by webview host. + * + * @param renderParam, params passed to renderprocess. + * @param ipcFd, ipc file descriptior for web browser and render process. + * @param sharedFd, shared memory file descriptior. + * @param renderPid, created render pid. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int StartRenderProcess(const std::string &renderParam, int32_t ipcFd, + int32_t sharedFd, pid_t &renderPid) = 0; + + /** + * Render process call this to attach app manager service. + * + * @param renderScheduler, scheduler of render process. + */ + virtual void AttachRenderProcess(const sptr &renderScheduler) = 0; + enum class Message { APP_ATTACH_APPLICATION = 0, APP_APPLICATION_FOREGROUNDED, @@ -223,6 +251,9 @@ public: GET_FOREGROUND_APPLICATIONS, START_USER_TEST_PROCESS, SCHEDULE_ACCEPT_WANT_DONE, + APP_GET_ABILITY_RECORDS_BY_PROCESS_ID, + START_RENDER_PROCESS, + ATTACH_RENDER_PROCESS, }; }; } // namespace AppExecFwk diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_mgr_proxy.h b/interfaces/innerkits/app_manager/include/appmgr/app_mgr_proxy.h index d3db6663ef838318c7f6fec4535ae1e046b823ae..b3b4fb69a0e9da813f2bb2013f4221ec55e11063 100644 --- a/interfaces/innerkits/app_manager/include/appmgr/app_mgr_proxy.h +++ b/interfaces/innerkits/app_manager/include/appmgr/app_mgr_proxy.h @@ -193,6 +193,34 @@ public: virtual void ScheduleAcceptWantDone( const int32_t recordId, const AAFwk::Want &want, const std::string &flag) override; + + /** + * Get the token of ability records by process ID. + * + * @param pid The process id. + * @param tokens The token of ability records. + * @return Returns true on success, others on failure. + */ + virtual int GetAbilityRecordsByProcessID(const int pid, std::vector> &tokens) override; + + /** + * Start webview render process, called by webview host. + * + * @param renderParam, params passed to renderprocess. + * @param ipcFd, ipc file descriptior for web browser and render process. + * @param sharedFd, shared memory file descriptior. + * @param renderPid, created render pid. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int StartRenderProcess(const std::string &renderParam, int32_t ipcFd, + int32_t sharedFd, pid_t &renderPid) override; + + /** + * Render process call this to attach app manager service. + * + * @param renderApp, information needed to start the Application. + */ + virtual void AttachRenderProcess(const sptr &renderApp) override; private: bool SendTransactCmd(IAppMgr::Message code, MessageParcel &data, MessageParcel &reply); diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_mgr_stub.h b/interfaces/innerkits/app_manager/include/appmgr/app_mgr_stub.h index 0af16c37c815c883cf2a21a5db705d2159be2eec..b6a7dbf5214ba1e9c00bdc88b119bf23b7a4d2aa 100644 --- a/interfaces/innerkits/app_manager/include/appmgr/app_mgr_stub.h +++ b/interfaces/innerkits/app_manager/include/appmgr/app_mgr_stub.h @@ -76,6 +76,9 @@ private: int32_t HandleGetForegroundApplications(MessageParcel &data, MessageParcel &reply); int32_t HandleStartUserTestProcess(MessageParcel &data, MessageParcel &reply); int32_t HandleScheduleAcceptWantDone(MessageParcel &data, MessageParcel &reply); + int32_t HandleGetAbilityRecordsByProcessID(MessageParcel &data, MessageParcel &reply); + int32_t HandleStartRenderProcess(MessageParcel &data, MessageParcel &reply); + int32_t HandleAttachRenderProcess(MessageParcel &data, MessageParcel &reply); using AppMgrFunc = int32_t (AppMgrStub::*)(MessageParcel &data, MessageParcel &reply); std::map memberFuncMap_; diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_scheduler_interface.h b/interfaces/innerkits/app_manager/include/appmgr/app_scheduler_interface.h index 631de3d4dbfe25ff3d78423cbe03583c98a4beaa..d80f7d2166e4f86ef8a852fd159b22d04ab98bec 100644 --- a/interfaces/innerkits/app_manager/include/appmgr/app_scheduler_interface.h +++ b/interfaces/innerkits/app_manager/include/appmgr/app_scheduler_interface.h @@ -91,14 +91,8 @@ public: */ virtual void ScheduleAbilityStage(const HapModuleInfo &) = 0; - /** - * ScheduleLaunchAbility, call ScheduleLaunchAbility() through proxy project, - * Notify application to launch ability. - * - * @param The ability info. - * @return - */ - virtual void ScheduleLaunchAbility(const AbilityInfo &, const sptr &) = 0; + virtual void ScheduleLaunchAbility(const AbilityInfo &, const sptr &, + const std::shared_ptr &want) = 0; /** * ScheduleCleanAbility, call ScheduleCleanAbility() through proxy project, diff --git a/interfaces/innerkits/app_manager/include/appmgr/app_scheduler_proxy.h b/interfaces/innerkits/app_manager/include/appmgr/app_scheduler_proxy.h index de976e225cda63a87f7b3826c0e8dd7aa750fe05..74462aaadee20fd3d57525101fae0c4b9bc4ec7e 100644 --- a/interfaces/innerkits/app_manager/include/appmgr/app_scheduler_proxy.h +++ b/interfaces/innerkits/app_manager/include/appmgr/app_scheduler_proxy.h @@ -90,9 +90,12 @@ public: * Notify application to launch ability. * * @param The ability info. + * @param The ability token. + * @param The ability want. * @return */ - virtual void ScheduleLaunchAbility(const AbilityInfo &, const sptr &) override; + virtual void ScheduleLaunchAbility(const AbilityInfo &, const sptr &, + const std::shared_ptr &want) override; /** * ScheduleCleanAbility, call ScheduleCleanAbility() through proxy project, diff --git a/interfaces/innerkits/app_manager/include/appmgr/configuration.h b/interfaces/innerkits/app_manager/include/appmgr/configuration.h index 43ef49f5de5222624ada508ae38782933099b016..f166fc3bdfbe2c81c51651fd1cfb0799a479573f 100644 --- a/interfaces/innerkits/app_manager/include/appmgr/configuration.h +++ b/interfaces/innerkits/app_manager/include/appmgr/configuration.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -28,15 +28,28 @@ namespace AppExecFwk { namespace ConfigurationInner { const std::string CONNECTION_SYMBOL {"#"}; const std::string EMPTY_STRING {""}; + const std::string APPLICATION_DIRECTION {"ohos.application.direction"}; + const std::string APPLICATION_DENSITYDPI {"ohos.application.densitydpi"}; + const std::string APPLICATION_DISPLAYID {"ohos.application.displayid"}; /* * This must be synchronized with the value in GlobalConfigurationKey */ const std::vector SystemConfigurationKeyStore { OHOS::AppExecFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE, - OHOS::AppExecFwk::GlobalConfigurationKey::SYSTEM_ORIENTATION, + OHOS::AppExecFwk::GlobalConfigurationKey::SYSTEM_COLORMODE, + OHOS::AppExecFwk::ConfigurationInner::APPLICATION_DIRECTION, + OHOS::AppExecFwk::ConfigurationInner::APPLICATION_DENSITYDPI, + OHOS::AppExecFwk::ConfigurationInner::APPLICATION_DISPLAYID, }; -} + + const std::string COLOR_MODE_LIGHT {"light"}; + const std::string COLOR_MODE_DARK {"dark"}; + + const std::string DIRECTION_VERTICAL {"vertical"}; + const std::string DIRECTION_HORIZONTAL {"horizontal"}; +}; + class Configuration final: public Parcelable { public: Configuration(); diff --git a/interfaces/innerkits/app_manager/include/appmgr/configuration_convertor.h b/interfaces/innerkits/app_manager/include/appmgr/configuration_convertor.h new file mode 100644 index 0000000000000000000000000000000000000000..495972dbb2196f01bd941f4fa057a1d5debaeb65 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/configuration_convertor.h @@ -0,0 +1,39 @@ +/* + * 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_AAFWK_INTERFACES_INNERKITS_CONFIGURATION_CONVERTOR_H +#define OHOS_AAFWK_INTERFACES_INNERKITS_CONFIGURATION_CONVERTOR_H + +#include +#include "res_common.h" + +namespace OHOS::AppExecFwk { +Global::Resource::ColorMode ConvertColorMode(std::string colormode); + +Global::Resource::Direction ConvertDirection(int32_t height, int32_t width); +Global::Resource::Direction ConvertDirection(std::string direction); + +Global::Resource::ScreenDensity ConvertDensity(float density); +Global::Resource::ScreenDensity ConvertDensity(std::string density); + +int32_t ConvertDisplayId(std::string displayId); + +std::string GetColorModeStr(int32_t colormode); + +std::string GetDirectionStr(int32_t height, int32_t width); + +std::string GetDensityStr(float density); +} // namespace OHOS::AppExecFwk +#endif // OHOS_AAFWK_INTERFACES_INNERKITS_CONFIGURATION_CONVERTOR_H \ No newline at end of file diff --git a/interfaces/innerkits/app_manager/include/appmgr/global_configuration_key.h b/interfaces/innerkits/app_manager/include/appmgr/global_configuration_key.h index 2cbbf7ace4cfdf4a9ac2cc97013b59ac9794a833..3f16223bd2e400dc315b9d46b7b0c00f9b7399a6 100644 --- a/interfaces/innerkits/app_manager/include/appmgr/global_configuration_key.h +++ b/interfaces/innerkits/app_manager/include/appmgr/global_configuration_key.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -24,7 +24,7 @@ namespace GlobalConfigurationKey { /* For the time being, there is no uniform standard */ /* Must be synchronized with the keystore(SystemConfigurationKeyStore)in the configuration */ static const std::string SYSTEM_LANGUAGE {"ohos.system.language"}; - static const std::string SYSTEM_ORIENTATION {"ohos.system.orientation"}; + static const std::string SYSTEM_COLORMODE {"ohos.system.colorMode"}; } // namespace GlobalConfigurationKey } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/app_manager/include/appmgr/iability_controller.h b/interfaces/innerkits/app_manager/include/appmgr/iability_controller.h index 96d687fc0404d2b24e6841916d7a53971b3e8c10..cc1d37402453fc9150091ac6cdb26f733e3ff465 100644 --- a/interfaces/innerkits/app_manager/include/appmgr/iability_controller.h +++ b/interfaces/innerkits/app_manager/include/appmgr/iability_controller.h @@ -40,16 +40,16 @@ public: virtual bool AllowAbilityStart(const Want &want, const std::string &bundleName) = 0; /** - * The system is scheduling Ability to the foreground. + * The system is scheduling Ability to background. * * @param bundleName The bundleName of ability to return. - * @return Return true to allow ability to foreground, or false to reject. + * @return Return true to allow ability to background, or false to reject. */ - virtual bool AllowAbilityForeground(const std::string &bundleName) = 0; + virtual bool AllowAbilityBackground(const std::string &bundleName) = 0; enum class Message { TRANSACT_ON_ALLOW_ABILITY_START = 0, - TRANSACT_ON_ALLOW_ABILITY_FOREGROUND, + TRANSACT_ON_ALLOW_ABILITY_BACKGROUND, }; }; } // namespace AppExecFwk diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/clean_cache_callback_interface.h b/interfaces/innerkits/app_manager/include/appmgr/irender_scheduler.h similarity index 58% rename from services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/clean_cache_callback_interface.h rename to interfaces/innerkits/app_manager/include/appmgr/irender_scheduler.h index ffc733a9baff3128a36b76db803afa9ef88c765e..d4d7cba7c0d23dbb459d17bd16dd26f4ee9d90b2 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/clean_cache_callback_interface.h +++ b/interfaces/innerkits/app_manager/include/appmgr/irender_scheduler.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -13,28 +13,33 @@ * limitations under the License. */ -#ifndef FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_CLEAN_CACHE_CALLBACK_INTERFACE_H -#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_CLEAN_CACHE_CALLBACK_INTERFACE_H +#ifndef FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_IRENDER_SCHEDULER_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_IRENDER_SCHEDULER_H #include "iremote_broker.h" namespace OHOS { namespace AppExecFwk { -class ICleanCacheCallback : public IRemoteBroker { +/** + * @class IRenderScheduler + * Ipc interface of render process to app mgr service. + */ +class IRenderScheduler : public IRemoteBroker { public: - DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.CleanCacheCallback"); + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.RenderScheduler"); /** - * @brief Called when clean cache files progress finished. - * @param succeeded Indicates the result of the clean cache files progress. + * Notify Browser's fd to render process. + * + * @param ipcFd, ipc file descriptior for web browser and render process. + * @param sharedFd, shared memory file descriptior. */ - virtual void OnCleanCacheFinished(bool succeeded) = 0; + virtual void NotifyBrowserFd(int32_t ipcFd, int32_t sharedFd) = 0; enum class Message { - ON_CLEAN_CACHE_CALLBACK, + NOTIFY_BROWSER_FD = 1, }; }; } // namespace AppExecFwk } // namespace OHOS - -#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_CLEAN_CACHE_CALLBACK_INTERFACE_H +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_IRENDER_SCHEDULER_H diff --git a/interfaces/kits/js/app/processErrorInfo.d.ts b/interfaces/innerkits/app_manager/include/appmgr/render_scheduler_host.h old mode 100755 new mode 100644 similarity index 31% rename from interfaces/kits/js/app/processErrorInfo.d.ts rename to interfaces/innerkits/app_manager/include/appmgr/render_scheduler_host.h index f08a28f7059d9b99a46cf1c6283c098ea792df56..5b13f250e8a59bdc05fa231cee99b28d8cefea93 --- a/interfaces/kits/js/app/processErrorInfo.d.ts +++ b/interfaces/innerkits/app_manager/include/appmgr/render_scheduler_host.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -13,44 +13,39 @@ * limitations under the License. */ -import { ProcessErrCode } from '../@ohos.app.abilityManager.d.ts'; +#ifndef FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_RENDER_SCHEDULER_HOST_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_RENDER_SCHEDULER_HOST_H +#include + +#include "irender_scheduler.h" +#include "iremote_object.h" +#include "iremote_stub.h" +#include "nocopyable.h" + +namespace OHOS { +namespace AppExecFwk { /** - * @name This class saves process error information - * @since 7 - * @SysCap appexecfwk - * @import import app from 'app/processErrorInfo' - * @devices phone, tablet - * @systemapi hide this for inner system use + * @class RenderSchedulerHost + * RenderScheduler stub. */ -export interface ProcessErrorInfo { - /** - * @default Error reason, see { ProcessErrCode } in abilityManager - */ - errStatus: ProcessErrCode; - /** - * @default the name of the error process - */ - processName: string; - /** - * @default the process ID - */ - pid: number; - /** - * @default the user ID - */ - uid: number; - /** - * @default the name of the ability corresponding with the error - */ - abilityName: string; - /** - * @default the error message - */ - errMsg: string; - /** - * @default the error trace, for you to find the original error - */ - backTrace: string; -} +class RenderSchedulerHost : public IRemoteStub { +public: + RenderSchedulerHost(); + virtual ~RenderSchedulerHost(); + + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + int32_t HandleNotifyBrowserFd(MessageParcel &data, MessageParcel &reply); + + using RenderSchedulerFunc = int32_t (RenderSchedulerHost::*)(MessageParcel &data, MessageParcel &reply); + std::map memberFuncMap_; + + DISALLOW_COPY_AND_MOVE(RenderSchedulerHost); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_RENDER_SCHEDULER_HOST_H diff --git a/interfaces/innerkits/app_manager/include/appmgr/render_scheduler_proxy.h b/interfaces/innerkits/app_manager/include/appmgr/render_scheduler_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..196fe3d9d06648c3bf16bb89df9824fca3473f97 --- /dev/null +++ b/interfaces/innerkits/app_manager/include/appmgr/render_scheduler_proxy.h @@ -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. + */ + +#ifndef FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_RENDER_SCHEDULER_PROXY_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_RENDER_SCHEDULER_PROXY_H + +#include "irender_scheduler.h" + +#include "iremote_proxy.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class RenderSchedulerProxy + * RenderScheduler proxy. + */ +class RenderSchedulerProxy : public IRemoteProxy { +public: + explicit RenderSchedulerProxy(const sptr &impl); + + virtual ~RenderSchedulerProxy() = default; + + /** + * Notify Browser's fd to render process. + * + * @param ipcFd, ipc file descriptior for web browser and render process. + * @param sharedFd, shared memory file descriptior. + */ + virtual void NotifyBrowserFd(int32_t ipcFd, int32_t sharedFd) override; + +private: + bool WriteInterfaceToken(MessageParcel &data); + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_RENDER_SCHEDULER_PROXY_H diff --git a/interfaces/kits/js/app/abilityMissionInfo.d.ts b/interfaces/innerkits/app_manager/include/appmgr/running_process_info.h old mode 100755 new mode 100644 similarity index 31% rename from interfaces/kits/js/app/abilityMissionInfo.d.ts rename to interfaces/innerkits/app_manager/include/appmgr/running_process_info.h index bd219349286bc3ba180437ec60b36269cf2682d6..6691dabcc620ef9c86b8a02a0e9b2f4cdcc35b71 --- a/interfaces/kits/js/app/abilityMissionInfo.d.ts +++ b/interfaces/innerkits/app_manager/include/appmgr/running_process_info.h @@ -1,57 +1,64 @@ -/* - * 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 { ElementName } from '../bundle/elementName'; - -/** - * @name Mission information corresponding to ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @import import AbilityMissionInfo from 'app/abilityMissionInfo' - * @permission N/A - * @devices phone, tablet, tv, wearable, car - */ -export interface AbilityMissionInfo { - /** - * @default Unique identification of task stack information corresponding to ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - missionId: number; - - /** - * @default The component launched as the first ability in the task stack - * This can be considered the "application" of this task stack - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - bottomAbility: ElementName; - - /** - * @default The ability component at the top of the history stack of the task - * This is what the user is currently doing - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - topAbility: ElementName; - - /** - * @default The corresponding ability description information in the task stack - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - windowMode: number; -} - +/* + * 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_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_RUNNING_PROCESS_INFO_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_RUNNING_PROCESS_INFO_H + +#include +#include + +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +enum class AppProcessState { + APP_STATE_BEGIN = 0, + APP_STATE_CREATE = APP_STATE_BEGIN, + APP_STATE_READY, + APP_STATE_FOREGROUND, + APP_STATE_BACKGROUND, + APP_STATE_SUSPENDED, + APP_STATE_TERMINATED, + APP_STATE_END, +}; + +enum class WeightReasonCode { + REASON_UNKNOWN = 0, + WEIGHT_FOREGROUND = 100, + WEIGHT_FOREGROUND_SERVICE = 125, + WEIGHT_VISIBLE = 200, + WEIGHT_PERCEPTIBLE = 230, + WEIGHT_SERVICE = 300, + WEIGHT_TOP_SLEEPING = 325, + WEIGHT_CANT_SAVE_STATE = 350, + WEIGHT_CACHED = 400, + WEIGHT_GONE = 1000, +}; + +struct RunningProcessInfo : public Parcelable { + std::string processName_; + std::int32_t pid_; + std::int32_t uid_; + AppProcessState state_; + std::vector bundleNames; + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static RunningProcessInfo *Unmarshalling(Parcel &parcel); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_RUNNING_PROCESS_INFO_H diff --git a/interfaces/kits/js/app/systemMemoryAttr.d.ts b/interfaces/innerkits/app_manager/include/appmgr/system_memory_attr.h old mode 100755 new mode 100644 similarity index 53% rename from interfaces/kits/js/app/systemMemoryAttr.d.ts rename to interfaces/innerkits/app_manager/include/appmgr/system_memory_attr.h index eee6e70681a11dd33bf5cba1093fba6ae02d16df..48b5322e5bd1f1a284b516412437dcaf0e83e57e --- a/interfaces/kits/js/app/systemMemoryAttr.d.ts +++ b/interfaces/innerkits/app_manager/include/appmgr/system_memory_attr.h @@ -1,44 +1,58 @@ -/* - * 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. - */ - -/** - * @name This class saves system memory attributes - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @import import MemoryMapInfo from 'app/systemMemoryAttr' - * @devices phone, tablet, tv, wearable, car - * @systemapi hide this for inner system use - */ - export interface SystemMemoryAttr { - /** - * @default The available memory on the system - */ - availSysMem: number; - /** - * @default The total memory on the system - */ - totalSysMem: number; - /** - * @default The low memory threshold under which the system - * will kill background processes - */ - threshold: number; - /** - * @default Whether the system is in low memory status - */ - isSysInlowMem: boolean; -} - - +/* + * 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 OHOS_AAFWK_INTERFACES_INNERKITS_SYSTEM_MEMORY_ATTR_H +#define OHOS_AAFWK_INTERFACES_INNERKITS_SYSTEM_MEMORY_ATTR_H + +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class SystemMemoryAttr + * SystemMemoryAttr is used to query system memory info. + */ +class SystemMemoryAttr : public Parcelable { +public: + SystemMemoryAttr(); + virtual ~SystemMemoryAttr() = default; + /** + * @default The available memory on the system + */ + int64_t availSysMem_; + + /** + * @default The total memory on the system + */ + int64_t totalSysMem_; + + /** + * @default The low memory threshold under which the system + * will kill background processes + */ + int64_t threshold_; + + /** + * @default Whether the system is in low memory status + */ + bool isSysInlowMem_; + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static SystemMemoryAttr *Unmarshalling(Parcel &parcel); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_AAFWK_INTERFACES_INNERKITS_SYSTEM_MEMORY_ATTR_H \ No newline at end of file diff --git a/interfaces/innerkits/app_manager/src/appmgr/ability_controller_proxy.cpp b/interfaces/innerkits/app_manager/src/appmgr/ability_controller_proxy.cpp index 303c1890afb000fdbe3260f8c275f1ed5505d6e6..d868ab3a60faddda42ece5da88a522cd393a8cf9 100644 --- a/interfaces/innerkits/app_manager/src/appmgr/ability_controller_proxy.cpp +++ b/interfaces/innerkits/app_manager/src/appmgr/ability_controller_proxy.cpp @@ -58,7 +58,7 @@ bool AbilityControllerProxy::AllowAbilityStart(const Want &want, const std::stri return reply.ReadBool(); } -bool AbilityControllerProxy::AllowAbilityForeground(const std::string &bundleName) +bool AbilityControllerProxy::AllowAbilityBackground(const std::string &bundleName) { MessageParcel data; MessageParcel reply; @@ -73,7 +73,7 @@ bool AbilityControllerProxy::AllowAbilityForeground(const std::string &bundleNam return true; } int32_t ret = remote->SendRequest( - static_cast(IAbilityController::Message::TRANSACT_ON_ALLOW_ABILITY_FOREGROUND), + static_cast(IAbilityController::Message::TRANSACT_ON_ALLOW_ABILITY_BACKGROUND), data, reply, option); if (ret != NO_ERROR) { APP_LOGW("SendRequest is failed, error code: %{public}d", ret); diff --git a/interfaces/innerkits/app_manager/src/appmgr/ability_controller_stub.cpp b/interfaces/innerkits/app_manager/src/appmgr/ability_controller_stub.cpp index c5705d3bd0927dafd3d7a8fd6e2a7066fc510adb..a3cdfd92c5b4b5d3fd293077ea25423d64efdfda 100644 --- a/interfaces/innerkits/app_manager/src/appmgr/ability_controller_stub.cpp +++ b/interfaces/innerkits/app_manager/src/appmgr/ability_controller_stub.cpp @@ -27,8 +27,8 @@ AbilityControllerStub::AbilityControllerStub() IAbilityController::Message::TRANSACT_ON_ALLOW_ABILITY_START)] = &AbilityControllerStub::HandleAllowAbilityStart; memberFuncMap_[static_cast( - IAbilityController::Message::TRANSACT_ON_ALLOW_ABILITY_FOREGROUND)] = - &AbilityControllerStub::HandleAllowAbilityForeground; + IAbilityController::Message::TRANSACT_ON_ALLOW_ABILITY_BACKGROUND)] = + &AbilityControllerStub::HandleAllowAbilityBackground; } AbilityControllerStub::~AbilityControllerStub() @@ -62,7 +62,7 @@ bool AbilityControllerStub::AllowAbilityStart(const Want &want, const std::strin return true; } -bool AbilityControllerStub::AllowAbilityForeground(const std::string &bundleName) +bool AbilityControllerStub::AllowAbilityBackground(const std::string &bundleName) { return true; } @@ -81,11 +81,11 @@ int32_t AbilityControllerStub::HandleAllowAbilityStart(MessageParcel &data, Mess return NO_ERROR; } -int32_t AbilityControllerStub::HandleAllowAbilityForeground(MessageParcel &data, MessageParcel &reply) +int32_t AbilityControllerStub::HandleAllowAbilityBackground(MessageParcel &data, MessageParcel &reply) { - APP_LOGI("HandleAllowAbilityForeground"); + APP_LOGI("HandleAllowAbilityBackground"); std::string pkg = data.ReadString(); - bool ret = AllowAbilityForeground(pkg); + bool ret = AllowAbilityBackground(pkg); reply.WriteBool(ret); return NO_ERROR; } diff --git a/interfaces/innerkits/app_manager/src/appmgr/ability_state_data.cpp b/interfaces/innerkits/app_manager/src/appmgr/ability_state_data.cpp index 5dd13b6e2d695796fbe95b7a3cab6ad86e71418b..8741a02d71fc18b27e6b4aa7598db933a878e765 100644 --- a/interfaces/innerkits/app_manager/src/appmgr/ability_state_data.cpp +++ b/interfaces/innerkits/app_manager/src/appmgr/ability_state_data.cpp @@ -22,8 +22,8 @@ namespace AppExecFwk { bool AbilityStateData::Marshalling(Parcel &parcel) const { return (parcel.WriteString(bundleName) && parcel.WriteString(abilityName) && - parcel.WriteInt32(abilityState) && - parcel.WriteInt32(pid) && parcel.WriteInt32(uid) && parcel.WriteParcelable(token)); + parcel.WriteInt32(abilityState) && parcel.WriteInt32(pid) && + parcel.WriteInt32(uid) && parcel.WriteParcelable(token) && parcel.WriteInt32(abilityType)); } bool AbilityStateData::ReadFromParcel(Parcel &parcel) @@ -40,6 +40,7 @@ bool AbilityStateData::ReadFromParcel(Parcel &parcel) token = parcel.ReadParcelable(); + abilityType = parcel.ReadInt32(); return true; } diff --git a/interfaces/innerkits/app_manager/src/appmgr/ams_mgr_proxy.cpp b/interfaces/innerkits/app_manager/src/appmgr/ams_mgr_proxy.cpp index effa2e7d6798bc3c295847e861a934c079e5bec5..d1b349653f5b1691c0ab686c3d20f310cb7fc3f0 100644 --- a/interfaces/innerkits/app_manager/src/appmgr/ams_mgr_proxy.cpp +++ b/interfaces/innerkits/app_manager/src/appmgr/ams_mgr_proxy.cpp @@ -36,7 +36,8 @@ bool AmsMgrProxy::WriteInterfaceToken(MessageParcel &data) } void AmsMgrProxy::LoadAbility(const sptr &token, const sptr &preToken, - const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo) + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo, + const std::shared_ptr &want) { APP_LOGD("start"); if (!abilityInfo || !appInfo) { @@ -54,6 +55,10 @@ void AmsMgrProxy::LoadAbility(const sptr &token, const sptr remote = Remote(); if (remote == nullptr) { APP_LOGE("Remote() is NULL"); diff --git a/interfaces/innerkits/app_manager/src/appmgr/ams_mgr_stub.cpp b/interfaces/innerkits/app_manager/src/appmgr/ams_mgr_stub.cpp index b9ad246fa302f2ffaf435b54787a652025164f73..eb7e502a84410a65efdeb1a457493561726f0c6d 100644 --- a/interfaces/innerkits/app_manager/src/appmgr/ams_mgr_stub.cpp +++ b/interfaces/innerkits/app_manager/src/appmgr/ams_mgr_stub.cpp @@ -112,7 +112,13 @@ ErrCode AmsMgrStub::HandleLoadAbility(MessageParcel &data, MessageParcel &reply) return ERR_APPEXECFWK_PARCEL_ERROR; } - LoadAbility(token, preToke, abilityInfo, appInfo); + std::shared_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("ReadParcelable want failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + LoadAbility(token, preToke, abilityInfo, appInfo, want); return NO_ERROR; } diff --git a/interfaces/innerkits/app_manager/src/appmgr/app_mgr_client.cpp b/interfaces/innerkits/app_manager/src/appmgr/app_mgr_client.cpp index a19edea671213bc2611ada0e3d3295ec609d5c44..69c441f0aac786fc7b8e9fbe611f4a8eca8faf87 100644 --- a/interfaces/innerkits/app_manager/src/appmgr/app_mgr_client.cpp +++ b/interfaces/innerkits/app_manager/src/appmgr/app_mgr_client.cpp @@ -37,7 +37,7 @@ AppMgrClient::~AppMgrClient() {} AppMgrResultCode AppMgrClient::LoadAbility(const sptr &token, const sptr &preToken, - const AbilityInfo &abilityInfo, const ApplicationInfo &appInfo) + const AbilityInfo &abilityInfo, const ApplicationInfo &appInfo, const AAFwk::Want &want) { sptr service = iface_cast(remote_); if (service != nullptr) { @@ -46,7 +46,8 @@ AppMgrResultCode AppMgrClient::LoadAbility(const sptr &token, con // From here, separate AbilityInfo and ApplicationInfo from AA. std::shared_ptr abilityInfoPtr = std::make_shared(abilityInfo); std::shared_ptr appInfoPtr = std::make_shared(appInfo); - amsService->LoadAbility(token, preToken, abilityInfoPtr, appInfoPtr); + std::shared_ptr wantPtr = std::make_shared(want); + amsService->LoadAbility(token, preToken, abilityInfoPtr, appInfoPtr, wantPtr); return AppMgrResultCode::RESULT_OK; } } @@ -435,5 +436,48 @@ AppMgrResultCode AppMgrClient::UpdateConfiguration(const Configuration &config) amsService->UpdateConfiguration(config); return AppMgrResultCode::RESULT_OK; } + +int AppMgrClient::GetAbilityRecordsByProcessID(const int pid, std::vector> &tokens) +{ + sptr service = iface_cast(remote_); + if (service == nullptr) { + APP_LOGE("service is nullptr"); + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; + } + + return service->GetAbilityRecordsByProcessID(pid, tokens); +} + +int AppMgrClient::StartRenderProcess(const std::string &renderParam, int32_t ipcFd, + int32_t sharedFd, pid_t &renderPid) +{ + if (!remote_) { + ConnectAppMgrService(); + } + + sptr service = iface_cast(remote_); + if (service != nullptr) { + return service->StartRenderProcess(renderParam, ipcFd, sharedFd, renderPid); + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + +void AppMgrClient::AttachRenderProcess(const sptr &renderScheduler) +{ + if (!renderScheduler) { + APP_LOGI("renderScheduler is nullptr"); + return; + } + + if (!remote_) { + ConnectAppMgrService(); + } + + sptr service = iface_cast(remote_); + if (service != nullptr) { + APP_LOGI("AttachRenderProcess"); + service->AttachRenderProcess(renderScheduler->AsObject()); + } +} } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/app_mgr_proxy.cpp b/interfaces/innerkits/app_manager/src/appmgr/app_mgr_proxy.cpp index ac1495cd26018fc0f49743f230bd210167da9b79..9ab3d4af95accc9e78386f9223dfcc469dbfd170 100644 --- a/interfaces/innerkits/app_manager/src/appmgr/app_mgr_proxy.cpp +++ b/interfaces/innerkits/app_manager/src/appmgr/app_mgr_proxy.cpp @@ -584,5 +584,94 @@ void AppMgrProxy::ScheduleAcceptWantDone(const int32_t recordId, const AAFwk::Wa return; } } + +int AppMgrProxy::GetAbilityRecordsByProcessID(const int pid, std::vector> &tokens) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + + data.WriteInt32(pid); + if (!WriteInterfaceToken(data)) { + return ERR_FLATTEN_OBJECT; + } + if (!SendTransactCmd(IAppMgr::Message::APP_GET_ABILITY_RECORDS_BY_PROCESS_ID, data, reply)) { + return ERR_NULL_OBJECT; + } + int32_t infoSize = reply.ReadInt32(); + for (int32_t i = 0; i < infoSize; i++) { + auto iRemote = reply.ReadRemoteObject(); + tokens.emplace_back(iRemote); + } + return reply.ReadInt32(); +} + +int AppMgrProxy::StartRenderProcess(const std::string &renderParam, int32_t ipcFd, + int32_t sharedFd, pid_t &renderPid) +{ + if (renderParam.empty() || ipcFd <= 0 || sharedFd <= 0) { + APP_LOGE("Invalid params, renderParam:%{public}s, ipcFd:%{public}d, sharedFd:%{public}d", + renderParam.c_str(), ipcFd, sharedFd); + return -1; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + APP_LOGE("WriteInterfaceToken faild"); + return ERR_FLATTEN_OBJECT; + } + + if (!data.WriteString(renderParam)) { + APP_LOGE("want paramSize failed."); + return -1; + } + + if (!data.WriteFileDescriptor(ipcFd) || !data.WriteFileDescriptor(sharedFd)) { + APP_LOGE("want fd failed, ipcFd:%{public}d, sharedFd:%{public}d", ipcFd, sharedFd); + return -1; + } + + int32_t ret = + Remote()->SendRequest(static_cast(IAppMgr::Message::START_RENDER_PROCESS), data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("StartRenderProcess SendRequest is failed, error code: %{public}d", ret); + return ret; + } + + auto result = reply.ReadInt32(); + renderPid = reply.ReadInt32(); + if (result != 0) { + APP_LOGW("StartRenderProcess failed, result: %{public}d", ret); + return ret; + } + return 0; +} + +void AppMgrProxy::AttachRenderProcess(const sptr &renderScheduler) +{ + if (!renderScheduler) { + APP_LOGE("renderScheduler is null"); + return; + } + + APP_LOGD("AttachRenderProcess start"); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + return; + } + if (!data.WriteParcelable(renderScheduler)) { + APP_LOGE("renderScheduler write failed."); + return; + } + + if (!SendTransactCmd(IAppMgr::Message::ATTACH_RENDER_PROCESS, data, reply)) { + APP_LOGE("SendTransactCmd ATTACH_RENDER_PROCESS faild"); + return; + } +} } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/app_mgr_stub.cpp b/interfaces/innerkits/app_manager/src/appmgr/app_mgr_stub.cpp index cba183d4fc7c3aa74f38820b3861ca854f222636..61bacadb85254477b9d1b3987b4ddfdb3dfb7fc3 100644 --- a/interfaces/innerkits/app_manager/src/appmgr/app_mgr_stub.cpp +++ b/interfaces/innerkits/app_manager/src/appmgr/app_mgr_stub.cpp @@ -74,6 +74,12 @@ AppMgrStub::AppMgrStub() &AppMgrStub::HandleStartUserTestProcess; memberFuncMap_[static_cast(IAppMgr::Message::SCHEDULE_ACCEPT_WANT_DONE)] = &AppMgrStub::HandleScheduleAcceptWantDone; + memberFuncMap_[static_cast(IAppMgr::Message::APP_GET_ABILITY_RECORDS_BY_PROCESS_ID)] = + &AppMgrStub::HandleGetAbilityRecordsByProcessID; + memberFuncMap_[static_cast(IAppMgr::Message::START_RENDER_PROCESS)] = + &AppMgrStub::HandleStartRenderProcess; + memberFuncMap_[static_cast(IAppMgr::Message::ATTACH_RENDER_PROCESS)] = + &AppMgrStub::HandleAttachRenderProcess; } AppMgrStub::~AppMgrStub() @@ -342,5 +348,49 @@ int32_t AppMgrStub::HandleScheduleAcceptWantDone(MessageParcel &data, MessagePar ScheduleAcceptWantDone(recordId, *want, flag); return NO_ERROR; } + +int32_t AppMgrStub::HandleGetAbilityRecordsByProcessID(MessageParcel &data, MessageParcel &reply) +{ + BYTRACE(BYTRACE_TAG_APP); + int32_t pid = data.ReadInt32(); + std::vector> tokens; + auto result = GetAbilityRecordsByProcessID(pid, tokens); + reply.WriteInt32(tokens.size()); + for (auto &it : tokens) { + if (!reply.WriteRemoteObject(it)) { + APP_LOGE("failed to write query result."); + return ERR_FLATTEN_OBJECT; + } + } + if (!reply.WriteInt32(result)) { + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +int32_t AppMgrStub::HandleStartRenderProcess(MessageParcel &data, MessageParcel &reply) +{ + std::string renderParam = data.ReadString(); + int32_t ipcFd = data.ReadFileDescriptor(); + int32_t sharedFd = data.ReadFileDescriptor(); + int32_t renderPid = 0; + int32_t result = StartRenderProcess(renderParam, ipcFd, sharedFd, renderPid); + if (!reply.WriteInt32(result)) { + APP_LOGE("write result error."); + return ERR_INVALID_VALUE; + } + if (!reply.WriteInt32(renderPid)) { + APP_LOGE("write renderPid error."); + return ERR_INVALID_VALUE; + } + return result; +} + +int32_t AppMgrStub::HandleAttachRenderProcess(MessageParcel &data, MessageParcel &reply) +{ + sptr scheduler = data.ReadParcelable(); + AttachRenderProcess(scheduler); + return NO_ERROR; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/app_scheduler_host.cpp b/interfaces/innerkits/app_manager/src/appmgr/app_scheduler_host.cpp index c5bcd6989b789f109092e2e1b75a7fcc814afd1b..a9213ed3a1b50769aeec4aa0d0de40d8cdbfe84f 100644 --- a/interfaces/innerkits/app_manager/src/appmgr/app_scheduler_host.cpp +++ b/interfaces/innerkits/app_manager/src/appmgr/app_scheduler_host.cpp @@ -122,7 +122,8 @@ int32_t AppSchedulerHost::HandleScheduleLaunchAbility(MessageParcel &data, Messa } sptr token = data.ReadParcelable(); - ScheduleLaunchAbility(*abilityInfo, token); + std::shared_ptr want(data.ReadParcelable()); + ScheduleLaunchAbility(*abilityInfo, token, want); return NO_ERROR; } diff --git a/interfaces/innerkits/app_manager/src/appmgr/app_scheduler_proxy.cpp b/interfaces/innerkits/app_manager/src/appmgr/app_scheduler_proxy.cpp index 30f1b86ea73555958e4f7e567fd17a556e115aeb..14ec6655388d7c190ec4bc4a9e7004b9e4824abc 100644 --- a/interfaces/innerkits/app_manager/src/appmgr/app_scheduler_proxy.cpp +++ b/interfaces/innerkits/app_manager/src/appmgr/app_scheduler_proxy.cpp @@ -143,7 +143,8 @@ void AppSchedulerProxy::ScheduleShrinkMemory(const int32_t level) } } -void AppSchedulerProxy::ScheduleLaunchAbility(const AbilityInfo &info, const sptr &token) +void AppSchedulerProxy::ScheduleLaunchAbility(const AbilityInfo &info, const sptr &token, + const std::shared_ptr &want) { MessageParcel data; MessageParcel reply; @@ -153,6 +154,10 @@ void AppSchedulerProxy::ScheduleLaunchAbility(const AbilityInfo &info, const spt } data.WriteParcelable(&info); data.WriteParcelable(token.GetRefPtr()); + if (!data.WriteParcelable(want.get())) { + APP_LOGE("write want fail."); + return; + } sptr remote = Remote(); if (remote == nullptr) { APP_LOGE("Remote() is NULL"); diff --git a/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp b/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp index 85b24de01b3265375cd9c3f38ae671930de67da1..b6b96e4e2550255026caa1f304012c32a2b598ef 100755 --- a/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp +++ b/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp @@ -208,9 +208,20 @@ bool Configuration::ReadFromParcel(Parcel &parcel) std::vector values; keys.clear(); values.clear(); - parcel.ReadStringVector(&keys); - parcel.ReadStringVector(&values); - + if (!parcel.ReadStringVector(&keys)) { + APP_LOGE("ReadStringVector for keys failed."); + return false; + } + if (!parcel.ReadStringVector(&values)) { + APP_LOGE("ReadStringVector for values failed."); + return false; + } + int32_t keySize = keys.size(); + int32_t valueSize = values.size(); + if (keySize != valueSize || configSize != valueSize) { + APP_LOGE("ReadFromParcel failed, invalid size."); + return false; + } std::string key; std::string val; for (int32_t i = 0; i < configSize; i++) { diff --git a/interfaces/innerkits/app_manager/src/appmgr/configuration_convertor.cpp b/interfaces/innerkits/app_manager/src/appmgr/configuration_convertor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5468a9016ba5ab76642fa1e544b98ed26f9103e3 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/configuration_convertor.cpp @@ -0,0 +1,189 @@ +/* + * 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 "configuration_convertor.h" + +#include "configuration.h" + +namespace OHOS::AppExecFwk { +constexpr float DPI_BASE = 160.0; + +Global::Resource::ColorMode ConvertColorMode(std::string colormode) +{ + auto resolution = Global::Resource::ColorMode::COLOR_MODE_NOT_SET; + + static const std::vector> resolutions = { + { "dark", Global::Resource::ColorMode::DARK }, + { "light", Global::Resource::ColorMode::LIGHT }, + }; + + for (const auto& [tempColorMode, value] : resolutions) { + if (tempColorMode == colormode) { + resolution = value; + break; + } + } + + return resolution; +} + +Global::Resource::Direction ConvertDirection(int32_t height, int32_t width) +{ + return height >= width ? Global::Resource::Direction::DIRECTION_VERTICAL : + Global::Resource::Direction::DIRECTION_HORIZONTAL; +} + +Global::Resource::Direction ConvertDirection(std::string direction) +{ + auto resolution = Global::Resource::Direction::DIRECTION_NOT_SET; + + static const std::vector> resolutions = { + { "vertical", Global::Resource::Direction::DIRECTION_VERTICAL }, + { "horizontal", Global::Resource::Direction::DIRECTION_HORIZONTAL }, + }; + + for (const auto& [tempDirection, value] : resolutions) { + if (tempDirection == direction) { + resolution = value; + break; + } + } + + return resolution; +} + +Global::Resource::ScreenDensity ConvertDensity(float density) +{ + static const std::vector> resolutions = { + { 0.0, Global::Resource::ScreenDensity::SCREEN_DENSITY_NOT_SET }, + { 120.0, Global::Resource::ScreenDensity::SCREEN_DENSITY_SDPI }, + { 160.0, Global::Resource::ScreenDensity::SCREEN_DENSITY_MDPI }, + { 240.0, Global::Resource::ScreenDensity::SCREEN_DENSITY_LDPI }, + { 320.0, Global::Resource::ScreenDensity::SCREEN_DENSITY_XLDPI }, + { 480.0, Global::Resource::ScreenDensity::SCREEN_DENSITY_XXLDPI }, + { 640.0, Global::Resource::ScreenDensity::SCREEN_DENSITY_XXXLDPI }, + }; + + float deviceDpi = density * DPI_BASE; + auto resolution = Global::Resource::ScreenDensity::SCREEN_DENSITY_NOT_SET; + for (const auto& [dpi, value] : resolutions) { + resolution = value; + if (deviceDpi <= dpi) { + break; + } + } + return resolution; +} + +Global::Resource::ScreenDensity ConvertDensity(std::string density) +{ + auto resolution = Global::Resource::ScreenDensity::SCREEN_DENSITY_NOT_SET; + + static const std::vector> resolutions = { + { "sdpi", Global::Resource::ScreenDensity::SCREEN_DENSITY_SDPI }, + { "mdpi", Global::Resource::ScreenDensity::SCREEN_DENSITY_MDPI }, + { "ldpi", Global::Resource::ScreenDensity::SCREEN_DENSITY_LDPI }, + { "xldpi", Global::Resource::ScreenDensity::SCREEN_DENSITY_XLDPI }, + { "xxldpi", Global::Resource::ScreenDensity::SCREEN_DENSITY_XXLDPI }, + { "xxxldpi", Global::Resource::ScreenDensity::SCREEN_DENSITY_XXXLDPI }, + }; + + for (const auto& [tempdensity, value] : resolutions) { + if (tempdensity == density) { + resolution = value; + break; + } + } + + return resolution; +} + +int32_t ConvertDisplayId(std::string displayId) +{ + if (displayId == ConfigurationInner::EMPTY_STRING) { + return -1; + } + + return std::stoi(displayId); +} + +std::string GetColorModeStr(int32_t colormode) +{ + std::string ret("no_color_mode"); + + switch (colormode) { + case Global::Resource::ColorMode::DARK: + ret = ConfigurationInner::COLOR_MODE_DARK; + break; + case Global::Resource::ColorMode::LIGHT: + ret = ConfigurationInner::COLOR_MODE_LIGHT; + break; + default: + break; + } + + return ret; +} + +std::string GetDirectionStr(Global::Resource::Direction direction) +{ + std::string ret("no_direction"); + + switch (direction) { + case Global::Resource::Direction::DIRECTION_VERTICAL: + ret = ConfigurationInner::DIRECTION_VERTICAL; + break; + case Global::Resource::Direction::DIRECTION_HORIZONTAL: + ret = ConfigurationInner::DIRECTION_HORIZONTAL; + break; + default: + break; + } + + return ret; +} + +std::string GetDirectionStr(int32_t height, int32_t width) +{ + return GetDirectionStr(ConvertDirection(height, width)); +} + +std::string GetDensityStr(Global::Resource::ScreenDensity density) +{ + std::string ret("no_screen_density"); + + static const std::vector> resolutions = { + { Global::Resource::ScreenDensity::SCREEN_DENSITY_SDPI, "sdpi" }, + { Global::Resource::ScreenDensity::SCREEN_DENSITY_MDPI, "mdpi" }, + { Global::Resource::ScreenDensity::SCREEN_DENSITY_LDPI, "ldpi" }, + { Global::Resource::ScreenDensity::SCREEN_DENSITY_XLDPI, "xldpi" }, + { Global::Resource::ScreenDensity::SCREEN_DENSITY_XXLDPI, "xxldpi" }, + { Global::Resource::ScreenDensity::SCREEN_DENSITY_XXXLDPI, "xxxldpi" }, + }; + + for (const auto& [dpi, value] : resolutions) { + if (dpi == density) { + return value; + } + } + + return ret; +} + +std::string GetDensityStr(float density) +{ + return GetDensityStr(ConvertDensity(density)); +} +} // namespace OHOS::AppExecFwk \ No newline at end of file diff --git a/interfaces/innerkits/app_manager/src/appmgr/render_scheduler_host.cpp b/interfaces/innerkits/app_manager/src/appmgr/render_scheduler_host.cpp new file mode 100644 index 0000000000000000000000000000000000000000..91a2db26d845aa4966508277fab5f0592da0392b --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/render_scheduler_host.cpp @@ -0,0 +1,63 @@ +/* + * 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 "render_scheduler_host.h" + +#include "app_log_wrapper.h" +#include "ipc_types.h" + +namespace OHOS { +namespace AppExecFwk { +RenderSchedulerHost::RenderSchedulerHost() +{ + memberFuncMap_[static_cast(IRenderScheduler::Message::NOTIFY_BROWSER_FD)] = + &RenderSchedulerHost::HandleNotifyBrowserFd; +} + +RenderSchedulerHost::~RenderSchedulerHost() +{ + memberFuncMap_.clear(); +} + +int RenderSchedulerHost::OnRemoteRequest(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + APP_LOGI("RenderSchedulerHost::OnReceived, code = %{public}d, flags= %{public}d.", code, option.GetFlags()); + std::u16string descriptor = RenderSchedulerHost::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGE("local descriptor is not equal to remote"); + return ERR_INVALID_STATE; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data, reply); + } + } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +int RenderSchedulerHost::HandleNotifyBrowserFd(MessageParcel &data, MessageParcel &reply) +{ + int32_t ipcFd = data.ReadFileDescriptor(); + int32_t sharedFd = data.ReadFileDescriptor(); + NotifyBrowserFd(ipcFd, sharedFd); + return 0; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/render_scheduler_proxy.cpp b/interfaces/innerkits/app_manager/src/appmgr/render_scheduler_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e409655b648f9b964c9333fec3ad12231413dd99 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/render_scheduler_proxy.cpp @@ -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. + */ + +#include "render_scheduler_proxy.h" + +#include "ipc_types.h" + +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +RenderSchedulerProxy::RenderSchedulerProxy( + const sptr &impl) : IRemoteProxy(impl) +{} + +bool RenderSchedulerProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(RenderSchedulerProxy::GetDescriptor())) { + APP_LOGE("write interface token failed"); + return false; + } + return true; +} + +void RenderSchedulerProxy::NotifyBrowserFd(int32_t ipcFd, int32_t sharedFd) +{ + APP_LOGD("NotifyBrowserFd start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!WriteInterfaceToken(data)) { + return; + } + + if (!data.WriteFileDescriptor(ipcFd) || !data.WriteFileDescriptor(sharedFd)) { + APP_LOGE("want fd failed, ipcFd:%{public}d, sharedFd:%{public}d", ipcFd, sharedFd); + return; + } + + sptr remote = Remote(); + if (remote == nullptr) { + APP_LOGE("Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + static_cast(IRenderScheduler::Message::NOTIFY_BROWSER_FD), + data, reply, option); + if (ret != NO_ERROR) { + APP_LOGW("SendRequest is failed, error code: %{public}d", ret); + } + APP_LOGD("NotifyBrowserFd end"); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/running_process_info.cpp b/interfaces/innerkits/app_manager/src/appmgr/running_process_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..880717e582df740579bd5c38930bf1e64c2ce792 --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/running_process_info.cpp @@ -0,0 +1,67 @@ +/* + * 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 "running_process_info.h" + +#include "nlohmann/json.hpp" +#include "string_ex.h" + +#include "app_log_wrapper.h" +#include "parcel_macro.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const std::string JSON_KEY_PROCESSNAME = "processName"; +const std::string JSON_KEY_PID = "pid"; +const std::string JSON_KEY_STATE = "state"; +} // namespace + +bool RunningProcessInfo::ReadFromParcel(Parcel &parcel) +{ + processName_ = Str16ToStr8(parcel.ReadString16()); + int32_t typeData; + READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, typeData); + pid_ = static_cast(typeData); + int32_t uidData; + READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, uidData); + uid_ = static_cast(uidData); + int32_t stateData; + READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, stateData); + state_ = static_cast(stateData); + return true; +} + +RunningProcessInfo *RunningProcessInfo::Unmarshalling(Parcel &parcel) +{ + RunningProcessInfo *info = new (std::nothrow) RunningProcessInfo(); + if (info && !info->ReadFromParcel(parcel)) { + APP_LOGW("read from parcel failed"); + delete info; + info = nullptr; + } + return info; +} + +bool RunningProcessInfo::Marshalling(Parcel &parcel) const +{ + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(processName_)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, static_cast(pid_)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, static_cast(uid_)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, static_cast(state_)); + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/app_manager/src/appmgr/system_memory_attr.cpp b/interfaces/innerkits/app_manager/src/appmgr/system_memory_attr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d098170ca9bf6b9f6d4dcaf203202fe4b605072b --- /dev/null +++ b/interfaces/innerkits/app_manager/src/appmgr/system_memory_attr.cpp @@ -0,0 +1,70 @@ +/* + * 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 "system_memory_attr.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +SystemMemoryAttr::SystemMemoryAttr() : availSysMem_(0), totalSysMem_(0), threshold_(0), isSysInlowMem_(false) +{} + +bool SystemMemoryAttr::ReadFromParcel(Parcel &parcel) +{ + parcel.ReadInt64(availSysMem_); + parcel.ReadInt64(totalSysMem_); + parcel.ReadInt64(threshold_); + isSysInlowMem_ = parcel.ReadBool(); + + APP_LOGD("SystemMemoryAttr::ReadFromParcel %{public}zu %{public}zu %{public}zu %{public}s", + static_cast(availSysMem_), + static_cast(totalSysMem_), + static_cast(threshold_), + (isSysInlowMem_ ? "true" : "false")); + + return true; +} + +SystemMemoryAttr *SystemMemoryAttr::Unmarshalling(Parcel &parcel) +{ + SystemMemoryAttr *info = new (std::nothrow) SystemMemoryAttr(); + if (info == nullptr) { + return nullptr; + } + + if (!info->ReadFromParcel(parcel)) { + delete info; + info = nullptr; + } + return info; +} + +bool SystemMemoryAttr::Marshalling(Parcel &parcel) const +{ + parcel.WriteInt64(availSysMem_); + parcel.WriteInt64(totalSysMem_); + parcel.WriteInt64(threshold_); + parcel.WriteBool(isSysInlowMem_); + + APP_LOGD("SystemMemoryAttr::Marshalling %{public}zu %{public}zu %{public}zu %{public}s", + static_cast(availSysMem_), + static_cast(totalSysMem_), + static_cast(threshold_), + (isSysInlowMem_ ? "true" : "false")); + + return true; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/base/BUILD.gn b/interfaces/innerkits/base/BUILD.gn index c41394fc0457daf3357f2ac9b6d7703ae1e986ee..42a2ef6572b42e190eb7899bf2f581ec104409ea 100644 --- a/interfaces/innerkits/base/BUILD.gn +++ b/interfaces/innerkits/base/BUILD.gn @@ -22,9 +22,6 @@ config("base_public_config") { visibility = [ ":*" ] include_dirs = [ "//foundation/aafwk/standard/interfaces/innerkits/base/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", - "//foundation/appexecfwk/standard/common/log/include", - "//third_party/jsoncpp/include", "//utils/native/base/include", ] } @@ -50,11 +47,8 @@ ohos_shared_library("base") { ] configs = [ ":base_config" ] public_configs = [ ":base_public_config" ] - deps = [ - "//third_party/jsoncpp:jsoncpp", - "//utils/native/base:utils", - ] + deps = [ "//utils/native/base:utils" ] subsystem_name = "aafwk" - part_name = "ability_runtime" + part_name = "ability_base" } diff --git a/interfaces/innerkits/bundle.json b/interfaces/innerkits/bundle.json new file mode 100644 index 0000000000000000000000000000000000000000..538567b689237c290afb596efdabad4e9c0fd906 --- /dev/null +++ b/interfaces/innerkits/bundle.json @@ -0,0 +1,90 @@ +{ + "name": "@ohos/ability_base", + "description": "aafwk子系统中的基础库,want,base等", + "version": "3.1", + "license": "Apache License 2.0", + "publishAs": "code-segment", + "segment": { + "destPath": "foundation/aafwk/standard/interfaces/innerkits" + }, + "dirs": {}, + "scripts": {}, + "component": { + "name": "ability_base", + "subsystem": "aafwk", + "syscap": [], + "features": [], + "adapted_system_type": [ + "standard" + ], + "rom": "", + "ram": "", + "deps": { + "components": [ + "hiviewdfx_hilog_native", + "ipc", + "utils_base" + ], + "third_party": [ + "jsoncpp", + "json" + ] + }, + "build": { + "sub_component": [ + "//foundation/aafwk/standard/interfaces/innerkits:base_innerkits_target" + ], + "inner_kits": [ + { + "header": { + "header_base": "//foundation/aafwk/standard/interfaces/innerkits/base/include/", + "header_files": [ + "ohos/aafwk/base/array_wrapper.h", + "ohos/aafwk/base/base_def.h", + "ohos/aafwk/base/base_interfaces.h", + "ohos/aafwk/base/base_object.h", + "ohos/aafwk/base/base_types.h", + "ohos/aafwk/base/bool_wrapper.h", + "ohos/aafwk/base/byte_wrapper.h", + "ohos/aafwk/base/double_wrapper.h", + "ohos/aafwk/base/float_wrapper.h", + "ohos/aafwk/base/int_wrapper.h", + "ohos/aafwk/base/light_refbase.h", + "ohos/aafwk/base/long_wrapper.h", + "ohos/aafwk/base/short_wrapper.h", + "ohos/aafwk/base/string_wrapper.h" + ] + }, + "name": "//foundation/aafwk/standard/interfaces/innerkits/base:base" + }, + { + "header": { + "header_base": "//foundation/aafwk/standard/interfaces/innerkits/want/include/", + "header_files": [ + "ohos/aafwk/content/element_name.h", + "ohos/aafwk/content/want.h", + "ohos/aafwk/content/skills.h", + "ohos/aafwk/content/want_params.h", + "ohos/aafwk/content/match_type.h", + "ohos/aafwk/content/operation.h", + "ohos/aafwk/content/patterns_matcher.h", + "ohos/aafwk/content/pac_map.h" + ] + }, + "name": "//foundation/aafwk/standard/interfaces/innerkits/want:want" + }, + { + "header": { + "header_base": "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "header_files": [ + "configuration.h", + "global_configuration_key.h" + ] + }, + "name": "//foundation/aafwk/standard/interfaces/innerkits/app_manager:configuration" + } + ], + "test": [] + } + } +} \ No newline at end of file diff --git a/interfaces/innerkits/form_manager/include/form_constants.h b/interfaces/innerkits/form_manager/include/form_constants.h index 796d214f81f2ffa58b6aaec3babb59ee898d9bcd..51a1fd8269b3f47d7655ee338a09f34fe93057d3 100644 --- a/interfaces/innerkits/form_manager/include/form_constants.h +++ b/interfaces/innerkits/form_manager/include/form_constants.h @@ -44,6 +44,9 @@ namespace Constants { const std::string ACTION_UPDATEATTIMER = "form_update_at_timer"; const std::string KEY_WAKEUP_TIME = "wakeUpTime"; const std::string KEY_ACTION_TYPE = "form_update_action_type"; + const std::string ABS_CODE_PATH = "/data/app/el1/bundle/public"; + const std::string LOCAL_CODE_PATH = "/data/storage/el1/bundle"; + const std::string LOCAL_BUNDLES = "/data/bundles"; const int TYPE_RESET_LIMIT = 1; const int TYPE_STATIC_UPDATE = 2; const int TYPE_DYNAMIC_UPDATE = 3; diff --git a/interfaces/innerkits/form_manager/src/form_provider_data.cpp b/interfaces/innerkits/form_manager/src/form_provider_data.cpp index fa5d0a85d5d50f89963c5e59fe10c2862558a4ae..66072d552401a7793ffaaad31772a78e60843701 100755 --- a/interfaces/innerkits/form_manager/src/form_provider_data.cpp +++ b/interfaces/innerkits/form_manager/src/form_provider_data.cpp @@ -57,7 +57,12 @@ FormProviderData::FormProviderData(std::string jsonDataString) if (jsonDataString.empty()) { jsonDataString = JSON_EMPTY_STRING; } - jsonFormProviderData_ = nlohmann::json::parse(jsonDataString); + nlohmann::json jsonObject = nlohmann::json::parse(jsonDataString, nullptr, false); + if (jsonObject.is_discarded()) { + HILOG_ERROR("failed to parse jsonDataString: %{public}s.", jsonDataString.c_str()); + return; + } + jsonFormProviderData_ = jsonObject; } /** @@ -164,7 +169,12 @@ void FormProviderData::SetDataString(std::string &jsonDataString) if (jsonDataString.empty()) { jsonDataString = JSON_EMPTY_STRING; } - jsonFormProviderData_ = nlohmann::json::parse(jsonDataString); + nlohmann::json jsonObject = nlohmann::json::parse(jsonDataString, nullptr, false); + if (jsonObject.is_discarded()) { + HILOG_ERROR("failed to parse jsonDataString: %{public}s.", jsonDataString.c_str()); + return; + } + jsonFormProviderData_ = jsonObject; } /** * @brief Merge new data to FormProviderData. @@ -230,7 +240,13 @@ void FormProviderData::SetImageDataMap(std::map) { return engine.CreateNumber(static_cast>(value)); } - return nullptr; + return engine.CreateUndefined(); } template @@ -101,7 +101,7 @@ NativeValue* CreateNativeArray(NativeEngine& engine, const std::vector& data) NativeValue* arrayValue = engine.CreateArray(data.size()); NativeArray* array = ConvertNativeValueTo(arrayValue); uint32_t index = 0; - for (const auto& item : data) { + for (const T& item : data) { array->SetElement(index++, CreateJsValue(engine, item)); } return arrayValue; diff --git a/interfaces/innerkits/runtime/include/runtime.h b/interfaces/innerkits/runtime/include/runtime.h index 5be53268372c76b103ed81a8fb0f76b62bea48b0..3a67756d144434a01f612e8d37e8bb2f96511c79 100644 --- a/interfaces/innerkits/runtime/include/runtime.h +++ b/interfaces/innerkits/runtime/include/runtime.h @@ -16,8 +16,6 @@ #ifndef FOUNDATION_OHOS_ABILITYRUNTIME_RUNTIME_H #define FOUNDATION_OHOS_ABILITYRUNTIME_RUNTIME_H -#include -#include #include namespace OHOS { diff --git a/interfaces/innerkits/uri_permission/BUILD.gn b/interfaces/innerkits/uri_permission/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..6025b2fffa9cb6c91471e5c14a383f04b3cfdd41 --- /dev/null +++ b/interfaces/innerkits/uri_permission/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("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +config("uripermkit_public_config") { + visibility = [ ":*" ] + include_dirs = [ "include" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} + +#build so +ohos_shared_library("uri_permission_mgr") { + configs = [ "${services_path}/common:common_config" ] + public_configs = [ ":uripermkit_public_config" ] + + sources = [ + "src/uri_permission_manager_client.cpp", + "src/uri_permission_manager_proxy.cpp", + "src/uri_permission_manager_stub.cpp", + ] + + deps = [ "${innerkits_path}/want:want" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "dmsfwk_standard:zuri", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + "utils_base:utils", + ] + + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/innerkits/uri_permission/include/uri_permission_manager_client.h b/interfaces/innerkits/uri_permission/include/uri_permission_manager_client.h new file mode 100644 index 0000000000000000000000000000000000000000..ac1f8c9c76d3bc85f46b7413bffed7261d4d144a --- /dev/null +++ b/interfaces/innerkits/uri_permission/include/uri_permission_manager_client.h @@ -0,0 +1,80 @@ +/* + * 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_AAFWK_URI_PERMISSION_MANAGER_CLIENT_H +#define OHOS_AAFWK_URI_PERMISSION_MANAGER_CLIENT_H + +#include "singleton.h" +#include "uri.h" +#include "uri_permission_manager_interface.h" + +namespace OHOS { +namespace AAFwk { +using ErrCode = int32_t; + +class UriPermissionManagerClient : public DelayedSingleton { +public: + UriPermissionManagerClient() = default; + ~UriPermissionManagerClient() = default; + + /** + * @brief Authorize the uri permission of fromTokenId to targetTokenId. + * + * @param uri The file uri. + * @param flag Want::FLAG_AUTH_READ_URI_PERMISSION or Want::FLAG_AUTH_WRITE_URI_PERMISSION. + * @param fromTokenId The owner of uri. + * @param targetTokenId The user of uri. + */ + void GrantUriPermission(const Uri &uri, unsigned int flag, const Security::AccessToken::AccessTokenID fromTokenId, + const Security::AccessToken::AccessTokenID targetTokenId); + + /** + * @brief Check whether the tokenId has URI permissions. + * + * @param uri The file uri. + * @param flag Want::FLAG_AUTH_READ_URI_PERMISSION or Want::FLAG_AUTH_WRITE_URI_PERMISSION. + * @param tokenId The user of uri. + * @return Returns true if the verification is successful, otherwise returns false. + */ + bool VerifyUriPermission(const Uri &uri, unsigned int flag, const Security::AccessToken::AccessTokenID tokenId); + + /** + * @brief Clear user's uri authorization record. + * + * @param tokenId A tokenId of an application. + */ + void RemoveUriPermission(const Security::AccessToken::AccessTokenID tokenId); + +private: + ErrCode ConnectUriPermService(); + DISALLOW_COPY_AND_MOVE(UriPermissionManagerClient); + + class UpmsDeathRecipient : public IRemoteObject::DeathRecipient { + public: + UpmsDeathRecipient(sptr &uriPermMgr) : proxy_(uriPermMgr) {} + ~UpmsDeathRecipient() = default; + virtual void OnRemoteDied([[maybe_unused]] const wptr& remote) override; + + private: + sptr proxy_; + }; + +private: + std::mutex mutex_; + sptr uriPermMgr_ = nullptr; +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_URI_PERMISSION_MANAGER_CLIENT_H diff --git a/interfaces/innerkits/uri_permission/include/uri_permission_manager_interface.h b/interfaces/innerkits/uri_permission/include/uri_permission_manager_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..a09037c32e6478e19de1c1b174cd0641d5b8d676 --- /dev/null +++ b/interfaces/innerkits/uri_permission/include/uri_permission_manager_interface.h @@ -0,0 +1,72 @@ +/* + * 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_AAFWK_URI_PERMISSION_MANAGER_INTERFACE_H +#define OHOS_AAFWK_URI_PERMISSION_MANAGER_INTERFACE_H + +#include "base/security/access_token/interfaces/innerkits/accesstoken/include/access_token.h" +#include "iremote_broker.h" +#include "uri.h" + +namespace OHOS { +namespace AAFwk { +class IUriPermissionManager : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.aafwk.UriPermissionManager"); + + /** + * @brief Authorize the uri permission of fromTokenId to targetTokenId. + * + * @param uri The file uri. + * @param flag Want::FLAG_AUTH_READ_URI_PERMISSION or Want::FLAG_AUTH_WRITE_URI_PERMISSION. + * @param fromTokenId The owner of uri. + * @param targetTokenId The user of uri. + */ + virtual void GrantUriPermission(const Uri &uri, unsigned int flag, + const Security::AccessToken::AccessTokenID fromTokenId, + const Security::AccessToken::AccessTokenID targetTokenId) = 0; + + /** + * @brief Check whether the tokenId has URI permissions. + * + * @param uri The file uri. + * @param flag Want::FLAG_AUTH_READ_URI_PERMISSION or Want::FLAG_AUTH_WRITE_URI_PERMISSION. + * @param tokenId The user of uri. + * @return Returns true if the verification is successful, otherwise returns false. + */ + virtual bool VerifyUriPermission(const Uri &uri, unsigned int flag, + const Security::AccessToken::AccessTokenID tokenId) = 0; + + /** + * @brief Clear user's uri authorization record. + * + * @param tokenId A tokenId of an application. + */ + virtual void RemoveUriPermission(const Security::AccessToken::AccessTokenID tokenId) = 0; + + enum UriPermMgrCmd { + // ipc id for GrantUriPermission + ON_GRANT_URI_PERMISSION = 0, + + // ipc id for VerifyUriPermission + ON_VERIFY_URI_PERMISSION, + + // ipc id for RemoveUriPermission + ON_REMOVE_URI_PERMISSION, + }; +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_URI_PERMISSION_MANAGER_INTERFACE_H diff --git a/interfaces/innerkits/uri_permission/include/uri_permission_manager_proxy.h b/interfaces/innerkits/uri_permission/include/uri_permission_manager_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..5d202e2798efc95d4e300b1cf254a5ea849af71e --- /dev/null +++ b/interfaces/innerkits/uri_permission/include/uri_permission_manager_proxy.h @@ -0,0 +1,43 @@ +/* + * 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_AAFWK_URI_PERMISSION_MANAGER_PROXY_H +#define OHOS_AAFWK_URI_PERMISSION_MANAGER_PROXY_H + +#include "iremote_proxy.h" +#include "uri_permission_manager_interface.h" + +namespace OHOS { +namespace AAFwk { +class UriPermissionManagerProxy : public IRemoteProxy { +public: + explicit UriPermissionManagerProxy(const sptr &impl); + virtual ~UriPermissionManagerProxy() = default; + + virtual void GrantUriPermission(const Uri &uri, unsigned int flag, + const Security::AccessToken::AccessTokenID fromTokenId, + const Security::AccessToken::AccessTokenID targetTokenId) override; + + virtual bool VerifyUriPermission(const Uri &uri, unsigned int flag, + const Security::AccessToken::AccessTokenID tokenId) override; + + virtual void RemoveUriPermission(const Security::AccessToken::AccessTokenID tokenId) override; + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_URI_PERMISSION_MANAGER_PROXY_H diff --git a/interfaces/innerkits/uri_permission/include/uri_permission_manager_stub.h b/interfaces/innerkits/uri_permission/include/uri_permission_manager_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..7799caade9dfd5bee4698e4836d98122e92e64b5 --- /dev/null +++ b/interfaces/innerkits/uri_permission/include/uri_permission_manager_stub.h @@ -0,0 +1,40 @@ +/* + * 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_AAFWK_URI_PERMISSION_MANAGER_STUB_H +#define OHOS_AAFWK_URI_PERMISSION_MANAGER_STUB_H + +#include + +#include "iremote_stub.h" +#include "message_parcel.h" +#include "nocopyable.h" +#include "uri_permission_manager_interface.h" + +namespace OHOS { +namespace AAFwk { +class UriPermissionManagerStub : public IRemoteStub { +public: + UriPermissionManagerStub() = default; + virtual ~UriPermissionManagerStub() = default; + + int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + DISALLOW_COPY_AND_MOVE(UriPermissionManagerStub); +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_URI_PERMISSION_MANAGER_STUB_H diff --git a/interfaces/innerkits/uri_permission/src/uri_permission_manager_client.cpp b/interfaces/innerkits/uri_permission/src/uri_permission_manager_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8b7684b585ad24a3b54c75992781171f77bb21f0 --- /dev/null +++ b/interfaces/innerkits/uri_permission/src/uri_permission_manager_client.cpp @@ -0,0 +1,89 @@ +/* + * 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 "uri_permission_manager_client.h" + +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AAFwk { +void UriPermissionManagerClient::GrantUriPermission(const Uri &uri, unsigned int flag, + const Security::AccessToken::AccessTokenID fromTokenId, const Security::AccessToken::AccessTokenID targetTokenId) +{ + HILOG_DEBUG("UriPermissionManagerClient::GrantUriPermission is called."); + ErrCode ret = ConnectUriPermService(); + if (ret != 0 || !uriPermMgr_) { + HILOG_ERROR("Failed to ConnectUriPermService"); + return; + } + uriPermMgr_->GrantUriPermission(uri, flag, fromTokenId, targetTokenId); +} + +bool UriPermissionManagerClient::VerifyUriPermission(const Uri &uri, unsigned int flag, + const Security::AccessToken::AccessTokenID tokenId) +{ + HILOG_DEBUG("UriPermissionManagerClient::VerifyUriPermission is called."); + ErrCode ret = ConnectUriPermService(); + if (ret != 0 || !uriPermMgr_) { + HILOG_ERROR("Failed to ConnectUriPermService"); + return false; + } + return uriPermMgr_->VerifyUriPermission(uri, flag, tokenId); +} + +void UriPermissionManagerClient::RemoveUriPermission(const Security::AccessToken::AccessTokenID tokenId) +{ + HILOG_DEBUG("UriPermissionManagerClient::RemoveUriPermission is called."); + ErrCode ret = ConnectUriPermService(); + if (ret != 0 || !uriPermMgr_) { + HILOG_ERROR("Failed to ConnectUriPermService"); + return; + } + uriPermMgr_->RemoveUriPermission(tokenId); +} + +ErrCode UriPermissionManagerClient::ConnectUriPermService() +{ + HILOG_DEBUG("UriPermissionManagerClient::ConnectUriPermService is called."); + std::lock_guard lock(mutex_); + if (uriPermMgr_ == nullptr) { + auto systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!systemAbilityMgr) { + HILOG_ERROR("Failed to get SystemAbilityManager."); + return -1; + } + + auto remoteObj = systemAbilityMgr->GetSystemAbility(URI_PERMISSION_MGR_SERVICE_ID); + if (!remoteObj || (uriPermMgr_ = iface_cast(remoteObj)) == nullptr) { + HILOG_ERROR("Failed to get UriPermService."); + return -1; + } + } + sptr recipient(new UpmsDeathRecipient(uriPermMgr_)); + uriPermMgr_->AsObject()->AddDeathRecipient(recipient); + HILOG_DEBUG("End UriPermissionManagerClient::ConnectUriPermService."); + return 0; +} + +void UriPermissionManagerClient::UpmsDeathRecipient::OnRemoteDied([[maybe_unused]] const wptr& remote) +{ + HILOG_ERROR("upms stub died."); + proxy_ = nullptr; +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/uri_permission/src/uri_permission_manager_proxy.cpp b/interfaces/innerkits/uri_permission/src/uri_permission_manager_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7602099ae43a12bfcbef2ec649ea7e41a78fe52d --- /dev/null +++ b/interfaces/innerkits/uri_permission/src/uri_permission_manager_proxy.cpp @@ -0,0 +1,110 @@ +/* + * 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 "uri_permission_manager_proxy.h" + +#include "hilog_wrapper.h" +#include "parcel.h" + +namespace OHOS { +namespace AAFwk { +UriPermissionManagerProxy::UriPermissionManagerProxy(const sptr &impl) + : IRemoteProxy(impl) {} + +void UriPermissionManagerProxy::GrantUriPermission(const Uri &uri, unsigned int flag, + const Security::AccessToken::AccessTokenID fromTokenId, const Security::AccessToken::AccessTokenID targetTokenId) +{ + HILOG_DEBUG("UriPermissionManagerProxy::GrantUriPermission is called."); + MessageParcel data; + if (!data.WriteInterfaceToken(IUriPermissionManager::GetDescriptor())) { + HILOG_ERROR("Write interface token failed."); + return; + } + if (!data.WriteParcelable(&uri)) { + HILOG_ERROR("Write uri failed."); + return; + } + if (!data.WriteInt32(flag)) { + HILOG_ERROR("Write flag failed."); + return; + } + if (!data.WriteInt32(fromTokenId)) { + HILOG_ERROR("Write fromTokenId failed."); + return; + } + if (!data.WriteInt32(targetTokenId)) { + HILOG_ERROR("Write targetTokenId failed."); + return; + } + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest(UriPermMgrCmd::ON_GRANT_URI_PERMISSION, data, reply, option); + if (error != ERR_OK) { + HILOG_ERROR("SendRequest fial, error: %{public}d", error); + } +} + +bool UriPermissionManagerProxy::VerifyUriPermission(const Uri &uri, unsigned int flag, + const Security::AccessToken::AccessTokenID tokenId) +{ + HILOG_DEBUG("UriPermissionManagerProxy::VerifyUriPermission is called."); + MessageParcel data; + if (!data.WriteInterfaceToken(IUriPermissionManager::GetDescriptor())) { + HILOG_ERROR("Write interface token failed."); + return false; + } + if (!data.WriteParcelable(&uri)) { + HILOG_ERROR("Write uri failed."); + return false; + } + if (!data.WriteInt32(flag)) { + HILOG_ERROR("Write flag failed."); + return false; + } + if (!data.WriteInt32(tokenId)) { + HILOG_ERROR("Write tokenId failed."); + return false; + } + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest(UriPermMgrCmd::ON_VERIFY_URI_PERMISSION, data, reply, option); + if (error != ERR_OK) { + HILOG_ERROR("SendRequest fial, error: %{public}d", error); + return false; + } + return true; +} + +void UriPermissionManagerProxy::RemoveUriPermission(const Security::AccessToken::AccessTokenID tokenId) +{ + HILOG_DEBUG("UriPermissionManagerProxy::RemoveUriPermission is called."); + MessageParcel data; + if (!data.WriteInterfaceToken(IUriPermissionManager::GetDescriptor())) { + HILOG_ERROR("Write interface token failed."); + return; + } + if (!data.WriteInt32(tokenId)) { + HILOG_ERROR("Write AccessTokenID failed."); + return; + } + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest(UriPermMgrCmd::ON_REMOVE_URI_PERMISSION, data, reply, option); + if (error != ERR_OK) { + HILOG_ERROR("SendRequest fail, error: %{public}d", error); + } +} +} // namespace AAFwk +} // namespace OHOS diff --git a/interfaces/innerkits/uri_permission/src/uri_permission_manager_stub.cpp b/interfaces/innerkits/uri_permission/src/uri_permission_manager_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..81d6ab6e58a8149c70d48664024224c564f6b1c5 --- /dev/null +++ b/interfaces/innerkits/uri_permission/src/uri_permission_manager_stub.cpp @@ -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. + */ + +#include "uri_permission_manager_stub.h" + +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AAFwk { +int UriPermissionManagerStub::OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + if (data.ReadInterfaceToken() != IUriPermissionManager::GetDescriptor()) { + HILOG_ERROR("InterfaceToken not equal IUriPermissionManager's descriptor."); + return ERR_INVALID_VALUE; + } + ErrCode errCode = ERR_OK; + switch (code) { + case UriPermMgrCmd::ON_GRANT_URI_PERMISSION : { + std::unique_ptr uri(data.ReadParcelable()); + if (!uri) { + errCode = ERR_DEAD_OBJECT; + HILOG_ERROR("To read uri failed."); + break; + } + auto flag = data.ReadInt32(); + auto fromTokenId = data.ReadInt32(); + auto targetTokenId = data.ReadInt32(); + GrantUriPermission(*uri, flag, fromTokenId, targetTokenId); + break; + } + case UriPermMgrCmd::ON_VERIFY_URI_PERMISSION : { + std::unique_ptr uri(data.ReadParcelable()); + if (!uri) { + errCode = ERR_DEAD_OBJECT; + HILOG_ERROR("To read uri failed."); + break; + } + auto flag = data.ReadInt32(); + auto tokenId = data.ReadInt32(); + if (!VerifyUriPermission(*uri, flag, tokenId)) { + errCode = ERR_INVALID_OPERATION; + HILOG_ERROR("To check uri permission failed."); + } + break; + } + case UriPermMgrCmd::ON_REMOVE_URI_PERMISSION : { + auto tokenId = data.ReadInt32(); + RemoveUriPermission(tokenId); + break; + } + default: + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + return errCode; +} +} // namespace AAFwk +} // namespace OHOS diff --git a/interfaces/innerkits/want/BUILD.gn b/interfaces/innerkits/want/BUILD.gn index 22c3ae7cb8490f3cf15c605647b90dbde531c512..3adcd1337924e16f88c0ff0b642d3819f1a021bb 100644 --- a/interfaces/innerkits/want/BUILD.gn +++ b/interfaces/innerkits/want/BUILD.gn @@ -46,6 +46,7 @@ wantImpl = "//foundation/aafwk/standard/frameworks/kits/content/cpp/src/ohos/aaf ohos_shared_library("want") { sources = [ + "${wantImpl}/element_name.cpp", "${wantImpl}/extra_params.cpp", "${wantImpl}/operation.cpp", "${wantImpl}/operation_builder.cpp", @@ -61,16 +62,11 @@ ohos_shared_library("want") { "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", - "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", - - #"//foundation/distributeddatamgr/distributeddatamgr:build_module", - "//foundation/distributedschedule/samgr/interfaces/innerkits/lsamgr:lsamgr", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] external_deps = [ - "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] @@ -78,5 +74,5 @@ ohos_shared_library("want") { configs = [ ":want_config" ] public_configs = [ ":want_public_config" ] subsystem_name = "aafwk" - part_name = "ability_runtime" + part_name = "ability_base" } diff --git a/interfaces/innerkits/want/include/ohos/aafwk/content/element_name.h b/interfaces/innerkits/want/include/ohos/aafwk/content/element_name.h new file mode 100644 index 0000000000000000000000000000000000000000..339226529e365db792d5bf7f1b9d0fb6e56cae66 --- /dev/null +++ b/interfaces/innerkits/want/include/ohos/aafwk/content/element_name.h @@ -0,0 +1,83 @@ +/* + * 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_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_ELEMENT_NAME_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_ELEMENT_NAME_H + +#include + +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +class ElementName : public Parcelable { + /* + * How to locate unique Ability: deviceId/bundleName/abilityName + */ +public: + ElementName(const std::string &deviceId, const std::string &bundleName, const std::string &abilityName); + ElementName(); + ~ElementName(); + + std::string GetURI() const; + bool operator==(const ElementName &element) const; + + inline void SetDeviceID(const std::string &id) + { + deviceId_ = id; + } + + inline std::string GetDeviceID() const + { + return deviceId_; + } + + inline void SetBundleName(const std::string &name) + { + bundleName_ = name; + } + + inline std::string GetBundleName() const + { + return bundleName_; + } + + inline void SetAbilityName(const std::string &name) + { + abilityName_ = name; + } + + inline std::string GetAbilityName() const + { + return abilityName_; + } + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static ElementName *Unmarshalling(Parcel &parcel); + + void SetElementDeviceID(ElementName *element, const char *deviceId); + void SetElementBundleName(ElementName *element, const char *bundleName); + void SetElementAbilityName(ElementName *element, const char *abilityName); + void ClearElement(ElementName *element); + +private: + std::string deviceId_; + std::string bundleName_; + std::string abilityName_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_ELEMENT_NAME_H diff --git a/interfaces/innerkits/want/include/ohos/aafwk/content/want.h b/interfaces/innerkits/want/include/ohos/aafwk/content/want.h index 1c571636cbb2f9e46917b6855e9d9debf3c16f59..8cbea1e7b33b4506804c444f2e95bdd931ec9bca 100644 --- a/interfaces/innerkits/want/include/ohos/aafwk/content/want.h +++ b/interfaces/innerkits/want/include/ohos/aafwk/content/want.h @@ -789,6 +789,7 @@ public: // reserved param definition static const std::string PARAM_RESV_WINDOW_MODE; + static const std::string PARAM_RESV_DISPLAY_ID; static const std::string PARAM_RESV_CALLER_TOKEN; static const std::string PARAM_RESV_CALLER_UID; static const std::string PARAM_RESV_CALLER_PID; diff --git a/interfaces/kits/js/app/missionSnapshot.d.ts b/interfaces/innerkits/wantagent/include/cancel_listener.h old mode 100755 new mode 100644 similarity index 51% rename from interfaces/kits/js/app/missionSnapshot.d.ts rename to interfaces/innerkits/wantagent/include/cancel_listener.h index 01ae787ee8c5c0a799cebc6d132ce5ee8597e492..bdb923a3c167d7e9684986e989a6bb8199eab806 --- a/interfaces/kits/js/app/missionSnapshot.d.ts +++ b/interfaces/innerkits/wantagent/include/cancel_listener.h @@ -13,25 +13,19 @@ * limitations under the License. */ -import { ElementName } from '../bundle/elementName'; -import { image } from '../@ohos.multimedia.image'; - -/** - * @name This class represents a mission snapshot. - * @since 7 - * @SysCap appexecfwk - * @import import MissionSnapshot from 'app/missionSnapshot' - * @devices phone, tablet - * @systemapi hide this for inner system use - */ -export interface MissionSnapshot { - /** - * @default The top ability in this mission snapshot - */ - topAbility: ElementName; +#ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_CANCEL_LISTENER_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_CANCEL_LISTENER_H +namespace OHOS::AbilityRuntime::WantAgent { +class CancelListener { +public: /** - * @default The entity of snapshot + * Called when a Cancel operation as completed. + * + * @param resultCode The final result code determined by the Send. */ - snapshot: image.PixelMap; -} + virtual void OnCancelled(int resultCode) = 0; + virtual ~CancelListener() = default; +}; +} // namespace OHOS::AbilityRuntime::WantAgent +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_CANCEL_LISTENER_H \ No newline at end of file diff --git a/interfaces/kits/js/app/activeProcessInfo.d.ts b/interfaces/innerkits/wantagent/include/completed_callback.h old mode 100755 new mode 100644 similarity index 39% rename from interfaces/kits/js/app/activeProcessInfo.d.ts rename to interfaces/innerkits/wantagent/include/completed_callback.h index 4ab5a6aa3d13ebb12c46c3221fbc44b4b5908d3f..d136783b48380780b632efc216f63b21fd4cb065 --- a/interfaces/kits/js/app/activeProcessInfo.d.ts +++ b/interfaces/innerkits/wantagent/include/completed_callback.h @@ -13,40 +13,28 @@ * limitations under the License. */ -/** - * @name This class saves process information about an application - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @import import app from 'app/activeProcessInfo' - * @permission N/A - * @devices phone, tablet, tv, wearable, car - */ -export interface ActiveProcessInfo { - /** - * @default process id - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - pid: number; - - /** - * @default user id - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - uid: number; +#ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_COMPLETED_CALLBACK_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_COMPLETED_CALLBACK_H - /** - * @default the name of the process - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - processName: string; +#include +#include +#include "want.h" +#include "want_params.h" +namespace OHOS::AbilityRuntime::WantAgent { +class CompletedCallback { +public: + virtual ~CompletedCallback() = default; /** - * @default an array of the bundleNames running in the process - * @since 7 - * @SysCap SystemCapability.Appexecfwk + * Called when a Send operation as completed. + * + * @param want The original Want that was sent. + * @param resultCode The final result code determined by the Send. + * @param resultData The final data collected by a broadcast. + * @param resultExtras The final extras collected by a broadcast. */ - bundleNames: Array; -} + virtual void OnSendFinished(const AAFwk::Want &want, int resultCode, const std::string &resultData, + const AAFwk::WantParams &resultExtras) = 0; +}; +} // namespace OHOS::AbilityRuntime::WantAgent +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_COMPLETED_CALLBACK_H \ No newline at end of file diff --git a/interfaces/innerkits/wantagent/include/completed_dispatcher.h b/interfaces/innerkits/wantagent/include/completed_dispatcher.h new file mode 100644 index 0000000000000000000000000000000000000000..fbb97a6b7548734b76d1a02ed8b9ab878a9f51d1 --- /dev/null +++ b/interfaces/innerkits/wantagent/include/completed_dispatcher.h @@ -0,0 +1,52 @@ +/* + * 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 BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_COMPLETED_DISPATCHER_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_COMPLETED_DISPATCHER_H + +#include +#include +#include "completed_callback.h" +#include "event_handler.h" +#include "want.h" +#include "want_params.h" +#include "want_receiver_stub.h" + +namespace OHOS::AbilityRuntime::WantAgent { +class PendingWant; +class CompletedDispatcher : public AAFwk::WantReceiverStub { +public: + CompletedDispatcher(const std::shared_ptr &pendingWant, + const std::shared_ptr &callback, const std::shared_ptr &handler); + virtual ~CompletedDispatcher() = default; + + void Send(const int32_t resultCode) override; + + void PerformReceive(const AAFwk::Want &want, int resultCode, const std::string &data, + const AAFwk::WantParams &extras, bool serialized, bool sticky, int sendingUser) override; + + void Run(); + +private: + const std::shared_ptr pendingWant_; + const std::shared_ptr callback_; + const std::shared_ptr handler_; + AAFwk::Want want_; + int resultCode_ = 0; + std::string resultData_; + AAFwk::WantParams resultExtras_; +}; +} // namespace OHOS::AbilityRuntime::WantAgent +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_COMPLETED_DISPATCHER_H \ No newline at end of file diff --git a/interfaces/innerkits/wantagent/include/pending_want.h b/interfaces/innerkits/wantagent/include/pending_want.h new file mode 100644 index 0000000000000000000000000000000000000000..c2a85aaf3756219969371593f54b6002ede661e4 --- /dev/null +++ b/interfaces/innerkits/wantagent/include/pending_want.h @@ -0,0 +1,281 @@ +/* + * 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 BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_PENDING_WANT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_PENDING_WANT_H + +#include +#include +#include +#include +#include "cancel_listener.h" +#include "context/context.h" +#include "completed_dispatcher.h" +#include "event_handler.h" +#include "want.h" +#include "want_agent_constant.h" +#include "want_params.h" +#include "want_receiver_stub.h" +#include "want_sender_info.h" +#include "want_sender_stub.h" + +namespace OHOS::AbilityRuntime::WantAgent { +class PendingWant final : public std::enable_shared_from_this, public Parcelable { +public: + PendingWant() {}; + PendingWant(const sptr &target); + PendingWant(const sptr &target, const sptr whitelistToken); + virtual ~PendingWant() = default; + + WantAgentConstant::OperationType GetType(const sptr &target); + + /** + * Retrieve a PendingWant that will start a new ability. + * + * @param context The Context in which this PendingWant should start + * the ability. + * @param requestCode Private request code for the sender + * @param want Want of the ability to be launched. + * @param flags May be FLAG_ONE_SHOT, FLAG_NO_CREATE}, + * FLAG_CANCEL_CURRENT, FLAG_UPDATE_CURRENT. + * + * @return Returns an existing or new PendingWant matching the given + * parameters. May return null only if FLAG_NO_CREATE has been + * supplied. + */ + static std::shared_ptr GetAbility(const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags); + + /** + * Retrieve a PendingWant that will start a new ability + * + * @param context The Context in which this PendingWant should start + * the ability. + * @param requestCode Private request code for the sender + * @param want Want of the ability to be launched. + * @param flags May be FLAG_ONE_SHOT, FLAG_NO_CREATE, + * FLAG_CANCEL_CURRENT, FLAG_UPDATE_CURRENT. + * @param options Additional options for how the ability should be started. + * May be null if there are no options. + * + * @return Returns an existing or new PendingWant matching the given + * parameters. May return null only if FLAG_NO_CREATE has been + * supplied. + */ + static std::shared_ptr GetAbility(const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, + unsigned int flags, const std::shared_ptr &options); + + /** + * Like GetAbility(Context, int, Want, int)}, but allows an + * array of Wants to be supplied. The last Want in the array is + * taken as the primary key for the PendingWant, like the single Want + * given to GetAbility(Context, int, Want, int). + * + * @param context The Context in which this PendingWant should start + * the ability. + * @param requestCode Private request code for the sender + * @param wants Array of Wants of the abilities to be launched. + * @param flags May be FLAG_ONE_SHOT, FLAG_NO_CREATE, + * FLAG_CANCEL_CURRENT, FLAG_UPDATE_CURRENT. + * + * @return Returns an existing or new PendingWant matching the given + * parameters. May return null only if FLAG_NO_CREATE has been + * supplied. + */ + static std::shared_ptr GetAbilities(const std::shared_ptr &context, + int requestCode, std::vector> &wants, unsigned int flags); + + /** + * Like GetAbility(Context, int, Want, int)}, but allows an + * array of Wants to be supplied. The last Want in the array is + * taken as the primary key for the PendingWant, like the single Want + * given to GetAbility(Context, int, Want, int). + * + * @param context The Context in which this PendingWant should start + * the ability. + * @param requestCode Private request code for the sender + * @param wants Array of Wants of the abilities to be launched. + * @param flags May be FLAG_ONE_SHOT, FLAG_NO_CREATE, + * FLAG_CANCEL_CURRENT} link #FLAG_UPDATE_CURRENT, + * FLAG_IMMUTABLE. + * + * @return Returns an existing or new PendingWant matching the given + * parameters. May return null only if FLAG_NO_CREATE has been + * supplied. + */ + static std::shared_ptr GetAbilities(const std::shared_ptr &context, + int requestCode, std::vector> &wants, unsigned int flags, + const std::shared_ptr &options); + + /** + * Retrieve a PendingWant that will perform a common event. + * + * @param context The Context in which this PendingWant should perform + * the common event. + * @param requestCode Private request code for the sender + * @param want The Want to be common event. + * @param flags May be FLAG_ONE_SHOT, FLAG_NO_CREATE, + * FLAG_CANCEL_CURRENT, FLAG_UPDATE_CURRENT, + * FLAG_IMMUTABLE. + * + * @return Returns an existing or new PendingWant matching the given + * parameters. May return null only if FLAG_NO_CREATE has been + * supplied. + */ + static std::shared_ptr GetCommonEvent(const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags); + + /** + * Note that current user will be interpreted at the time the + * common event is sent, not when the pending want is created. + */ + static std::shared_ptr GetCommonEventAsUser( + const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags, int uid); + + /** + * Retrieve a PendingWant that will start a service. + * + * @param context The Context in which this PendingWant should start + * the service. + * @param requestCode Private request code for the sender + * @param want An Want describing the service to be started. + * @param flags May be FLAG_ONE_SHOT, FLAG_NO_CREATE, + * FLAG_CANCEL_CURRENT, FLAG_UPDATE_CURRENT, + * FLAG_IMMUTABLE. + * + * @return Returns an existing or new PendingWant matching the given + * parameters. May return null only if FLAG_NO_CREATE has been + * supplied. + */ + static std::shared_ptr GetService( + const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags); + + /** + * Retrieve a PendingWant that will start a foreground service. + * + * @param context The Context in which this PendingWant should start + * the service. + * @param requestCode Private request code for the sender + * @param want An Want describing the service to be started. + * @param flags May be FLAG_ONE_SHOT, FLAG_NO_CREATE, + * FLAG_CANCEL_CURRENT, FLAG_UPDATE_CURRENT, + * FLAG_IMMUTABLE . + * + * @return Returns an existing or new PendingWant matching the given + * parameters. May return null only if FLAG_NO_CREATE has been + * supplied. + */ + static std::shared_ptr GetForegroundService( + const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags); + + /** + * @description: Marshals a Want into a Parcel. + * Fields in the Want are marshalled separately. If any field fails to be marshalled, false is returned. + * @param parcel Indicates the Parcel object for marshalling. + * @return Returns true if the marshalling is successful; returns false otherwise. + */ + virtual bool Marshalling(Parcel &parcel) const; + + /** + * @description: Unmarshals a Want from a Parcel. + * Fields in the Want are unmarshalled separately. If any field fails to be unmarshalled, false is returned. + * @param parcel Indicates the Parcel object for unmarshalling. + * @return Returns true if the unmarshalling is successful; returns false otherwise. + */ + static PendingWant *Unmarshalling(Parcel &parcel); + + static bool Equals( + const std::shared_ptr &targetPendingWant, const std::shared_ptr &otherPendingWant); + + void Cancel(const sptr &target); + + void Send(const sptr &target); + + void Send(int resultCode, const sptr &target); + + void Send(int resultCode, + const std::shared_ptr &want, const sptr &target); + + void Send(int resultCode, const sptr &onCompleted, const sptr &target); + + void Send(int resultCode, + const std::shared_ptr &want, const sptr &onCompleted, + const sptr &target); + + void Send(int resultCode, + const std::shared_ptr &want, const sptr &onCompleted, + const std::string &requiredPermission, const sptr &target); + + void Send(int resultCode, const std::shared_ptr &want, + const sptr &onCompleted, const std::string &requiredPermission, + const std::shared_ptr &options, const sptr &target); + + int SendAndReturnResult(int resultCode, const std::shared_ptr &want, + const sptr &onCompleted, const std::string &requiredPermission, + const std::shared_ptr &options, const sptr &target); + + std::string GetBundleName(const sptr &target); + + int GetUid(const sptr &target); + + sptr GetTarget(); + + void SetTarget(const sptr &target); + + void RegisterCancelListener( + const std::shared_ptr &cancelListener, const sptr &target); + + void NotifyCancelListeners(int32_t resultCode); + + void UnregisterCancelListener( + const std::shared_ptr &cancelListener, const sptr &target); + + int GetHashCode(const sptr &target); + + std::shared_ptr GetWant(const sptr &target); + + std::shared_ptr GetWantSenderInfo(const sptr &target); + +private: + std::mutex lock_object; + sptr target_; + sptr cancelReceiver_; + sptr whitelistToken_; + std::vector> cancelListeners_; + + class CancelReceiver : public AAFwk::WantReceiverStub { + public: + explicit CancelReceiver(const std::weak_ptr &outerInstance); + virtual ~CancelReceiver() = default; + + void Send(const int32_t resultCode) override; + void PerformReceive(const AAFwk::Want &want, int resultCode, const std::string &data, + const AAFwk::WantParams &extras, bool serialized, bool sticky, int sendingUser) override; + + private: + std::weak_ptr outerInstance_; + }; + + static std::shared_ptr BuildServicePendingWant( + const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags, + WantAgentConstant::OperationType serviceKind); +}; +} // namespace OHOS::AbilityRuntime::WantAgent +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_PENDING_WANT_H \ No newline at end of file diff --git a/interfaces/innerkits/wantagent/include/trigger_info.h b/interfaces/innerkits/wantagent/include/trigger_info.h new file mode 100644 index 0000000000000000000000000000000000000000..60fcd63f9b1891bac718e178e6642fdd25d87774 --- /dev/null +++ b/interfaces/innerkits/wantagent/include/trigger_info.h @@ -0,0 +1,173 @@ +/* + * 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 BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_TRIGGER_INFO_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_TRIGGER_INFO_H + +#include +#include +#include "want.h" +#include "want_params.h" + +namespace OHOS::AbilityRuntime::WantAgent { +class TriggerInfo final : public std::enable_shared_from_this { +public: + /** + * Default constructor used to create a {@code TriggerInfo} instance. + * + */ + TriggerInfo(); + virtual ~TriggerInfo() = default; + + /** + * A constructor used to create a {@code TriggerInfo} instance based on the input parameters. + * + * @param permission Indicates the permission required for an {@link WantAgent} recipient. + * This parameter is valid only when the {@link WantAgent} is triggered to send common events. + * @param extraInfo Indicates the custom extra data you want to add for triggering an {@link WantAgent}. + * @param want Indicates the extra {@link ohos.aafwk.content.Want}. + * If {@code flags} in {@link WantAgentInfo} contains {@link WantAgentConstant.Flags#CONSTANT_FLAG}, + * this parameter is invalid. If flags contains {@link WantAgentConstant.Flags#REPLACE_ELEMENT}, + * {@link WantAgentConstant.Flags#REPLACE_ACTION}, {@link WantAgentConstant.Flags#REPLACE_URI}, + * {@link WantAgentConstant.Flags#REPLACE_ENTITIES}, and {@link WantAgentConstant.Flags#REPLACE_BUNDLE}, + * the {@code element}, {@code action}, {@code uri}, {@code entities}, and {@code bundleName} attributes of the + * {@link ohos.aafwk.content.Want} specified in this parameter will be used to replace the + * corresponding attributes in the original {@link ohos.aafwk.content.Want}, respectively. + * If this parameter is null, the original {@link ohos.aafwk.content.Want} remains unchanged. + * @param code Indicates the result code provided for the target of the {@link WantAgent}. + */ + TriggerInfo(const std::string &permission, const std::shared_ptr &extraInfo, + const std::shared_ptr &want, int resultCode); + + /** + * A constructor used to create a {@code TriggerInfo} instance by copying parameters from an existing one. + * + * @param paramInfo Indicates the existing {@code TriggerInfo} object. + */ + explicit TriggerInfo(const TriggerInfo ¶mInfo); + + /** + * A copy assignment operator used to create a {@code TriggerInfo} instance by copying parameters from an existing + * one. + * + * @param paramInfo Indicates the existing {@code TriggerInfo} object. + */ + const TriggerInfo &operator=(const TriggerInfo ¶mInfo); + + /** + * Obtains the permission from the current {@code TriggerInfo} object. + * + * @return Returns the permission name. + */ + std::string GetPermission() const; + + /** + * Obtains the extra data from the {@code TriggerInfo} object. + * + * @return Returns the extra data. + */ + std::shared_ptr GetExtraInfo() const; + + /** + * Obtains the {@link ohos.aafwk.content.Want} used for triggering an {@link WantAgent}. + * + * @return Returns an {@link ohos.aafwk.content.Want} object. + */ + std::shared_ptr GetWant() const; + + /** + * Obtains the result code provided for the target of the {@link WantAgent}. + * + * @return Returns the result code provided for the target of the {@link WantAgent}. + */ + int GetResultCode() const; + + /** + * A builder class for {@link TriggerInfo} objects. + * + */ +public: + class Builder final : public std::enable_shared_from_this { + public: + /** + * Default constructor used to create a {@code Builder} instance. + * + */ + Builder(); + virtual ~Builder() = default; + + /** + * Sets the permission that the {@link WantAgent} recipient must have. + * + * @param permission Indicates the permission to set. This parameter is valid only when the {@link WantAgent} + * to trigger is intended to send a common event. + * @return Returns this {@code Builder} object with the specified permission. + */ + std::shared_ptr SetPermission(const std::string &permission); + + /** + * Sets custom data. + * + * @param params Indicates the custom data to set. + * @return Returns this {@code Builder} object with the custom data. + */ + std::shared_ptr SetWantParams(const std::shared_ptr ¶ms); + + /** + * Sets a custom {@link ohos.aafwk.content.Want}. + * + * @param want Indicates the custom {@code Want} to set. If the member variable {@code flags} of the + * {@link WantAgentInfo} contains {@link WantAgentConstant.Flags#CONSTANT_FLAG}, this parameter does not + * take effect. If {@code flags} contains {@link WantAgentConstant.Flags#REPLACE_ELEMENT}, + * {@link WantAgentConstant.Flags#REPLACE_ACTION}, {@link WantAgentConstant.Flags#REPLACE_URI}, + * {@link WantAgentConstant.Flags#REPLACE_ENTITIES}, and {@link WantAgentConstant.Flags#REPLACE_BUNDLE}, + * the {@code element}, {@code action}, {@code uri}, {@code entities}, and {@code bundleName} attributes of the + * {@link ohos.aafwk.content.Want} specified in this parameter will be used to replace the corresponding + * attributes in the original {@link ohos.aafwk.content.Want}, respectively. If this parameter is null, the + * original {@link ohos.aafwk.content.Want} remains unchanged. + * @return Returns this {@code Builder} object with the custom {@code Want}. + */ + std::shared_ptr SetWant(const std::shared_ptr &want); + + /** + * Sets the result code provided for the target of the {@link WantAgent}. + * + * @param code Indicates the result code provided for the target of the {@link WantAgent}. + * @return Returns this {@code Builder} object with the specified result code. + */ + std::shared_ptr SetResultCode(int resultCode); + + /** + * Creates a {@link TriggerInfo} object using all of the settings. + * + * @return Returns the created {@code TriggerInfo} object. + */ + std::shared_ptr Build(); + + private: + std::string permission_; + std::shared_ptr params_; + std::shared_ptr want_; + int resultCode_ = 0; + }; + +private: + std::string permission_; + std::shared_ptr extraInfo_; + std::shared_ptr want_; + int resultCode_ = 0; +}; +} // namespace OHOS::AbilityRuntime::WantAgent +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_TRIGGER_INFO_H \ No newline at end of file diff --git a/interfaces/innerkits/wantagent/include/want_agent.h b/interfaces/innerkits/wantagent/include/want_agent.h new file mode 100644 index 0000000000000000000000000000000000000000..5ae6c9242033d3334dac045b634c9e14014d1294 --- /dev/null +++ b/interfaces/innerkits/wantagent/include/want_agent.h @@ -0,0 +1,72 @@ +/* + * 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 BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_H + +#include +#include +#include "parcel.h" +#include "pending_want.h" +#include "want.h" +#include "want_params.h" + +namespace OHOS::AbilityRuntime::WantAgent { +class WantAgent final : public std::enable_shared_from_this, public Parcelable { +public: + WantAgent() {}; + virtual ~WantAgent() = default; + /** + * Constructor. + * + * @param obj The proxy object. + */ + explicit WantAgent(const std::shared_ptr &pendingWant); + + /** + * Gets proxy obj. + * + * @return Return obj. + */ + std::shared_ptr GetPendingWant(); + + /** + * Sets proxy obj. + * + * @param obj The proxy object. + */ + void SetPendingWant(const std::shared_ptr &pendingWant); + + /** + * @description: Marshals a Want into a Parcel. + * Fields in the Want are marshalled separately. If any field fails to be marshalled, false is returned. + * @param parcel Indicates the Parcel object for marshalling. + * @return Returns true if the marshalling is successful; returns false otherwise. + */ + virtual bool Marshalling(Parcel &parcel) const; + + /** + * @description: Unmarshals a Want from a Parcel. + * Fields in the Want are unmarshalled separately. If any field fails to be unmarshalled, false is returned. + * @param parcel Indicates the Parcel object for unmarshalling. + * @return Returns true if the unmarshalling is successful; returns false otherwise. + */ + static WantAgent *Unmarshalling(Parcel &parcel); + +private: + std::shared_ptr pendingWant_; +}; +} // namespace OHOS::AbilityRuntime::WantAgent +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_H \ No newline at end of file diff --git a/interfaces/innerkits/wantagent/include/want_agent_constant.h b/interfaces/innerkits/wantagent/include/want_agent_constant.h new file mode 100644 index 0000000000000000000000000000000000000000..b8541a3840b6b874f79bfc5d8d690fbfebf9e0df --- /dev/null +++ b/interfaces/innerkits/wantagent/include/want_agent_constant.h @@ -0,0 +1,133 @@ +/* + * 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 BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_CONSTANT_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_CONSTANT_H + +namespace OHOS::AbilityRuntime::WantAgent { +///

+/// Provides enumerated constants that are used for setting object attributes in the methods provided by +/// . +/// +/// +class WantAgentConstant final { + /// + /// Enumerates flags for using an . + /// + /// +public: + enum class Flags { + /// + /// Indicates that the can be used only once. + /// + ONE_TIME_FLAG, + + /// + /// Indicates that {@code null} is returned if the does not exist. + /// + NO_BUILD_FLAG, + + /// + /// Indicates that the existing should be canceled before the new object is + /// generated. + /// + CANCEL_PRESENT_FLAG, + + /// + /// Indicates that the system only replaces the extra data of the existing + /// with that of the new object. + /// + UPDATE_PRESENT_FLAG, + + /// + /// Indicates that the created should be immutable. + /// + CONSTANT_FLAG, + + /// + /// Indicates that the current value of {@code element} can be replaced + /// when the is triggered. + /// + REPLACE_ELEMENT, + + /// + /// Indicates that the current value of {@code action} can be replaced + /// when the is triggered. + /// + REPLACE_ACTION, + + /// + /// Indicates that the current value of {@code uri} can be replaced when the is + /// triggered. + /// + REPLACE_URI, + + /// + /// Indicates that the current value of {@code entities} can be replaced + /// when the is triggered. + /// + REPLACE_ENTITIES, + + /// + /// Indicates that the current value of {@code bundleName} can be replaced + /// when the is triggered. + /// + REPLACE_BUNDLE + }; + + /// + /// Identifies the operation for using an , such as starting an ability or sending a + /// common event. + /// + /// +public: + enum class OperationType { + /// + /// Unknown operation. + /// + UNKNOWN_TYPE, + + /// + /// Starts an ability with a UI. + /// + START_ABILITY, + + /// + /// Starts multiple abilities. + /// + START_ABILITIES, + + /// + /// Starts an ability without a UI. + /// + START_SERVICE, + + /// + /// Sends a common event. + /// + SEND_COMMON_EVENT, + + /// + /// Starts a foreground ability without a UI. + /// + START_FOREGROUND_SERVICE + }; + +private: + WantAgentConstant() {}; + virtual ~WantAgentConstant() = default; +}; +} // namespace OHOS::AbilityRuntime::WantAgent +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_CONSTANT_H diff --git a/interfaces/innerkits/wantagent/include/want_agent_helper.h b/interfaces/innerkits/wantagent/include/want_agent_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..90d93c22f63a8b09e110a9b4e7a5f7526a9f5f32 --- /dev/null +++ b/interfaces/innerkits/wantagent/include/want_agent_helper.h @@ -0,0 +1,199 @@ +/* + * 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 BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_HELPER_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_HELPER_H + +#include +#include +#include "context/context.h" +#include "completed_callback.h" +#include "completed_dispatcher.h" +#include "event_handler.h" +#include "nlohmann/json.hpp" +#include "trigger_info.h" +#include "want.h" +#include "want_agent.h" +#include "want_agent_info.h" +#include "want_params.h" + +namespace OHOS::AbilityRuntime::WantAgent { +/** + * A helper class used to obtain, trigger, cancel, and compare WantAgent objects and to obtain + * the bundle name, UID, and hash code value of an WantAgent object. + * + */ + +static const int FLAG_ONE_SHOT = 1 << 30; +static const int FLAG_NO_CREATE = 1 << 29; +static const int FLAG_CANCEL_CURRENT = 1 << 28; +static const int FLAG_UPDATE_CURRENT = 1 << 27; +static const int FLAG_IMMUTABLE = 1 << 26; +static const int INVLID_WANT_AGENT_USER_ID = -1; + +class WantAgentHelper final : public std::enable_shared_from_this { +public: + /** + * Obtains an WantAgent object. + * The WantAgent class does not have any constructor, and you can only use this method to create an + * WantAgent object. + * + * @param context Indicates the context of the caller. This parameter cannot be null. + * @param paramsInfo Indicates the WantAgentInfo object that contains parameters of the + * WantAgent object to create. + * @return Returns the created WantAgent object. + */ + static std::shared_ptr GetWantAgent( + const std::shared_ptr &context, const WantAgentInfo ¶msInfo); + + /** + * Obtains an WantAgent object. + * + * The WantAgent class does not have any constructor, and you can only use this method to create an + * WantAgent object. + * + * @param paramsInfo Indicates the WantAgentInfo object that contains parameters of the + * WantAgent object to create. + * @param userId Indicates the user id for this wantagent info, default is INVLID_WANT_AGENT_USER_ID(-1). + * @return Returns the created WantAgent object. + */ + static std::shared_ptr GetWantAgent(const WantAgentInfo ¶msInfo, + int32_t userId = INVLID_WANT_AGENT_USER_ID); + + /** + * Obtains an WantAgent object operation type. + * + * @param agent Indicates the WantAgent to trigger. + * @return Returns the created WantAgent object. + */ + static WantAgentConstant::OperationType GetType(const std::shared_ptr &agent); + + /** + * Triggers an WantAgent. + * + * After this method is called, events associated with the specified WantAgent will be executed, + * such as starting an ability or sending a common event. + * + * @param context Indicates the context of the caller. This parameter cannot be null. + * @param agent Indicates the WantAgent to trigger. + * @param onCompleted Indicates the callback method to be called after the WantAgent is triggered. + * This parameter can be null. + * @param handler Indicates the thread for executing the callback indicated by OnCompleted. + * If this parameter is null, the callback method will be executed in a thread in the thread pool of + * the current process. + * @param paramsInfo Indicates the TriggerInfo object that contains triggering parameters. + */ + static void TriggerWantAgent(const std::shared_ptr &agent, + const std::shared_ptr &callback, + const TriggerInfo ¶msInfo); + + /** + * Cancels an WantAgent. + * + * Only the application that creates the WantAgent can cancel it. + * + * @param agent Indicates the WantAgent to cancel. + */ + static void Cancel(const std::shared_ptr &agent); + + /** + * Checks whether two WantAgent objects are the same. + * + * @param agent Indicates one of the WantAgent object to compare. + * @param otherAgent Indicates the other WantAgent object to compare. + * @return Returns true If the two objects are the same; returns false otherwise. + */ + static bool JudgeEquality(const std::shared_ptr &agent, const std::shared_ptr &otherAgent); + + /** + * Obtains the hash code value of an WantAgent. + * + * @param agent Indicates the antAgent whose hash code value is to be obtained. + * @return Returns the hash code value of the WantAgent. + */ + static int GetHashCode(const std::shared_ptr &agent); + + /** + * Obtains the bundle name of an WantAgent. + * + * @param agent Indicates the WantAgent whose bundle name is to be obtained. + * @return Returns the bundle name of the WantAgent if any; returns {@code null} otherwise. + */ + static std::string GetBundleName(const std::shared_ptr &agent); + + /** + * Obtains the user ID (UID) of an WantAgent. + * + * @param agent Indicates the WantAgent whose UID is to be obtained. + * @return Returns the UID of the WantAgent if any; returns -1} otherwise. + */ + static int GetUid(const std::shared_ptr &agent); + + /** + * Obtains the Want WantAgent. + * + * @param agent Indicates the WantAgent whose Want is to be obtained. + * @return Returns the Want of the WantAgent. + */ + static std::shared_ptr GetWant(const std::shared_ptr &agent); + + /** + * Register Cancel function Listener. + * + * @param cancelListener Register listener object. + * @param agent Indicates the WantAgent whose bundle name is to be obtained. + */ + static void RegisterCancelListener( + const std::shared_ptr &cancelListener, const std::shared_ptr &agent); + + /** + * Unregister Cancel function Listener. + * + * @param cancelListener Register listener object. + * @param agent Indicates the WantAgent whose bundle name is to be obtained. + */ + static void UnregisterCancelListener( + const std::shared_ptr &cancelListener, const std::shared_ptr &agent); + + /** + * Convert WantAgentInfo object to json string. + * + * @param jsonObject Json object. + * @return WantAgentInfo object's json string. + */ + static std::string ToString(const std::shared_ptr &agent); + + /** + * Convert json string to WantAgentInfo object. + * + * @param jsonString Json string. + * @return WantAgentInfo object. + */ + static std::shared_ptr FromString(const std::string &jsonString); + +private: + WantAgentHelper(); + virtual ~WantAgentHelper() = default; + +private: + static void Send(const std::shared_ptr &pendingWant, + WantAgentConstant::OperationType type, + const sptr &callBack, + const TriggerInfo ¶msInfo); + + static unsigned int FlagsTransformer(const std::vector &flags); +}; +} // namespace OHOS::AbilityRuntime::WantAgent +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_HELPER_H \ No newline at end of file diff --git a/interfaces/innerkits/wantagent/include/want_agent_info.h b/interfaces/innerkits/wantagent/include/want_agent_info.h new file mode 100644 index 0000000000000000000000000000000000000000..08275dc34486cc0477916880589fc732adefd340 --- /dev/null +++ b/interfaces/innerkits/wantagent/include/want_agent_info.h @@ -0,0 +1,124 @@ +/* + * 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 BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_INFO_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_INFO_H + +#include +#include +#include "want.h" +#include "want_agent_constant.h" +#include "want_params.h" + +namespace OHOS::AbilityRuntime::WantAgent { +/** + * A parametric class that contains the parameters required by WantAgentHelper GetWantAgent. + * + * This class is used to encapsulate parameters requestCode, operationType, + * flag, Wants, and extraInfo. It is used as the input parameter for + * the WantAgentHelper GetWantAgent method. + * + */ +class WantAgentInfo final : public std::enable_shared_from_this { +public: + /** + * Default constructor used to create an empty WantAgentInfo instance. + * + */ + WantAgentInfo(); + virtual ~WantAgentInfo() = default; + + /** + * A constructor used to create an WantAgentInfo instance based on the input parameters. + * + * @param requestCode Indicates the request code to set. It is a private value defined by the user. + * @param operationType Indicates the type of the operation to be performed by the WantAgent object. + * For details about the value range, see WantAgentConstant.OperationType. + * @param flag Indicates the flag for handling the WantAgent. + * For details about the value range, see WantAgentConstant.Flags. + * @param Wants Indicates the collection of Want objects to be used for creating the WantAgent + * object. The number of Wants in the collection is determined by WantAgentConstant.OperationType. + * @param extraInfo Indicates the extra information to be used for creating the WantAgent object. + */ + WantAgentInfo(int requestCode, const WantAgentConstant::OperationType &operationType, WantAgentConstant::Flags flag, + std::vector> &Wants, const std::shared_ptr &extraInfo); + + /** + * A constructor used to create an WantAgentInfo instance based on the input parameters. + * + * @param requestCode Indicates the request code to set. It is a private value defined by the user. + * @param operationType Indicates the type of the operation to be performed by the WantAgent object. + * For details about the value range, see WantAgentConstant.OperationType. + * @param flags Indicates the flags for handling the WantAgent. + * For details about the value range, see WantAgentConstant.Flags. + * @param Wants Indicates the collection of Want objects to be used for creating the WantAgent + * object. The number of Wants in the collection is determined by WantAgentConstant.OperationType. + * @param extraInfo Indicates the extra information to be used for creating the WantAgent object. + */ + WantAgentInfo(int requestCode, const WantAgentConstant::OperationType &operationType, + const std::vector &flags, std::vector> &Wants, + const std::shared_ptr &extraInfo); + + /** + * A constructor used to create an WantAgentInfo instance by copying parameters from an existing one. + * + * @param paramInfo Indicates the existing WantAgentInfo object. + */ + explicit WantAgentInfo(const std::shared_ptr ¶mInfo); + + /** + * Obtains the requestCode of the WantAgent object. + * + * @return Returns the requestCode of the WantAgent object. + */ + int GetRequestCode() const; + + /** + * Obtains the operationType of the WantAgent object. + * + * @return Returns the operationType of the WantAgent object. + */ + WantAgentConstant::OperationType GetOperationType() const; + + /** + * Obtains the flag of the WantAgent object. + * + * @return Returns the flag of the WantAgent object. + */ + std::vector GetFlags() const; + + /** + * Obtains the collection of all Wants of the WantAgent object. + * + * @return Returns the collection of all Wants of the WantAgent object. + */ + std::vector> GetWants() const; + + /** + * Obtains the extra information of the WantAgent object. + * + * @return Returns the extra information of the WantAgent object. + */ + std::shared_ptr GetExtraInfo() const; + +private: + int requestCode_ = 0; + WantAgentConstant::OperationType operationType_ = WantAgentConstant::OperationType::UNKNOWN_TYPE; + std::vector flags_ = std::vector(); + std::vector> wants_ = std::vector>(); + std::shared_ptr extraInfo_; +}; +} // namespace OHOS::AbilityRuntime::WantAgent +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_INFO_H \ No newline at end of file diff --git a/interfaces/innerkits/wantagent/include/want_agent_log_wrapper.h b/interfaces/innerkits/wantagent/include/want_agent_log_wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..8b4506b7de2d669d74859b33510d3dfb66c46ab1 --- /dev/null +++ b/interfaces/innerkits/wantagent/include/want_agent_log_wrapper.h @@ -0,0 +1,68 @@ +/* + * 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 BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_LOG_WRAPPER_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_LOG_WRAPPER_H + +#include +#include "hilog/log.h" + +namespace OHOS::AbilityRuntime::WantAgent { +#ifndef WANT_AGENT_LOG_DOMAIN +#define WANT_AGENT_LOG_DOMAIN 0xD001000 +#endif +#ifndef WANT_AGENT_LOG_TAG +#define WANT_AGENT_LOG_TAG "WantAgent" +#endif + +enum class WantAgentLogLevel { DEBUG = 0, INFO, WARN, ERROR, FATAL }; + +static constexpr OHOS::HiviewDFX::HiLogLabel Want_Agent_LABEL = {LOG_CORE, WANT_AGENT_LOG_DOMAIN, WANT_AGENT_LOG_TAG}; + +class WantAgentLogWrapper { +public: + static bool JudgeLevel(const WantAgentLogLevel &level); + + static void SetLogLevel(const WantAgentLogLevel &level) + { + level_ = level; + } + + static const WantAgentLogLevel &GetLogLevel() + { + return level_; + } + + static std::string GetBriefFileName(const char *str); + +private: + static WantAgentLogLevel level_; +}; + +#define PRINT_LOG(LEVEL, Level, fmt, ...) \ + if (WantAgentLogWrapper::JudgeLevel(WantAgentLogLevel::LEVEL)) \ + OHOS::HiviewDFX::HiLog::Level(Want_Agent_LABEL, \ + "[%{public}s(%{public}s)] " fmt, \ + WantAgentLogWrapper::GetBriefFileName(__FILE__).c_str(), \ + __FUNCTION__, \ + ##__VA_ARGS__) + +#define WANT_AGENT_LOGD(fmt, ...) PRINT_LOG(DEBUG, Debug, fmt, ##__VA_ARGS__) +#define WANT_AGENT_LOGI(fmt, ...) PRINT_LOG(INFO, Info, fmt, ##__VA_ARGS__) +#define WANT_AGENT_LOGW(fmt, ...) PRINT_LOG(WARN, Warn, fmt, ##__VA_ARGS__) +#define WANT_AGENT_LOGE(fmt, ...) PRINT_LOG(ERROR, Error, fmt, ##__VA_ARGS__) +#define WANT_AGENT_LOGF(fmt, ...) PRINT_LOG(FATAL, Fatal, fmt, ##__VA_ARGS__) +} // namespace OHOS::AbilityRuntime::WantAgent +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_LOG_WRAPPER_H diff --git a/interfaces/kits/js/@ohos.ability.dataUriUtils.d.ts b/interfaces/kits/js/@ohos.ability.dataUriUtils.d.ts deleted file mode 100644 index 912ae82a7cfee581cd7b7ce61a4514251f86c655..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/@ohos.ability.dataUriUtils.d.ts +++ /dev/null @@ -1,60 +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. - */ -declare namespace dataUriUtils { - /** - * Obtains the ID attached to the end of the path component of the given URI. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - * @param dataUri Indicates the Uri object from which the ID is to be obtained. - * @return Returns the ID attached to the end of the path component; - * returns -1 if the given dataUri does not contain a path component. - */ - function getIdSync(URI: string): number; - - /** - * Attaches the given ID to the end of the path component of the given URI. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - * @param dataUri Indicates the Uri object to which the ID is to be attached. - * @param id Indicates the ID to attach. - * @return Returns the Uri object with the given ID attached. - */ - function attachIdSync(URI: string, id: number): string; - - /** - * Deletes the ID from the end of the path component of the given URI. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - * @param dataUri Indicates the Uri object from which the ID is to be deleted. - * @return Returns the Uri object with the ID deleted. - */ - function deleteIdSync(URI: string): string; - - /** - * Updates the ID in the specified dataUri. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - * @param dataUri Indicates the Uri object to be updated. - * @param id Indicates the new ID. - * @return Returns the updated Uri object. - */ - function updateIdSync(URI: string, id: number): string; -} - -export default dataUriUtils; \ No newline at end of file diff --git a/interfaces/kits/js/@ohos.ability.featureAbility.d.ts b/interfaces/kits/js/@ohos.ability.featureAbility.d.ts deleted file mode 100644 index d92e73b84042761f75587e8d617bd57bcd14b4f5..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/@ohos.ability.featureAbility.d.ts +++ /dev/null @@ -1,150 +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 } from './basic'; -import { Want } from './ability/want'; -import { StartAbilityParameter } from './ability/startAbilityParameter'; -import { AbilityResult } from './ability/abilityResult'; -import { Context } from './app/context'; -import { DataAbilityHelper } from './ability/dataAbilityHelper'; -import { ConnectOptions } from './ability/connectOptions'; - -/** - * A Feature Ability represents an ability with a UI and is designed to interact with users. - * @name featureAbility - * @since 6 - * @sysCap AAFwk - * @devices phone, tablet - * @permission N/A - */ -declare namespace featureAbility { - /** - * Obtain the want sended from the source ability. - * @devices phone, tablet - * @since 6 - * @sysCap AAFwk - * @param parameter Indicates the ability to start. - * @return - - */ - function getWant(callback: AsyncCallback): void; - function getWant(): Promise; - - /** - * Starts a new ability. - * @devices phone, tablet - * @since 6 - * @sysCap AAFwk - * @param parameter Indicates the ability to start. - * @return - - */ - function startAbility(parameter: StartAbilityParameter, callback: AsyncCallback): void; - function startAbility(parameter: StartAbilityParameter): Promise; - - /** - * Obtains the application context. - * - * @return Returns the application context. - * @since 6 - */ - function getContext(): Context; - - /** - * Starts an ability and returns the execution result when the ability is destroyed. - * @devices phone, tablet - * @since 7 - * @sysCap AAFwk - * @param parameter Indicates the ability to start. - * @return - - */ - function startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback): void; - function startAbilityForResult(parameter: StartAbilityParameter): Promise; - - /** - * Sets the result code and data to be returned by this Page ability to the caller - * and destroys this Page ability. - * @devices phone, tablet - * @since 7 - * @sysCap AAFwk - * @param parameter Indicates the result to return. - * @return - - */ - function terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback): void; - function terminateSelfWithResult(parameter: AbilityResult): Promise; - - /** - * Destroys this Page ability. - * @devices phone, tablet - * @since 7 - * @sysCap AAFwk - * @return - - */ - function terminateSelf(callback: AsyncCallback): void; - - /** - * Obtains the dataAbilityHelper. - * @devices phone, tablet - * @since 7 - * @sysCap AAFwk - * @param uri Indicates the path of the file to open. - * @return Returns the dataAbilityHelper. - */ - function acquireDataAbilityHelper(uri: string): DataAbilityHelper; - - /** - * Checks whether the main window of this ability has window focus. - * @devices phone, tablet - * @since 7 - * @sysCap AAFwk - */ - function hasWindowFocus(callback: AsyncCallback): void; - function hasWindowFocus(): Promise; - - /** - * Connects the current ability to an ability using the AbilityInfo.AbilityType.SERVICE template. - * @default - - * @devices phone, tablet - * @since 7 - * @SysCap aafwk - * @param request The element name of the service ability - * @param options The remote object instance - * @return Returns the number of the ability connected - */ - function connectAbility(request: Want, options:ConnectOptions ): number; - - /** - * The callback interface was connect successfully. - * @default - - * @devices phone, tablet - * @since 7 - * @SysCap aafwk - * @param connection The number of the ability connected - */ - function disconnectAbility(connection: number, callback:AsyncCallback): void; - function disconnectAbility(connection: number): Promise; - - export enum AbilityWindowConfiguration { - WINDOW_MODE_UNDEFINED = 0, - WINDOW_MODE_FULLSCREEN = 1, - WINDOW_MODE_SPLIT_PRIMARY = 100, - WINDOW_MODE_SPLIT_SECONDARY = 101, - WINDOW_MODE_FLOATING = 102 - } - - export enum AbilityStartSetting { - BOUNDS_KEY = "abilityBounds", - WINDOW_MODE_KEY = "windowMode", - DISPLAY_ID_KEY = "displayId" - } -} -export default featureAbility; diff --git a/interfaces/kits/js/@ohos.ability.particleAbility.d.ts b/interfaces/kits/js/@ohos.ability.particleAbility.d.ts deleted file mode 100644 index 44e794c32b5e290c2508cdc4bd16cbaa51bc3ace..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/@ohos.ability.particleAbility.d.ts +++ /dev/null @@ -1,64 +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 } from './basic'; -import { StartAbilityParameter } from './ability/startAbilityParameter'; -import { Want } from './ability/want'; -import { ConnectOptions } from './ability/connectOptions'; - -/** - * A Particle Ability represents an ability with service. - * @name particleAbility - * @since 7 - * @sysCap AAFwk - * @devices phone, tablet - * @permission N/A - */ -declare namespace particleAbility { - - /** - * Service ability uses this method to start a specific ability. - * @devices phone, tablet - * @since 7 - * @sysCap AAFwk - * @param parameter Indicates the ability to start. - * @return - - */ - function startAbility(parameter: StartAbilityParameter, callback: AsyncCallback): void; - function startAbility(parameter: StartAbilityParameter): Promise; - - /** - * Connects the current ability to an ability using the AbilityInfo.AbilityType.SERVICE template. - * @default - - * @devices phone, tablet - * @since 7 - * @SysCap aafwk - * @param request The element name of the service ability - * @param options The remote object instance - * @return Returns the number of the ability connected - */ - function connectAbility(request: Want, options:ConnectOptions ): number; - - /** - * The callback interface was connect successfully. - * @default - - * @devices phone, tablet - * @since 7 - * @SysCap aafwk - * @param connection The number of the ability connected - */ - function disconnectAbility(connection: number, callback:AsyncCallback): void; - function disconnectAbility(connection: number): Promise; -} -export default particleAbility; \ No newline at end of file diff --git a/interfaces/kits/js/@ohos.ability.wantConstant.d.ts b/interfaces/kits/js/@ohos.ability.wantConstant.d.ts deleted file mode 100644 index edae0e993c1c9d4df226b2465058e56bf50b5254..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/@ohos.ability.wantConstant.d.ts +++ /dev/null @@ -1,341 +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. - */ - -/** - * the constant for action and entity in the want - * @name wantConstant - * @since 6 - * @sysCap aafwk - * @devices phone, tablet - * @permission N/A - */ -declare namespace wantConstant { - /** - * the constant for action of the want - * @name Action - * @since 6 - * @sysCap aafwk - * @devices phone, tablet - * @permission N/A - */ - export enum Action { - /** - * Indicates the action of backing home. - * - * @since 1 - */ - ACTION_HOME = "ohos.want.action.home", - - /** - * Indicates the action of starting a Page ability that displays a keypad. - * - * @since 6 - */ - ACTION_DIAL = "ohos.want.action.dial", - - /** - * Indicates the action of starting a Page ability for search. - * - * @since 6 - */ - ACTION_SEARCH = "ohos.want.action.search", - - /** - * Indicates the action of starting a Page ability that provides wireless network settings, for example, - * Wi-Fi options. - * - * @since 6 - */ - ACTION_WIRELESS_SETTINGS = "ohos.settings.wireless", - - /** - * Indicates the action of starting a Page ability that manages installed applications. - * - * @since 6 - */ - ACTION_MANAGE_APPLICATIONS_SETTINGS = "ohos.settings.manage.applications", - - /** - * Indicates the action of starting a Page ability that displays details of a specified application. - * - *

You must specify the application bundle name in the {@code package} attribute of the {@code Intent} - * containing this action. - * - * @since 6 - */ - ACTION_APPLICATION_DETAILS_SETTINGS = "ohos.settings.application.details", - - /** - * Indicates the action of starting a Page ability for setting an alarm clock. - * - * @since 6 - */ - ACTION_SET_ALARM = "ohos.want.action.setAlarm", - - /** - * Indicates the action of starting a Page ability that displays all alarm - * clocks. - * - * @since 6 - */ - ACTION_SHOW_ALARMS = "ohos.want.action.showAlarms", - - /** - * Indicates the action of starting a Page ability for snoozing an alarm clock. - * - * @since 6 - */ - ACTION_SNOOZE_ALARM = "ohos.want.action.snoozeAlarm", - - /** - * Indicates the action of starting a Page ability for deleting an alarm clock. - * - * @since 6 - */ - ACTION_DISMISS_ALARM = "ohos.want.action.dismissAlarm", - - /** - * Indicates the action of starting a Page ability for dismissing a timer. - * - * @since 6 - */ - ACTION_DISMISS_TIMER = "ohos.want.action.dismissTimer", - - /** - * Indicates the action of starting a Page ability for sending a sms. - * - * @since 6 - */ - ACTION_SEND_SMS = "ohos.want.action.sendSms", - - /** - * Indicates the action of starting a Page ability for opening contacts or pictures. - * - * @since 6 - */ - ACTION_CHOOSE = "ohos.want.action.choose", - - /** - * Indicates the action of showing the application selection dialog box. - * - * @since 6 - */ - ACTION_SELECT = "ohos.want.action.select", - - /** - * Indicates the action of sending a single data record. - * - * @since 6 - */ - ACTION_SEND_DATA = "ohos.want.action.sendData", - - /** - * Indicates the action of sending multiple data records. - * - * @since 6 - */ - ACTION_SEND_MULTIPLE_DATA = "ohos.want.action.sendMultipleData", - - /** - * Indicates the action of requesting the media scanner to scan files and adding the files to the media library. - * - * @since 6 - */ - ACTION_SCAN_MEDIA_FILE = "ohos.want.action.scanMediaFile", - - /** - * Indicates the action of viewing data. - * - * @since 6 - */ - ACTION_VIEW_DATA = "ohos.want.action.viewData", - - /** - * Indicates the action of editing data. - * - * @since 6 - */ - ACTION_EDIT_DATA = "ohos.want.action.editData", - - /** - * Indicates the choices you will show with {@link #ACTION_PICKER}. - * - * @since 6 - */ - INTENT_PARAMS_INTENT = "ability.want.params.INTENT", - - /** - * Indicates the CharSequence dialog title when used with a {@link #ACTION_PICKER}. - * - * @since 6 - */ - INTENT_PARAMS_TITLE = "ability.want.params.TITLE", - - /** - * Indicates the action of select file. - * - * @since 7 - */ - ACTION_FILE_SELECT = "ohos.action.fileSelect", - - /** - * Indicates the URI holding a stream of data associated with the Intent when used with a {@link #ACTION_SEND_DATA}. - * - * @since 7 - */ - PARAMS_STREAM = "ability.params.stream", - } - - /** - * the constant for Entity of the want - * @name Action - * @since 6 - * @sysCap aafwk - * @devices phone, tablet - * @permission N/A - */ - export enum Entity { - /** - * Indicates the default entity, which is used if the entity is not specified. - * - * @since 6 - */ - ENTITY_DEFAULT = "entity.system.default", - - /** - * Indicates the home screen entity. - * - * @since 6 - */ - ENTITY_HOME = "entity.system.home", - - /** - * Indicates the voice interaction entity. - * - * @since 6 - */ - ENTITY_VOICE = "entity.system.voice", - - /** - * Indicates the browser category. - * - * @since 6 - */ - ENTITY_BROWSABLE = "entity.system.browsable", - - /** - * Indicates the video category. - */ - ENTITY_VIDEO = "entity.system.video" - } - - export enum Flags { - /** - * Indicates the grant to perform read operations on the URI. - * - * @hide - */ - FLAG_AUTH_READ_URI_PERMISSION = 0x00000001, - - /** - * Indicates the grant to perform write operations on the URI. - * - * @hide - */ - FLAG_AUTH_WRITE_URI_PERMISSION = 0x00000002, - - /** - * Returns the result to the source ability. - */ - FLAG_ABILITY_FORWARD_RESULT = 0x00000004, - - /** - * Determines whether an ability on the local device can be migrated to a remote device. - */ - FLAG_ABILITY_CONTINUATION = 0x00000008, - - /** - * Specifies whether a component does not belong to OHOS. - */ - FLAG_NOT_OHOS_COMPONENT = 0x00000010, - - /** - * Specifies whether an ability is started. - */ - FLAG_ABILITY_FORM_ENABLED = 0x00000020, - - /** - * Indicates the grant for possible persisting on the URI. - * - * @hide - */ - FLAG_AUTH_PERSISTABLE_URI_PERMISSION = 0x00000040, - - /** - * Returns the result to the source ability slice. - * - * @hide - */ - FLAG_AUTH_PREFIX_URI_PERMISSION = 0x00000080, - - /** - * Supports multi-device startup in the distributed scheduling system. - */ - FLAG_ABILITYSLICE_MULTI_DEVICE = 0x00000100, - - /** - * Indicates that an ability using the Service template is started regardless of whether the host application has - * been started. - */ - FLAG_START_FOREGROUND_ABILITY = 0x00000200, - - /** - * Indicates the continuation is reversible. - * - * @hide - */ - FLAG_ABILITY_CONTINUATION_REVERSIBLE = 0x00000400, - - /** - * Install the specified ability if it's not installed. - */ - FLAG_INSTALL_ON_DEMAND = 0x00000800, - - /** - * Install the specifiedi ability with background mode if it's not installed. - */ - FLAG_INSTALL_WITH_BACKGROUND_MODE = 0x80000000, - - /** - * Indicates the operation of clearing other missions. This flag can be set for the {@code Intent} passed to - * {@link ohos.app.Context#startAbility} and must be used together with {@link FLAG_ABILITY_NEW_MISSION}. - */ - FLAG_ABILITY_CLEAR_MISSION = 0x00008000, - - /** - * Indicates the operation of creating a task on the historical mission stack. - */ - FLAG_ABILITY_NEW_MISSION = 0x10000000, - - /** - * Indicates that the existing instance of the ability to start will be reused if it is already at the top of - * the mission stack. Otherwise, a new ability instance will be created. - * - */ - FLAG_ABILITY_MISSION_TOP = 0x20000000 - } -} - -export default wantConstant; \ No newline at end of file diff --git a/interfaces/kits/js/@ohos.app.abilityManager.d.ts b/interfaces/kits/js/@ohos.app.abilityManager.d.ts deleted file mode 100644 index 8bec57baa5f2a473ed744824999f645e61eba59a..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/@ohos.app.abilityManager.d.ts +++ /dev/null @@ -1,83 +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 } from './basic'; -import { AbilityMissionInfo } from './app/abilityMissionInfo'; -import { ActiveProcessInfo } from './app/activeProcessInfo'; - -/** - * This module provides the capability to manage abilities and obtaining system task information. - * - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @devices phone, tablet, tv, wearable, car - * @import import abilityManager from '@ohos.app.abilityManager' - * @permission N/A - */ -declare namespace abilityManager { - - /** - * Get information about running processes - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @devices phone, tablet, tv, wearable, car - * @return a list of ActiveProcessInfo records describing each process. - * @permission ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION - * @systemapi hide this for inner system use - */ - function getActiveProcessInfos(): Promise>; - function getActiveProcessInfos(callback: AsyncCallback>): void; - - /** - * Get information about the running ability missions - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @devices phone, tablet, tv, wearable, car - * @param upperLimit The maximum number of mission infos to return in the array. - * @return an array of AbilityMissionInfo records describing each active mission. - * @permission ohos.permission.ACCESS_MISSIONS - * @systemapi hide this for inner system use - */ - function getActiveAbilityMissionInfos(upperLimit: number): Promise>; - function getActiveAbilityMissionInfos(upperLimit: number, callback: AsyncCallback>): void; - - /** - * Get information about recently run missions - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @devices phone, tablet, tv, wearable, car - * @param upperLimit The maximum number of previous mission infos to return in the array. - * @return an array of AbilityMissionInfo records describing each of the previous mission. - * @permission ohos.permission.ACCESS_MISSIONS_EXTRA - * @systemapi hide this for inner system use - */ - function getPreviousAbilityMissionInfos(upperLimit: number): Promise>; - function getPreviousAbilityMissionInfos(upperLimit: number, callback: AsyncCallback>): void; - - /** - * Delete the specified missions - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @devices phone, tablet, tv, wearable, car - * @param missionIds An array of missions, representing the missions that need to be deleted. - * @permission ohos.permission.DELETE_MISSIONS - * @systemapi hide this for inner system use - */ - function deleteMissions(missionIds: Array): Promise; - function deleteMissions(missionIds: Array, callback: AsyncCallback): void; - -} - -export default abilityManager; diff --git a/interfaces/kits/js/@ohos.application.DataShareExtAbility.d.ts b/interfaces/kits/js/@ohos.application.DataShareExtAbility.d.ts deleted file mode 100644 index 4e9c950410bf29f6b5a263a2799e4e08ce27ab9d..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/@ohos.application.DataShareExtAbility.d.ts +++ /dev/null @@ -1,192 +0,0 @@ -/* - * 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/js/@ohos.bundle.d.ts b/interfaces/kits/js/@ohos.bundle.d.ts deleted file mode 100644 index 6e9ff46b8dd0f24117db7d1e9e90e67c34a60ac6..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/@ohos.bundle.d.ts +++ /dev/null @@ -1,347 +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'; -import { ApplicationInfo } from './bundle/applicationInfo'; -import { BundleInfo } from './bundle/bundleInfo'; -import { AbilityInfo } from './bundle/abilityInfo'; -import { Want } from './ability/want'; -import { BundleInstaller } from './bundle/bundleInstaller'; -import { ElementName } from './bundle/elementName'; -import { ShortcutInfo } from './bundle/shortcutInfo'; -import { ModuleUsageRecord } from './bundle/moduleUsageRecord'; - -/** - * bundle. - * @name bundle - * @since 7 - * @sysCap SystemCapability.Appexecfwk - * @devices phone, tablet, tv, wearable - * @permission NA - */ -declare namespace bundle { - -/** - * @name BundleFlag - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @import NA - * @permission NA - * @devices phone, tablet, tv, wearable - */ - enum BundleFlag { - GET_BUNDLE_DEFAULT = 0x00000000, - GET_BUNDLE_WITH_ABILITIES = 0x00000001, - GET_APPLICATION_INFO_WITH_PERMISSION = 0x00000008, - } - -/** - * @name GrantStatus - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @import NA - * @permission NA - * @devices phone, tablet, tv, wearable - */ - export enum GrantStatus { - PERMISSION_DENIED = -1, - PERMISSION_GRANTED = 0, - } - - /** - * @name AbilityType - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @import NA - * @permission NA - * @devices phone, tablet, tv, wearable - */ - export enum AbilityType { - /** - * @default Indicates an unknown ability type - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - UNKNOWN, - - /** - * @default Indicates that the ability has a UI - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - PAGE, - - /** - * @default Indicates that the ability does not have a UI - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - SERVICE, - - /** - * @default Indicates that the ability is used to provide data access services - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - DATA, - } - - /** - * @name AbilitySubType - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @import NA - * @permission NA - * @devices phone, tablet, tv, wearable - */ - export enum AbilitySubType { - UNSPECIFIED = 0, - CA = 1, - } - - /** - * @name DisplayOrientation - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @import NA - * @permission NA - * @devices phone, tablet, tv, wearable - */ - export enum DisplayOrientation { - /** - * @default Indicates that the system automatically determines the display orientation - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - UNSPECIFIED, - - /** - * @default Indicates the landscape orientation - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - LANDSCAPE, - - /** - * @default Indicates the portrait orientation - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - PORTRAIT, - - /** - * @default Indicates the page ability orientation is the same as that of the nearest ability in the stack - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - FOLLOW_RECENT, - } - - /** - * @name LaunchMode - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @import NA - * @permission NA - * @devices phone, tablet, tv, wearable - */ - export enum LaunchMode { - /** - * @default Indicates that the ability has only one instance - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - SINGLETON = 0, - - /** - * @default Indicates that the ability can have multiple instances - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - STANDARD = 1, - } - - /** - * @name InstallErrorCode - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @import NA - * @permission NA - * @devices phone, tablet, tv, wearable - */ - export enum InstallErrorCode{ - SUCCESS = 0, - STATUS_INSTALL_FAILURE = 1, - STATUS_INSTALL_FAILURE_ABORTED = 2, - STATUS_INSTALL_FAILURE_INVALID = 3, - STATUS_INSTALL_FAILURE_CONFLICT = 4, - STATUS_INSTALL_FAILURE_STORAGE = 5, - STATUS_INSTALL_FAILURE_INCOMPATIBLE = 6, - STATUS_UNINSTALL_FAILURE = 7, - STATUS_UNINSTALL_FAILURE_BLOCKED = 8, - STATUS_UNINSTALL_FAILURE_ABORTED = 9, - STATUS_UNINSTALL_FAILURE_CONFLICT = 10, - STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT = 0x0B, - STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED = 0x0C, - STATUS_ABILITY_NOT_FOUND = 0x40, - STATUS_BMS_SERVICE_ERROR = 0x41 - } - - /** - * Obtains based on a given networkId and bundle name. - * - * @devices phone, tablet, tv, wearable - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @param networkId Indicates the device networkId in area network. - * @param bundleName Indicates the application bundle name to be queried. - * @param flags Indicates the flag used to specify information contained in that will be - * returned. - * @return Returns the BundleInfo object. - * @permission ohos.permission.GET_BUNDLE_INFO_PRIVILEGED,ohos.permission.GET_BUNDLE_INFO - */ - function getBundleInfo(bundleName: string, bundleFlags: number, callback: AsyncCallback): void; - function getBundleInfo(bundleName: string, bundleFlags: number): Promise; - - /** - * Obtains the interface used to install bundles. - * - * @devices phone, tablet, tv, wearable - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @return Returns the IBundleInstaller interface. - * @permission ohos.permission.INSTALL_BUNDLE - */ - function getBundleInstaller(callback: AsyncCallback): void; - function getBundleInstaller(): Promise; - - /** - * Obtains based on a given bundle name. - * - * @devices phone, tablet, tv, wearable - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @param bundleName Indicates the application bundle name to be queried. - * @param flags Indicates the flag used to specify information contained in the ApplicationInfo object - * that will be returned. - * @param userId Indicates the user ID. - * @return Returns the ApplicationInfo object. - * @permission ohos.permission.GET_BUNDLE_INFO_PRIVILEGED, ohos.permission.GET_BUNDLE_INFO - */ - function getApplicationInfo(bundleName: string, bundleFlags: number, userId: number, callback: AsyncCallback) : void; - function getApplicationInfo(bundleName: string, bundleFlags: number, userId: number) : Promise; - - /** - * Checks whether a specified bundle has been granted a specific permission. - * - * @devices phone, tablet, tv, wearable - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @param bundleName Indicates the name of the bundle to check. - * @param permission Indicates the permission to check. - * @return Returns 0 if the bundle has the permission; returns -1 otherwise. - */ - function checkPermission(bundleName: string, permission: string, callback: AsyncCallback): void; - function checkPermission(bundleName: string, permission: string): Promise; - - /** - * Query the AbilityInfo by the given Want. - * - * @devices phone, tablet, tv, wearable - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @param intent Indicates the Intent containing the application bundle name to - * be queried. - * @param flags Indicates the flag used to specify information contained in the AbilityInfo objects that - * will be returned. - * @param userId Indicates the user ID. - * @return Returns a list of AbilityInfo objects. - * @permission ohos.permission.GET_BUNDLE_INFO_PRIVILEGED, ohos.permission.GET_BUNDLE_INFO - */ - function queryAbilityByWant(want: Want, bundleFlags: number, userId: number, callback: AsyncCallback>): void; - function queryAbilityByWant(want: Want, bundleFlags: number, userId:number): Promise>; - - /** - * Obtains BundleInfo of all bundles available in the system. - * - * @devices phone, tablet, tv, wearable - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @param flags Indicates the flag used to specify information contained in the BundleInfo that will be - * returned. - * @return Returns a list of BundleInfo objects. - * @permission ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - */ - function getAllBundleInfo(bundlelFlag: BundleFlag, callback: AsyncCallback>) : void; - function getAllBundleInfo(bundlelFlag: BundleFlag) : Promise>; - - /** - * Obtains information about all installed applications of a specified user. - * - * @devices phone, tablet, tv, wearable - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @param flags Indicates the flag used to specify information contained in the ApplicationInfo objects - * that will be returned. - * @param userId Indicates the user ID. - * @return Returns a list of ApplicationInfo objects. - * @permission ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - */ - function getAllApplicationInfo(bundleFlags: number, userId: number, callback: AsyncCallback>) : void; - function getAllApplicationInfo(bundleFlags: number, userId: number) : Promise>; - - /** - * Obtains information about an application bundle contained in an ohos Ability Package (HAP). - * - * @devices phone, tablet, tv, wearable - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @param hapFilePath Indicates the path storing the HAP. The path should be the relative path to the data - * directory of the current application. - * @param flags Indicates the flag used to specify information contained in the BundleInfo object to be - * returned. - * @return Returns the BundleInfo object. - */ - function getBundleArchiveInfo(hapFilePath: string, bundleFlags: number, callback: AsyncCallback) : void - function getBundleArchiveInfo(hapFilePath: string, bundleFlags: number) : Promise; - - /** - * Obtains information about the shortcuts of the application. - * - * @devices phone, tablet, tv, wearable - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @param bundleName Indicates the bundle name of the application. - * @return Returns a list of ShortcutInfo objects containing shortcut information about the application. - * @permission ohos.permission.MANAGE_SHORTCUTS - */ - function getAllShortcutInfo(bundleName: string, callback: AsyncCallback>): void; - function getAllShortcutInfo(bundleName: string): Promise>; - - /** - * get module usage record list in descending order of lastLaunchTime. - * - * @devices phone, tablet, tv, wearable - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @param maxNum the return size of the records, must be in range of 1 to 1000. - * @return Returns ability usage record list. - * @systemapi hide this for inner system use - */ - function getModuleUsageRecords(maxNum: number, callback: AsyncCallback>): void; - function getModuleUsageRecords(maxNum: number): Promise>; -} - -export default bundle; diff --git a/interfaces/kits/js/ability/connectOptions.d.ts b/interfaces/kits/js/ability/connectOptions.d.ts deleted file mode 100644 index c718f678c3b1a8efde126c16d3378e9e0a91ebf8..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/ability/connectOptions.d.ts +++ /dev/null @@ -1,52 +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 { ElementName } from '../bundle/elementName'; -import rpc from './../@ohos.rpc'; - -export interface ConnectOptions { - /** - * The callback interface was connect successfully. - * - * @default - - * @devices phone, tablet - * @since 7 - * @SysCap aafwk - * @param elementName The element name of the service ability - * @param remoteObject The remote object instance - */ - onConnect: (elementName: ElementName, remoteObject: RemoteObject) => void; - - /** - * The callback interface was disconnect successfully. - * - * @default - - * @devices phone, tablet - * @since 7 - * @SysCap aafwk - * @param elementName The element name of the service ability - */ - onDisconnect: (elementName: ElementName) => void; - - /** - * The callback interface was connect failed. - * - * @default - - * @devices phone, tablet - * @since 7 - * @SysCap aafwk - * @param code The error code of the failed. - */ - onFailed: (code: number) => void; -} diff --git a/interfaces/kits/js/ability/dataAbilityHelper.d.ts b/interfaces/kits/js/ability/dataAbilityHelper.d.ts deleted file mode 100644 index 71dd47e5b0ffb35ee89462c8dde7a5307cae20d5..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/ability/dataAbilityHelper.d.ts +++ /dev/null @@ -1,224 +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 } from './../basic'; -import { DataAbilityOperation } from './dataAbilityOperation'; -import { ValuesBucket, ResultSet, DataAbilityPredicates } from './../@ohos.data.rdb'; - -/** - * DataAbilityHelper - * @devices phone, tablet - * - * @since 7 - */ -export interface DataAbilityHelper { - /** - * Opens a file in a specified remote path. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - * @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. - * @param callback Indicates the callback when openfile success - */ - openFile(uri: string, mode: string, callback: AsyncCallback): void; - openFile(uri: string, mode: string): Promise; - - /** - * Registers an observer to observe data specified by the given uri. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - * @param type dataChange. - * @param uri Indicates the path of the data to operate. - * @param callback Indicates the callback when dataChange. - */ - on(type: 'dataChange', uri: string, callback: AsyncCallback): void; - - /** - * Deregisters an observer used for monitoring data specified by the given uri. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - * @param type dataChange. - * @param uri Indicates the path of the data to operate. - * @param callback Indicates the registered callback. - */ - off(type: 'dataChange', uri: string, callback?: AsyncCallback): void; - - /** - * Inserts a single data record into the database. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - * @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. - */ - insert(URI: string, values: ValuesBucket, callback: AsyncCallback): void; - insert(URI: string, values: ValuesBucket): Promise; - - /** - * Deletes one or more data records from the database. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - * @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. - */ - delete(URI: string, predicates: DataAbilityPredicates, callback: AsyncCallback): void; - delete(URI: string, predicates: DataAbilityPredicates): Promise; - - /** - * Queries data in the database. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - * @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. - */ - query(URI: string, columns: Array, predicates: DataAbilityPredicates, callback: AsyncCallback): void; - query(URI: string, columns: Array, predicates: DataAbilityPredicates): Promise; - - /** - * Updates data records in the database. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - * @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. - */ - update(URI: string, values: ValuesBucket, predicates: DataAbilityPredicates, callback: AsyncCallback): void; - update(URI: string, values: ValuesBucket, predicates: DataAbilityPredicates): Promise; - - /** - * Inserts multiple data records into the database. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - * @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. - */ - batchInsert(URI: string, values: Array, callback: AsyncCallback): void; - batchInsert(URI: string, values: Array): Promise; - - /** - * Performs batch operations on the database. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - * @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. - */ - executeBatch(URI: string, operations: Array, callback: AsyncCallback>): void; - executeBatch(URI: string, operations: Array): Promise>; - - /** - * Obtains the MIME type of the date specified by the given URI. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - * @param uri Indicates the path of the data to operate. - * @return Returns the MIME type that matches the data specified by uri. - */ - getType(URI: string, callback: AsyncCallback): void; - getType(URI: string): Promise; - - /** - * Obtains the MIME types of files supported. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - * @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. - *

1. "*/*": Obtains all types supported by Data abilities. - *

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 matched MIME types. If there is no match, {@code null} is returned. - */ - getFileTypes(uri: string, mimeTypeFilter:string, callback: AsyncCallback>): void; - getFileTypes(uri: string, mimeTypeFilter): Promise>; - - /** - * Converts the given {@code uri} that refers to the Data ability into a normalized {@link ohos.utils.net.Uri}. - * A normalized URI can be used across devices, persisted, backed up, and restored. - *

To transfer a normalized URI from another environment to the current environment, you should call this - * method again to re-normalize the URI for the current environment or call {@link #denormalizeUri(Uri)} - * to convert it to a denormalized URI that can be used only in the current environment. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - * @param uri Indicates the {@link ohos.utils.net.Uri} object to normalize. - * @return Returns the normalized {@code Uri} object if the Data ability supports URI normalization; - * returns {@code null} otherwise. - * @throws DataAbilityRemoteException Throws this exception if the remote process exits. - * @throws NullPointerException Throws this exception if {@code uri} is null. - * @see #denormalizeUri - */ - normalizeUri(uri: string, callback: AsyncCallback): void; - normalizeUri(uri: string): Promise; - - /** - * Converts the given normalized {@code uri} generated by {@link #normalizeUri(Uri)} into a denormalized one. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - * @param uri Indicates the {@link ohos.utils.net.Uri} object 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 normalized {@code Uri} cannot be found in the current environment. - * @throws DataAbilityRemoteException Throws this exception if the remote process exits. - * @throws NullPointerException Throws this exception if {@code uri} is null. - * @see #normalizeUri - */ - denormalizeUri(uri: string, callback: AsyncCallback): void; - denormalizeUri(uri: string): Promise; - - /** - * Releases the client resource of the Data ability. - *

You should call this method to releases client resource after the data operations are complete.

- * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - * @return Returns {@code true} if the resource is successfully released; returns {@code false} otherwise. - */ - release(callback: AsyncCallback): void; - release(): Promise; - - /** - * Notifies the registered observers of a change to the data resource specified by Uri. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - * @param uri Indicates the {@link ohos.utils.net.Uri} object to notifyChange. - */ - notifyChange(URI: string, callback: AsyncCallback): void; - notifyChange(URI: string): Promise; -} - -export interface DataAbilityResult { - uri?: string; - count?: number; -} \ No newline at end of file diff --git a/interfaces/kits/js/ability/dataAbilityOperation.d.ts b/interfaces/kits/js/ability/dataAbilityOperation.d.ts deleted file mode 100644 index 99074f992c94b0f68a978e5cbc065d9c87271bed..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/ability/dataAbilityOperation.d.ts +++ /dev/null @@ -1,107 +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 { ValuesBucket, DataAbilityPredicates } from './../@ohos.data.rdb'; - -/** - * Performs an operation on the database. - * @devices phone, tablet - * - * @since 7 - */ -export interface DataAbilityOperation { - /** - * Obtains the data path of the operation. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - */ - uri: string; - /** - * Creates a DataAbilityOperation instance. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - */ - type: DataAbilityOperationType; - /** - * Sets the data records to be inserted or updated. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - */ - valuesBucket: ValuesBucket; - /** - * Sets filter criteria used for deleting updating or assert query data. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - */ - predicates: DataAbilityPredicates; - /** - * Sets the expected number of rows to update ,delete or assert query. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - */ - expectedCount: number; - /** - * Back reference to be used as a filter criterion in setPredicates(DataAbilityPredicates). - * This method can be used only for update, delete, and assert operations. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - */ - PredicatesBackReferences: {[key: number]: any}; - /** - * Sets an interrupt flag bit for a batch operation, which can be insert, update, delete, or assert. - * - * interrupted Specifies whether a batch operation can be interrupted. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - */ - interrupted: boolean; -} - -export enum DataAbilityOperationType { - /** - * Indicates an insert operation. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - */ - TYPE_INSERT = 1, - /** - * Indicates an update operation. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - */ - TYPE_UPDATE = 2, - /** - * Indicates a delete operation. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - */ - TYPE_DELETE = 3, - /** - * Indicates an assert operation. - * @devices phone, tablet - * @since 7 - * @SysCap AAFwk - */ - TYPE_ASSERT = 4 -} \ No newline at end of file diff --git a/interfaces/kits/js/ability/want.d.ts b/interfaces/kits/js/ability/want.d.ts deleted file mode 100644 index af2183ded2e6bd1db19f78012e18925d70a88482..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/ability/want.d.ts +++ /dev/null @@ -1,105 +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. - */ - -/** - * Want is the basic communication component of the system. - * @name Want - * @since 6 - * @sysCap AAFwk - * @devices phone, tablet - * @permission N/A - */ -export declare interface Want { - /** - * device id - * @default - - * @devices phone, tablet - * @since 6 - * @sysCap AAFwk - */ - deviceId?: string; - - /** - * bundle name - * @default - - * @devices phone, tablet - * @since 6 - * @sysCap AAFwk - */ - bundleName?: string; - - /** - * ability name - * @default - - * @devices phone, tablet - * @since 6 - * @sysCap AAFwk - */ - abilityName?: string; - - /** - * The description of a URI in a Want. - * @devices phone, tablet - * @since 6 - * @sysCap AAFwk - * @default - - */ - uri?: string; - - /** - * The description of the type in this Want. - * @devices phone, tablet - * @since 6 - * @sysCap AAFwk - * @default - - */ - type?: string; - - /** - * The options of the flags in this Want. - * @devices phone, tablet - * @since 6 - * @sysCap AAFwk - * @default - - */ - flags?: number; - - /** - * The description of an action in an want. - * @devices phone, tablet - * @since 6 - * @sysCap AAFwk - * @default - - */ - action?: string; - - /** - * The description of the WantParams object in an Want - * @devices phone, tablet - * @since 6 - * @sysCap AAFwk - * @default - - */ - parameters?: {[key: string]: any}; - - /** - * The description of a entities in a Want. - * @devices phone, tablet - * @since 6 - * @sysCap AAFwk - * @default - - */ - entities?: Array; -} \ No newline at end of file diff --git a/interfaces/kits/js/app/context.d.ts b/interfaces/kits/js/app/context.d.ts deleted file mode 100755 index 4ccb5f05a9e4a752bf90763c4e5971f647c78ae0..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/app/context.d.ts +++ /dev/null @@ -1,105 +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 } from '../basic'; - -/** - * The context of an ability or an application. It allows access to - * application-specific resources, request and verification permissions. - * Can only be obtained through the ability. - * - * @since 6 - * @SysCap SystemCapability.Appexecfwk - * @devices phone, tablet, tv, wearable, car - * @import import abilityManager from 'app/context' - * @permission N/A - */ -export interface Context { - - /** - * Verify whether the specified permission is allowed for a particular - * pid and uid running in the system. - * @param permission The name of the specified permission - * @param pid process id - * @param uid user id - * @note Pid and uid are optional. If you do not pass in pid and uid, - * it will check your own permission. - * @since 7 - * @sysCap SystemCapability.Appexecfwk - * @devices phone, tablet, tv, wearable, car - * @return asynchronous callback with {@code 0} if the PID - * and UID have the permission; callback with {@code -1} otherwise. - */ - verifyPermission(permission: string, options?: PermissionOptions): Promise; - verifyPermission(permission: string, options: PermissionOptions, callback: AsyncCallback): void; - verifyPermission(permission: string, callback: AsyncCallback): void; - - /** - * Requests certain permissions from the system. - * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. - * @param requestCode Indicates the request code to be passed to the PermissionRequestResult - * @since 7 - * @sysCap SystemCapability.Appexecfwk - * @devices phone, tablet, tv, wearable, car - */ - requestPermissionsFromUser(permissions: Array, requestCode: number, resultCallback: AsyncCallback): void; - -} - -/** - * @name the result of requestPermissionsFromUser with asynchronous callback - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @permission N/A - * @devices phone, tablet, tv, wearable, car - */ -interface PermissionRequestResult { - /** - * @default The request code passed in by the user - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - requestCode: number; - - /** - * @default The permissions passed in by the user - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - permissions: Array; - - /** - * @default The results for the corresponding request permissions - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - authResults: Array; -} - -interface PermissionOptions { - /** - * @default The process id - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - pid?: number; - - /** - * @default The user id - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - uid?: number; -} diff --git a/interfaces/kits/js/app/memoryMapInfo.d.ts b/interfaces/kits/js/app/memoryMapInfo.d.ts deleted file mode 100755 index 4c8ab45c3b155c201176f31110ec74321d132fd6..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/app/memoryMapInfo.d.ts +++ /dev/null @@ -1,63 +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. - */ - -/** - * @name This class saves memory map information about an application. - * All results are in kB. - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @import import MemoryMapInfo from 'app/memoryMapInfo' - * @permission N/A - * @devices phone, tablet, tv, wearable, car - * @systemapi hide this for inner system use - */ -export interface MemoryMapInfo { - /** - * @default The pss page size for virtual machine heap - */ - vmPss: number; - /** - * @default The private dirty page size for virtual machine heap - */ - vmPrivateDirty: number; - /** - * @default The shared dirty page size for virtual machine heap - */ - vmSharedDirty: number; - /** - * @default The pss page size for native heap - */ - nativePss: number; - /** - * @default The private dirty page size for native heap - */ - nativePrivateDirty: number; - /** - * @default The shared dirty page size for native heap - */ - nativeSharedDirty: number; - /** - * @default The pss page size for others - */ - otherPss: number; - /** - * @default The private dirty page size for others - */ - otherPrivateDirty: number; - /** - * @default The shared dirty page size for others - */ - otherSharedDirty: number; -} diff --git a/interfaces/kits/js/app/splitMissionInfo.d.ts b/interfaces/kits/js/app/splitMissionInfo.d.ts deleted file mode 100755 index 6f911d73360797172a3568e41575f217cfb5d910..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/app/splitMissionInfo.d.ts +++ /dev/null @@ -1,47 +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 { RectBounds } from '../wallpaper'; - -/** - * @name This class is the input param for { moveMissionToFirstSplitScreen }. - * @since 7 - * @SysCap appexecfwk - * @import import app from 'app/splitMissionInfo' - * @devices phone, tablet - * @systemapi hide this for inner system use - */ -export interface SplitMissionInfo { - /** - * @default the mission id that you want to move - */ - missionId: number; - /** - * @default whether the target window is the first one - */ - isFirstWindow: boolean; - /** - * @default whether to move the mission to top - */ - isToTop: boolean; - /** - * @default Whether you want an animation when moving the task - */ - isAnimating: boolean; - /** - * @default The bounds of the split window - */ - initialBounds: RectBounds; -} diff --git a/interfaces/kits/js/bundle/abilityInfo.d.ts b/interfaces/kits/js/bundle/abilityInfo.d.ts deleted file mode 100644 index 7e6904ab2e9b5334be520f325e11a744210dd70b..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/bundle/abilityInfo.d.ts +++ /dev/null @@ -1,244 +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 { ApplicationInfo } from './applicationInfo'; -import { CustomizeData } from './customizeData' -import bundle from './../@ohos.bundle'; - -/** - * @name Obtains configuration information about an ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @permission NA - * @devices phone, tablet, tv, wearable, car - */ -export interface AbilityInfo { - /** - * @default Indicates the name of the bundle containing the ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly bundleName: string; - - /** - * @default Ability simplified class name - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly name: string; - - /** - * @default Indicates the label of the ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly label: string; - - /** - * @default Describes the ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly description: string; - - /** - * @default Indicates the icon of the ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly icon: string; - - /** - * @default Indicates the label id of the ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly labelId: number; - - /** - * @default Indicates the description id of the ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly descriptionId: number; - - /** - * @default Indicates the icon id of the ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly iconId: number; - - /** - * @default Indicates the name of the .hap package to which the capability belongs - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly moduleName: string; - - /** - * @default Process of ability, if user do not set it ,the value equal application process - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly process: string; - - /** - * @default Info about which ability is this nick point to - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly targetAbility: string; - - /** - * @default Indicates the background service addressing a specific usage scenario - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly backgroundModes: number; - - /** - * @default Indicates whether an ability can be called by other abilities - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly isVisible: boolean; - - /** - * @default Indicates whether the ability provides the embedded card capability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly formEnabled: boolean; - - /** - * @default Enumerates types of templates that can be used by an ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly type: bundle.AbilityType; - - /** - * @default Enumerates the subType of templates used by an ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly subType: bundle.AbilitySubType; - - /** - * @default Enumerates ability display orientations - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly orientation: bundle.DisplayOrientation; - - /** - * @default Enumerates ability launch modes - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly launchMode: bundle.LaunchMode; - - /** - * @default The permissions that others need to launch this ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly permissions: Array; - - /** - * @default The device types that this ability can run on - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly deviceTypes: Array; - - /** - * @default The device capability that this ability needs - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly deviceCapabilities: Array; - - /** - * @default Indicates the permission required for reading ability data - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly readPermission: string; - - /** - * @default Indicates the permission required for writing data to the ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly writePermission: string; - - /** - * @default Obtains configuration information about an application - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly applicationInfo: ApplicationInfo; - - /** - * @default Where form can be displayed - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly formEntity: number; - - /** - * @default Minimum height of ability. - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly minFormHeight: number; - - /** - * @default Default height of ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly defaultFormHeight: number; - - /** - * @default Minimum width of ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly minFormWidth: number; - - /** - * @default Default width of ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly defaultFormWidth: number; - - /** - * @default Uri of ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly uri: string; - - /** - * @default Indicates the custom metadata of ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - customizeData: Map>; -} diff --git a/interfaces/kits/js/bundle/applicationInfo.d.ts b/interfaces/kits/js/bundle/applicationInfo.d.ts deleted file mode 100644 index 4820474ef88f0c61f354a0d1d1d1c1cd6068d7bc..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/bundle/applicationInfo.d.ts +++ /dev/null @@ -1,138 +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 { ModuleInfo } from './moduleInfo'; -import { CustomizeData } from './customizeData' - -/** - * @name Obtains configuration information about an application - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @permission NA - * @devices phone, tablet, tv, wearable, car - */ -export interface ApplicationInfo { - /** - * @default Indicates the application name, which is the same as {@code bundleName} - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly name: string; - - /** - * @default Description of application - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly description: string; - - /** - * @default Indicates the description id of the application - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly descriptionId: number; - - /** - * @default Indicates whether the application is a system application - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly systemApp: boolean; - - /** - * @default Indicates whether or not this application may be instantiated - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly enabled: boolean; - - /** - * @default Indicates the label of the application - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly label: string; - - /** - * @default Indicates the label id of the application - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly labelId: string; - - /** - * @default Indicates the icon of the application - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly icon: string; - - /** - * @default Indicates the icon id of the application - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly iconId: string; - - /** - * @default Process of application, if user do not set it ,the value equal bundleName - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly process: string; - - /** - * @default Indicates the running mode supported by the application - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly supportedModes: number; - - /** - * @default Indicates the path storing the module resources of the application - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly moduleSourceDirs: Array; - - /** - * @default Indicates the permissions required for accessing the application. - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly permissions: Array; - - /** - * @default Indicates module information about an application - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly moduleInfo: Array; - - /** - * @default Indicates the path where the {@code Entry.hap} file of the application is saved - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly entryDir: string; - - /** - * @default Indicates the custom metadata of the application - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - customizeData: Map; -} \ No newline at end of file diff --git a/interfaces/kits/js/bundle/bundleInfo.d.ts b/interfaces/kits/js/bundle/bundleInfo.d.ts deleted file mode 100644 index 6353eaef993782219ad6861054cf73d4e256c9e2..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/bundle/bundleInfo.d.ts +++ /dev/null @@ -1,237 +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 { AbilityInfo } from './abilityInfo'; -import { ApplicationInfo } from './applicationInfo'; -import { HapModuleInfo } from './hapModuleInfo'; - -/** - * @name The scene which is used - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @permission NA - * @devices phone, tablet, tv, wearable, car - */ -export interface UsedScene { - /** - * @default Indicates the abilities that need the permission - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - abilities: Array; - - /** - * @default Indicates the time when the permission is used - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - when: string; -} - -/** - * @name Indicates the required permissions details defined in file config.json - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @permission NA - * @devices phone, tablet, tv, wearable, car - */ -export interface ReqPermissionDetail { - /** - * @default Indicates the name of this required permissions - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - name: string; - - /** - * @default Indicates the reason of this required permissions - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - reason: string; - - /** - * @default Indicates the used scene of this required permissions - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - usedScene: UsedScene; -} - -/** - * @name Obtains configuration information about a bundle - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @permission NA - * @devices phone, tablet, tv, wearable, car - */ -export interface BundleInfo { - /** - * @default Indicates the name of this bundle - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly name: string; - - /** - * @default Indicates the name of this original bundle - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly type: string; - - /** - * @default Indicates the ID of the application to which this bundle belongs - * The application ID uniquely identifies an application. It is determined by the bundle name and signature - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly appId: string; - - /** - * @default Indicates the UID of the application to which this bundle belongs - * The UID uniquely identifies an application. It is determined by the process and user IDs of the application - * After an application is installed, its UID remains unchanged unless it is uninstalled and then reinstalled - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly uid: number; - - /** - * @default Indicates the hap install time - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly installTime: number; - - /** - * @default Indicates the hap update time - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly updateTime: number; - - /** - * @default Obtains configuration information about an application - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly appInfo: ApplicationInfo; - - /** - * @default Obtains configuration information about an ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly abilityInfo: Array; - - /** - * @default Indicates the required permissions name defined in file config.json - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly reqPermissions: Array; - - /** - * @default Indicates the required permissions details defined in file config.json - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly reqPermissionDetails: Array; - - /** - * @default Describes the bundle vendor - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly vendor: string; - - /** - * @default Indicates the version number of the bundle - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly versionCode: number; - - /** - * @default Indicates the text description of the bundle version - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly versionName: string; - - /** - * @default Indicates the compatible version number of the bundle - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly compatibleVersion: number; - - /** - * @default Indicates the target version number of the bundle - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly targetVersion: number; - - /** - * @default Indicates is compress native libs - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly isCompressNativeLibs: boolean; - - /** - * @default Obtains configuration information about an module - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly hapModuleInfo: Array; - - /** - * @default Indicates entry module name - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly entryModuleName: string; - - /** - * @default Indicates the cpuAbi information of this bundle. - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly cpuAbi: string; - - /** - * @default Indicates is silent installation - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly isSilentInstallation: string; - - /** - * @default Indicates the earliest historical version compatible with the bundle - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly minCompatibleVersionCode: number; - - /** - * @default Indicates whether free installation of the entry is supported - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly entryInstallationFree: boolean; -} diff --git a/interfaces/kits/js/bundle/bundleInstaller.d.ts b/interfaces/kits/js/bundle/bundleInstaller.d.ts deleted file mode 100644 index 5cdfc48f780c946ee46ceef7d3c1c80c08aab26f..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/bundle/bundleInstaller.d.ts +++ /dev/null @@ -1,107 +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 } from './../basic'; -import bundle from './../@ohos.bundle'; - -/** - * @name Provides parameters required for installing or uninstalling an application. - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @permission NA - * @devices phone, tablet, tv, wearable, car - */ -export interface InstallParam { - /** - * @default Indicates the user id - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - userId: number; - - /** - * @default Indicates the install flag - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - installFlag: number; - - /** - * @default Indicates whether the param has data - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - isKeepData: boolean; -} - -/** - * @name Indicates the install or uninstall status - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @permission NA - * @devices phone, tablet, tv, wearable, car - */ -export interface InstallStatus { - - /** - * @default Indicates the install or uninstall error code - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - status: bundle.InstallErrorCode; - - /** - * @default Indicates the install or uninstall result string message - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - statusMessage: string; -} - -/** - * @name Offers install, upgrade, and remove bundles on the devices. - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @permission NA - * @devices phone, tablet, tv, wearable, car - */ -export interface BundleInstaller { - /** - * Install an application in a HAP. - * - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @devices phone, tablet, tv, wearable, car - * @param bundleFilePaths Indicates the path where the bundle of the application is stored. The path should be the - * relative path to the data directory of the current application. - * @param installParam Indicates other parameters required for the installation. - * @return InstallStatus - * @permission ohos.permission.INSTALL_BUNDLE - */ - install(bundleFilePaths: Array, param: InstallParam, callback: AsyncCallback): void; - - /** - * Uninstall an application. - * - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @devices phone, tablet, tv, wearable, car - * @param bundleName Indicates the bundle name of the application to be uninstalled. - * @param installParam Indicates other parameters required for the uninstallation. - * @return InstallStatus - * @permission ohos.permission.INSTALL_BUNDLE - */ - uninstall(bundleName: string, param: InstallParam, callback: AsyncCallback): void; -} \ No newline at end of file diff --git a/interfaces/kits/js/bundle/hapModuleInfo.d.ts b/interfaces/kits/js/bundle/hapModuleInfo.d.ts deleted file mode 100644 index a62a66955d341a076b9600c522bf4c14e2ae7be9..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/bundle/hapModuleInfo.d.ts +++ /dev/null @@ -1,116 +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 { AbilityInfo } from "./abilityInfo"; - -/** - * @name Obtains configuration information about an module. - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @permission NA - * @devices phone, tablet, tv, wearable, car - */ -export interface HapModuleInfo { - /** - * @default Indicates the name of this hapmodule - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly name: string; - /** - * @default Describes the hapmodule - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly description: string; - /** - * @default Indicates the description of this hapmodule - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly descriptionId: number; - /** - * @default Indicates the icon of this hapmodule - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly icon: string; - /** - * @default Indicates the label of this hapmodule - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly label: string; - /** - * @default Indicates the label id of this hapmodule - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly labelId: number; - /** - * @default Indicates the icon id of this hapmodule - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly iconId: number; - /** - * @default Indicates the background img of this hapmodule - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly backgroundImg: string; - /** - * @default Indicates the supported modes of this hapmodule - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly supportedModes: number; - /** - * @default Indicates the req capabilities of this hapmodule - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly reqCapabilities: Array; - /** - * @default The device types that this hapmodule can run on - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly deviceTypes: Array; - /** - * @default Obtains configuration information about ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly abilityInfo: Array; - /** - * @default Indicates the name of the .hap package to which the capability belongs - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly moduleName: string; - /** - * @default Indicates the main ability name of this hapmodule - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly mainAbilityName: string; - /** - * @default Indicates whether free installation of the hapmodule is supported - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly installationFree: boolean; -} \ No newline at end of file diff --git a/interfaces/kits/js/bundle/moduleUsageRecord.d.ts b/interfaces/kits/js/bundle/moduleUsageRecord.d.ts deleted file mode 100644 index 0bc3620102c1ad500749f468d6c1fc0b8aeec85b..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/bundle/moduleUsageRecord.d.ts +++ /dev/null @@ -1,103 +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. - */ - -/** - * @name Stores FA usage information. - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @permission NA - * @devices phone, tablet, tv, wearable, car - * @systemapi hide this for inner system use - */ -export interface ModuleUsageRecord { - /** - * @default Indicates the name of the bundle containing the module - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly bundleName: string; - /** - * @default Indicates the app label id of this module - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly appLabelId: number; - /** - * @default Indicates the name of this module - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly name: string; - /** - * @default Indicates the label id of this module - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly labelId: number; - /** - * @default Indicates the description id of this module - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly descriptionId: number; - /** - * @default Indicates the ability name of this module - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly abilityName: string; - /** - * @default Indicates the ability label id of this module - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly abilityLabelId: number; - /** - * @default Indicates the ability description id of this module - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly abilityDescriptionId: number; - /** - * @default Indicates the ability icon id of this module - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly abilityIconId: number; - /** - * @default Indicates the launched count of this module - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly launchedCount: number; - /** - * @default Indicates the last launch time of this module - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly lastLaunchTime: number; - /** - * @default Indicates whether the module is removed - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly isRemoved: boolean; - /** - * @default Indicates whether free installation of the module is supported - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly installationFreeSupported: boolean; -} \ No newline at end of file diff --git a/interfaces/kits/js/bundle/shortcutInfo.d.ts b/interfaces/kits/js/bundle/shortcutInfo.d.ts deleted file mode 100644 index 0caaa904588090744952185e131400367a56fdac..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/bundle/shortcutInfo.d.ts +++ /dev/null @@ -1,107 +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. - */ - - /** - * @name Provides methods for obtaining information about the ability that a shortcut will start, including the target - * bundle name and ability class name. - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @permission NA - * @devices phone, tablet, tv, wearable, car - */ -export interface ShortcutWant{ - /** - * @default Indicates the target bundle of the shortcut want - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly targetBundle: string; - /** - * @default Indicates the target class of the shortcut want - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly targetClass: string; -} - - /** - * @name Provides information about a shortcut, including the shortcut ID and label. - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @permission NA - * @devices phone, tablet, tv, wearable, car - */ -export interface ShortcutInfo { - /** - * @default Indicates the ID of the application to which this shortcut belongs - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly id: string; - /** - * @default Indicates the name of the bundle containing the shortcut - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly bundleName: string; - /** - * @default Indicates the host ability of the shortcut - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly hostAbility: string; - /** - * @default Indicates the icon of the shortcut - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly icon: string; - /** - * @default Indicates the label of the shortcut - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly label: string; - /** - * @default Indicates the disableMessage of the shortcut - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly disableMessage: string; - /** - * @default Indicates the wants of the shortcut - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly wants: Array; - /** - * @default Indicates whether the shortcut is static - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly isStatic?: boolean - /** - * @default Indicates whether the shortcut is homeshortcut - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly isHomeShortcut?: boolean; - /** - * @default Indicates whether the shortcut is enabled - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly isEnabled?: boolean; -} \ No newline at end of file diff --git a/interfaces/kits/napi/BUILD.gn b/interfaces/kits/napi/BUILD.gn index aff640ffd0f3bc5e2e014181a14f2b1a81491baf..7323187890a114f43a2aab0357bfc58cb6fe1c0c 100644 --- a/interfaces/kits/napi/BUILD.gn +++ b/interfaces/kits/napi/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -29,20 +29,27 @@ 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/configuration_constant:configurationconstant_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/datashare_ext_ability:datashareextensionability_napi", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/datashare_ext_ability_context:datashareextensionabilitycontext_napi", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/ext_ability_context:extabilitycontext_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", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/mission_manager:distributedmissionmanager", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/mission_manager:missionmanager_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/particleAbility:particleability", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/service_ext_ability:serviceextability_napi", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/service_ext_ability_context:serviceextabilitycontext_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/service_extension_context:serviceextensioncontext_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/serviceextension:serviceextension_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/static_subscriber_extension:staticsubscriberextension_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/static_subscriber_extension_context:staticsubscriberextensioncontext_napi", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/uri_permission:uripermmgr_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/wantConstant:wantconstant", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/wantagent:wantagent", ] } diff --git a/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.cpp b/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.cpp index 6f33960308b7ba5413c6b261cca5cb529a65f775..8f6613b9feac48e3c973ff1630ad3f537d845f81 100644 --- a/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.cpp +++ b/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.cpp @@ -50,9 +50,6 @@ OHOS::sptr GetAppManagerInstance() napi_value ParseBundleName(napi_env env, std::string &bundleName, napi_value args) { - napi_valuetype valuetype = napi_valuetype::napi_null; - NAPI_CALL(env, napi_typeof(env, args, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); char buf[NapiAbilityMgr::BUFFER_LENGTH_MAX] = {0}; size_t len = 0; napi_get_value_string_utf8(env, args, buf, NapiAbilityMgr::BUFFER_LENGTH_MAX, &len); @@ -321,7 +318,7 @@ void GetMissionSnapshotInfoForResult(napi_env env, MissionSnapshot &recentMissio napi_value iconResult = nullptr; iconResult = Media::PixelMapNapi::CreatePixelMap(env, recentMissionInfos.snapshot); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, result, "snapshot", iconResult)); - }else{ + } else { NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, result, "snapshot", NapiGetNull(env))); } } @@ -836,7 +833,7 @@ napi_value NAPI_GetActiveAbilityMissionInfos(napi_env env, napi_callback_info in callBackMode = true; } - AsyncMissionInfosCallbackInfo *async_callback_info = new (std::nothrow) AsyncMissionInfosCallbackInfo{ + AsyncMissionInfosCallbackInfo *async_callback_info = new (std::nothrow) AsyncMissionInfosCallbackInfo { .env = env, .asyncWork = nullptr, .deferred = nullptr, @@ -1692,6 +1689,9 @@ napi_value NAPI_KillProcessesByBundleName(napi_env env, napi_callback_info info) HILOG_INFO("argc = [%{public}zu]", argc); std::string bundleName = ""; + napi_valuetype valuetype = napi_valuetype::napi_null; + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); ParseBundleName(env, bundleName, argv[0]); bool callBackMode = false; @@ -1813,6 +1813,9 @@ napi_value NAPI_ClearUpApplicationData(napi_env env, napi_callback_info info) HILOG_INFO("argc = [%{public}zu]", argc); std::string bundleName = ""; + napi_valuetype valuetype = napi_valuetype::napi_null; + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); ParseBundleName(env, bundleName, argv[0]); bool callBackMode = false; @@ -1851,7 +1854,7 @@ auto NAPI_GetAbilityMissionSnapshotAsyncExecute = [](napi_env env, void *data) { HILOG_INFO("GetAbilityMissionSnapshotWrap called..."); AsyncGetMissionSnapshot *async_callback_info = (AsyncGetMissionSnapshot *)data; AAFwk::AbilityManagerClient::GetInstance()->GetMissionSnapshot(async_callback_info->missionId, - async_callback_info->missionSnapshot); + async_callback_info->missionSnapshot); }; auto NAPI_GetAbilityMissionSnapshotAsyncCompleteCallback = [](napi_env env, napi_status status, void *data) { @@ -1952,7 +1955,7 @@ napi_value NAPI_GetAbilityMissionSnapshot(napi_env env, napi_callback_info info) } AsyncGetMissionSnapshot *async_callback_info = - new (std::nothrow) AsyncGetMissionSnapshot{.env = env, .asyncWork = nullptr, .deferred = nullptr}; + new (std::nothrow) AsyncGetMissionSnapshot {.env = env, .asyncWork = nullptr, .deferred = nullptr}; if (async_callback_info == nullptr) { return NapiGetNull(env); } diff --git a/interfaces/kits/napi/aafwk/ability_context/ability_context.js b/interfaces/kits/napi/aafwk/ability_context/ability_context.js index c053519cd7c01bddf99987417eef145dd577b4dd..8c8cd091839310d57356e179ef87580ef15931aa 100755 --- a/interfaces/kits/napi/aafwk/ability_context/ability_context.js +++ b/interfaces/kits/napi/aafwk/ability_context/ability_context.js @@ -21,11 +21,11 @@ class AbilityContext extends Context { super(obj) this.abilityInfo = obj.abilityInfo this.currentHapModuleInfo = obj.currentHapModuleInfo - this.configuration = obj.configuration + this.config = obj.config } onUpdateConfiguration(config) { - this.configuration = config + this.config = config } startAbility(want, options, callback) { @@ -52,12 +52,12 @@ class AbilityContext extends Context { } } - startAbilityForResult(want, callback) { - return this.__context_impl__.startAbilityForResult(want, callback) + startAbilityForResult(want, options, callback) { + return this.__context_impl__.startAbilityForResult(want, options, callback) } - startAbilityForResultWithAccount(want, accountId, callback) { - return this.__context_impl__.startAbilityForResultWithAccount(want, accountId, callback) + startAbilityForResultWithAccount(want, accountId, options, callback) { + return this.__context_impl__.startAbilityForResultWithAccount(want, accountId, options, callback) } connectAbility(want, options) { diff --git a/interfaces/kits/napi/aafwk/ability_manager/BUILD.gn b/interfaces/kits/napi/aafwk/ability_manager/BUILD.gn index 8db081cd2dec7ef8cfd3670ad4c2c404c0421cc8..beccfb4535881ac809bb9a2f232fa194f592f9ba 100644 --- a/interfaces/kits/napi/aafwk/ability_manager/BUILD.gn +++ b/interfaces/kits/napi/aafwk/ability_manager/BUILD.gn @@ -48,9 +48,9 @@ ohos_shared_library("abilitymanager_napi") { ] external_deps = [ + "ability_base:want", "ability_runtime:ability_manager", "ability_runtime:runtime", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/interfaces/kits/napi/aafwk/app/ability_delegator/BUILD.gn b/interfaces/kits/napi/aafwk/app/ability_delegator/BUILD.gn index da7a4cbcaafb060d2ae70696fef4d5a843ddc604..06853c2562bcd87ebc6757f53debf74211900615 100644 --- a/interfaces/kits/napi/aafwk/app/ability_delegator/BUILD.gn +++ b/interfaces/kits/napi/aafwk/app/ability_delegator/BUILD.gn @@ -36,7 +36,7 @@ ohos_shared_library("abilitydelegatorregistry") { deps = [ "//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", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_delegator", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", ] diff --git a/interfaces/kits/napi/aafwk/app/ability_delegator/ability_monitor.cpp b/interfaces/kits/napi/aafwk/app/ability_delegator/ability_monitor.cpp index 600f104ba571c121bc6ad1fa5af9a3efa360b4e6..bc8f2cdb097af9d23f38776e3ef35c2c76ed01ce 100644 --- a/interfaces/kits/napi/aafwk/app/ability_delegator/ability_monitor.cpp +++ b/interfaces/kits/napi/aafwk/app/ability_delegator/ability_monitor.cpp @@ -22,11 +22,11 @@ namespace OHOS { namespace AbilityDelegatorJs { using namespace OHOS::AbilityRuntime; -AbilityMonitor::AbilityMonitor(const std::string &name, JSAbilityMonitor *jsAbilityMonitor) +AbilityMonitor::AbilityMonitor(const std::string &name, const std::shared_ptr &jsAbilityMonitor) : IAbilityMonitor(name), jsMonitor_(jsAbilityMonitor) {} -void AbilityMonitor::onAbilityStart() +void AbilityMonitor::OnAbilityStart() { HILOG_INFO("onAbilityCreate is called"); @@ -39,7 +39,7 @@ void AbilityMonitor::onAbilityStart() HILOG_INFO("onAbilityCreate is called end"); } -void AbilityMonitor::onAbilityForeground() +void AbilityMonitor::OnAbilityForeground() { HILOG_INFO("onAbilityForeground is called"); @@ -52,7 +52,7 @@ void AbilityMonitor::onAbilityForeground() HILOG_INFO("onAbilityForeground is called end"); } -void AbilityMonitor::onAbilityBackground() +void AbilityMonitor::OnAbilityBackground() { HILOG_INFO("onAbilityBackground is called"); @@ -65,7 +65,7 @@ void AbilityMonitor::onAbilityBackground() HILOG_INFO("onAbilityBackground is called end"); } -void AbilityMonitor::onAbilityStop() +void AbilityMonitor::OnAbilityStop() { HILOG_INFO("onAbilityDestroy is called"); @@ -78,7 +78,7 @@ void AbilityMonitor::onAbilityStop() HILOG_INFO("onAbilityDestroy is called end"); } -void AbilityMonitor::onWindowStageCreate() +void AbilityMonitor::OnWindowStageCreate() { HILOG_INFO("onWindowStageCreate is called"); @@ -91,7 +91,7 @@ void AbilityMonitor::onWindowStageCreate() HILOG_INFO("onWindowStageCreate is called end"); } -void AbilityMonitor::onWindowStageRestore() +void AbilityMonitor::OnWindowStageRestore() { HILOG_INFO("onWindowStageRestore is called"); @@ -104,7 +104,7 @@ void AbilityMonitor::onWindowStageRestore() HILOG_INFO("onWindowStageRestore is called end"); } -void AbilityMonitor::onWindowStageDestroy() +void AbilityMonitor::OnWindowStageDestroy() { HILOG_INFO("onWindowStageDestroy is called"); diff --git a/interfaces/kits/napi/aafwk/app/ability_delegator/ability_monitor.h b/interfaces/kits/napi/aafwk/app/ability_delegator/ability_monitor.h index 1f00888d0e3f4d208e9728b0a79f338582f93f0e..dd89eb0340ddbd98bcddcab2d66f2310aa3edd7e 100644 --- a/interfaces/kits/napi/aafwk/app/ability_delegator/ability_monitor.h +++ b/interfaces/kits/napi/aafwk/app/ability_delegator/ability_monitor.h @@ -27,19 +27,18 @@ class NativeValue; namespace OHOS { namespace AbilityDelegatorJs { using namespace OHOS::AppExecFwk; -using Function = void(*)(); class AbilityMonitor : public IAbilityMonitor { public: - AbilityMonitor(const std::string &name, JSAbilityMonitor *jsAbilityMonitor); + AbilityMonitor(const std::string &name, const std::shared_ptr &jsAbilityMonitor); ~AbilityMonitor() = default; - void onAbilityStart(); - void onAbilityForeground(); - void onAbilityBackground(); - void onAbilityStop(); - void onWindowStageCreate(); - void onWindowStageRestore(); - void onWindowStageDestroy(); + void OnAbilityStart() override; + void OnAbilityForeground() override; + void OnAbilityBackground() override; + void OnAbilityStop() override; + void OnWindowStageCreate() override; + void OnWindowStageRestore() override; + void OnWindowStageDestroy() override; private: std::shared_ptr jsMonitor_; diff --git a/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator.cpp b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator.cpp index f7da618ea3cfa55b4d8ab662efd47c3e0268902e..9fbe7702c9a7388902f37324d297f34de6f20a09 100644 --- a/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator.cpp +++ b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator.cpp @@ -29,7 +29,6 @@ namespace AbilityDelegatorJs { constexpr size_t ARGC_ONE = 1; constexpr size_t ARGC_TWO = 2; constexpr size_t ARGC_THREE = 3; -constexpr size_t ARGC_FOUR = 4; constexpr size_t INDEX_ZERO = 0; constexpr size_t INDEX_ONE = 1; constexpr size_t INDEX_TWO = 2; @@ -104,11 +103,17 @@ NativeValue *JSAbilityDelegator::ExecuteShellCommand(NativeEngine *engine, Nativ return (me != nullptr) ? me->OnExecuteShellCommand(*engine, *info) : nullptr; } +NativeValue *JSAbilityDelegator::FinishTest(NativeEngine *engine, NativeCallbackInfo *info) +{ + JSAbilityDelegator *me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnFinishTest(*engine, *info) : nullptr; +} + NativeValue *JSAbilityDelegator::OnAddAbilityMonitor(NativeEngine &engine, NativeCallbackInfo &info) { HILOG_INFO("OnAddAbilityMonitor is called, argc = %{public}d", static_cast(info.argc)); - if (info.argc < ARGC_ONE || info.argc > ARGC_TWO) { + if (info.argc < ARGC_ONE) { HILOG_ERROR("Incorrect number of parameters"); return engine.CreateUndefined(); } @@ -134,7 +139,7 @@ NativeValue *JSAbilityDelegator::OnRemoveAbilityMonitor(NativeEngine &engine, Na { HILOG_INFO("OnRemoveAbilityMonitor is called, argc = %{public}d", static_cast(info.argc)); - if (info.argc < ARGC_ONE || info.argc > ARGC_TWO) { + if (info.argc < ARGC_ONE) { HILOG_ERROR("Incorrect number of parameters"); return engine.CreateUndefined(); } @@ -170,7 +175,7 @@ NativeValue *JSAbilityDelegator::OnWaitAbilityMonitor(NativeEngine &engine, Nati { HILOG_INFO("OnWaitAbilityMonitor is called, argc = %{public}d", static_cast(info.argc)); - if (info.argc < ARGC_ONE || info.argc > ARGC_THREE) { + if (info.argc < ARGC_ONE) { HILOG_ERROR("Incorrect number of parameters"); return engine.CreateUndefined(); } @@ -221,7 +226,7 @@ NativeValue *JSAbilityDelegator::OnPrint(NativeEngine &engine, NativeCallbackInf { HILOG_INFO("OnPrint is called, argc = %{public}d", static_cast(info.argc)); - if (info.argc < ARGC_ONE || info.argc > ARGC_TWO) { + if (info.argc < ARGC_ONE) { HILOG_ERROR("Incorrect number of parameters"); return engine.CreateUndefined(); } @@ -248,7 +253,7 @@ NativeValue *JSAbilityDelegator::OnExecuteShellCommand(NativeEngine &engine, Nat { HILOG_INFO("OnExecuteShellCommand is called, argc = %{public}d", static_cast(info.argc)); - if (info.argc < ARGC_ONE || info.argc > ARGC_FOUR) { + if (info.argc < ARGC_ONE) { HILOG_ERROR("Incorrect number of parameters"); return engine.CreateUndefined(); } @@ -285,11 +290,6 @@ NativeValue *JSAbilityDelegator::OnGetAppContext(NativeEngine &engine, NativeCal { HILOG_INFO("OnGetAppContext is called, argc = %{public}d", static_cast(info.argc)); - if (info.argc > ARGC_ONE) { - HILOG_ERROR("Incorrect number of parameters"); - return engine.CreateUndefined(); - } - AsyncTask::CompleteCallback complete = [](NativeEngine &engine, AsyncTask &task, int32_t status) { HILOG_INFO("OnGetAppContext AsyncTask is called"); std::shared_ptr context = @@ -307,7 +307,7 @@ NativeValue *JSAbilityDelegator::OnGetAbilityState(NativeEngine &engine, NativeC { HILOG_INFO("OnGetAbilityState is called, argc = %{public}d", static_cast(info.argc)); - if (info.argc < ARGC_ONE || info.argc > ARGC_TWO) { + if (info.argc < ARGC_ONE) { HILOG_ERROR("Incorrect number of parameters"); return engine.CreateUndefined(); } @@ -334,11 +334,6 @@ NativeValue *JSAbilityDelegator::OnGetCurrentTopAbility(NativeEngine &engine, Na { HILOG_INFO("OnGetCurrentTopAbility is called, argc = %{public}d", static_cast(info.argc)); - if (info.argc > ARGC_ONE) { - HILOG_ERROR("Incorrect number of parameters"); - return engine.CreateUndefined(); - } - AsyncTask::CompleteCallback complete = [this](NativeEngine &engine, AsyncTask &task, int32_t status) { HILOG_INFO("OnGetCurrentTopAbility AsyncTask is called"); sptr remoteObject = @@ -356,7 +351,7 @@ NativeValue *JSAbilityDelegator::OnDoAbilityForeground(NativeEngine &engine, Nat { HILOG_INFO("OnDoAbilityForeground is called, argc = %{public}d", static_cast(info.argc)); - if (info.argc < ARGC_ONE || info.argc > ARGC_TWO) { + if (info.argc < ARGC_ONE) { HILOG_ERROR("Incorrect number of parameters"); return engine.CreateUndefined(); } @@ -382,7 +377,7 @@ NativeValue *JSAbilityDelegator::OnDoAbilityBackground(NativeEngine &engine, Nat { HILOG_INFO("OnDoAbilityBackground is called, argc = %{public}d", static_cast(info.argc)); - if (info.argc < ARGC_ONE || info.argc > ARGC_TWO) { + if (info.argc < ARGC_ONE) { HILOG_ERROR("Incorrect number of parameters"); return engine.CreateUndefined(); } @@ -404,6 +399,38 @@ NativeValue *JSAbilityDelegator::OnDoAbilityBackground(NativeEngine &engine, Nat return result; } +NativeValue *JSAbilityDelegator::OnFinishTest(NativeEngine &engine, NativeCallbackInfo &info) +{ + HILOG_INFO("OnFinishTest is called, argc = %{public}d", static_cast(info.argc)); + + if (info.argc < ARGC_TWO) { + HILOG_ERROR("Incorrect number of parameters"); + return engine.CreateUndefined(); + } + + std::string msg; + int64_t code = 0; + if (!ConvertFromJsValue(engine, info.argv[INDEX_ZERO], msg)) { + HILOG_ERROR("Parse para failed"); + return engine.CreateUndefined(); + } + + if (!ConvertFromJsValue(engine, info.argv[INDEX_ONE], code)) { + HILOG_ERROR("Parse para argv[1] failed"); + return engine.CreateUndefined(); + } + + AsyncTask::CompleteCallback complete = [msg, code](NativeEngine &engine, AsyncTask &task, int32_t status) { + HILOG_INFO("OnFinishTest AsyncTask is called"); + AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator()->FinishUserTest(msg, code); + task.Resolve(engine, engine.CreateUndefined()); + }; + NativeValue *lastParam = (info.argc == ARGC_THREE) ? info.argv[INDEX_TWO] : nullptr; + NativeValue *result = nullptr; + AsyncTask::Schedule(engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; +} + NativeValue *JSAbilityDelegator::ParseJSMonitorPara( NativeEngine &engine, NativeValue *value, std::shared_ptr &monitor) { @@ -436,7 +463,7 @@ NativeValue *JSAbilityDelegator::ParseJSMonitorPara( abilityMonitor->SetJsAbilityMonitorEnv(&engine); abilityMonitor->SetJsAbilityMonitor(value); - monitor = std::make_shared(abilityName, abilityMonitor.get()); + monitor = std::make_shared(abilityName, abilityMonitor); if (!monitor) { HILOG_INFO("Failed to create monitor"); return nullptr; @@ -444,7 +471,7 @@ NativeValue *JSAbilityDelegator::ParseJSMonitorPara( std::shared_ptr refence = nullptr; refence.reset(engine.CreateReference(value, 1)); - monitorRecord[refence] = monitor; + monitorRecord.emplace(refence, monitor); return engine.CreateNull(); } diff --git a/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator.h b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator.h index 4ad09f07960689513c5c8ed9464b0bad6e0e21fe..06342d72ec84a39baf0821453c21b4add65ad14e 100644 --- a/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator.h +++ b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator.h @@ -39,6 +39,7 @@ public: static NativeValue *GetCurrentTopAbility(NativeEngine *engine, NativeCallbackInfo *info); static NativeValue *DoAbilityForeground(NativeEngine *engine, NativeCallbackInfo *info); static NativeValue *DoAbilityBackground(NativeEngine *engine, NativeCallbackInfo *info); + static NativeValue *FinishTest(NativeEngine *engine, NativeCallbackInfo *info); private: NativeValue *OnAddAbilityMonitor(NativeEngine &engine, NativeCallbackInfo &info); @@ -51,6 +52,7 @@ private: NativeValue *OnGetCurrentTopAbility(NativeEngine &engine, NativeCallbackInfo &info); NativeValue *OnDoAbilityForeground(NativeEngine &engine, NativeCallbackInfo &info); NativeValue *OnDoAbilityBackground(NativeEngine &engine, NativeCallbackInfo &info); + NativeValue *OnFinishTest(NativeEngine &engine, NativeCallbackInfo &info); private: NativeValue *CreateJsAbilityObject(NativeEngine &engine, const sptr &remoteObject); diff --git a/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator_registry.cpp b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator_registry.cpp index 9dfcbef1e0a5cd2771df79bc003d99500b998652..41b4d16025b6e817a3147260c7af08566d431b3d 100644 --- a/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator_registry.cpp +++ b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator_registry.cpp @@ -28,7 +28,6 @@ using namespace OHOS::AppExecFwk; using namespace OHOS::AbilityRuntime; namespace { constexpr int32_t ARGC_ONE = 1; - class JsAbilityDelegatorRegistry { public: JsAbilityDelegatorRegistry() = default; @@ -55,16 +54,12 @@ public: private: NativeValue *OnGetAbilityDelegator(NativeEngine &engine, NativeCallbackInfo &info) { - HILOG_INFO("%{public}s is called", __FUNCTION__); - if (info.argc > ARGC_ONE) { - HILOG_ERROR("Params not match"); - return engine.CreateUndefined(); - } + HILOG_INFO("OnGetAbilityDelegator is called, argc = %{public}d", static_cast(info.argc)); AsyncTask::CompleteCallback complete = [](NativeEngine &engine, AsyncTask &task, int32_t status) { + HILOG_INFO("OnGetAbilityDelegator AsyncTask::CompleteCallback"); task.Resolve(engine, CreateJsAbilityDelegator(engine)); }; - NativeValue *lastParam = (info.argc == ARGC_ONE) ? info.argv[0] : nullptr; NativeValue *result = nullptr; AsyncTask::Schedule( @@ -74,11 +69,7 @@ private: NativeValue *OnGetArguments(NativeEngine &engine, NativeCallbackInfo &info) { - HILOG_INFO("%{public}s is called", __FUNCTION__); - if (info.argc > ARGC_ONE) { - HILOG_ERROR("Params not match"); - return engine.CreateUndefined(); - } + HILOG_INFO("OnGetArguments is called, argc = %{public}d", static_cast(info.argc)); AsyncTask::CompleteCallback complete = [](NativeEngine &engine, AsyncTask &task, int32_t status) { std::shared_ptr abilityDelegatorArgs = diff --git a/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator_utils.cpp b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator_utils.cpp index 9af710d8deb636d8add38c1924fd1c1b537b6834..5918ce21b818442ae2a37622ec5f8fdbac25cc7a 100644 --- a/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator_utils.cpp +++ b/interfaces/kits/napi/aafwk/app/ability_delegator/js_ability_delegator_utils.cpp @@ -48,29 +48,25 @@ NativeValue *CreateJsAbilityDelegator(NativeEngine &engine) BindNativeFunction(engine, *object, "doAbilityBackground", JSAbilityDelegator::DoAbilityBackground); BindNativeFunction(engine, *object, "print", JSAbilityDelegator::Print); BindNativeFunction(engine, *object, "executeShellCommand", JSAbilityDelegator::ExecuteShellCommand); + BindNativeFunction(engine, *object, "finishTest", JSAbilityDelegator::FinishTest); return objValue; } -napi_value WrapStringToJS(napi_env env, const std::string &value) -{ - napi_value result = nullptr; - NAPI_CALL(env, napi_create_string_utf8(env, value.c_str(), NAPI_AUTO_LENGTH, &result)); - return result; -} - -void SetAbilityDelegatorArgumentsPara(napi_env env, const std::map ¶s) +NativeValue *SetAbilityDelegatorArgumentsPara(NativeEngine &engine, const std::map ¶s) { HILOG_INFO("SetAbilityDelegatorArgumentsPara is called"); - napi_value parameter = nullptr; - napi_value result = nullptr; + NativeValue *objValue = engine.CreateObject(); + NativeObject *object = ConvertNativeValueTo(objValue); + if (object == nullptr) { + HILOG_ERROR("Failed to get object"); + return nullptr; + } auto iter = paras.begin(); for (; iter != paras.end(); ++iter) { - NAPI_CALL_RETURN_VOID( - env, napi_set_named_property(env, parameter, iter->first.c_str(), WrapStringToJS(env, iter->second))); + object->SetProperty(iter->first.c_str(), CreateJsValue(engine, iter->second)); } - napi_set_named_property(env, result, "parameters", parameter); - return; + return objValue; } NativeValue *CreateJsAbilityDelegatorArguments( @@ -86,7 +82,8 @@ NativeValue *CreateJsAbilityDelegatorArguments( } object->SetProperty("bundleName", CreateJsValue(engine, abilityDelegatorArgs->GetTestBundleName())); - SetAbilityDelegatorArgumentsPara(reinterpret_cast(&engine), abilityDelegatorArgs->GetTestParam()); + object->SetProperty("parameters", + SetAbilityDelegatorArgumentsPara(engine, abilityDelegatorArgs->GetTestParam())); object->SetProperty("testCaseNames", CreateJsValue(engine, abilityDelegatorArgs->GetTestCaseName())); object->SetProperty("testRunnerClassName", CreateJsValue(engine, abilityDelegatorArgs->GetTestRunnerClassName())); diff --git a/interfaces/kits/napi/aafwk/app/ability_stage_context/ability_stage_context.js b/interfaces/kits/napi/aafwk/app/ability_stage_context/ability_stage_context.js index 247b206e50015d8bdd40a3070c4f26fede3c63d8..df92d8b36701b1fb942b1329390828d547ea982d 100644 --- a/interfaces/kits/napi/aafwk/app/ability_stage_context/ability_stage_context.js +++ b/interfaces/kits/napi/aafwk/app/ability_stage_context/ability_stage_context.js @@ -20,6 +20,11 @@ class AbilityStageContext extends Context { super(obj) this.currentHapModuleInfo = obj.currentHapModuleInfo + this.config = obj.config + } + + onUpdateConfiguration(config) { + this.config = config } } diff --git a/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager.cpp b/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager.cpp index 9e864b0619ab41f277fc84869a28be429438f894..0cdc4232613ec8bf64bf38aca5214efc4ef34e4c 100644 --- a/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager.cpp +++ b/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager.cpp @@ -89,6 +89,18 @@ public: return (me != nullptr) ? me->OnKillProcessWithAccount(*engine, *info) : nullptr; } + static NativeValue* KillProcessesByBundleName(NativeEngine* engine, NativeCallbackInfo* info) + { + JsAppManager* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnkillProcess(*engine, *info) : nullptr; + } + + static NativeValue* ClearUpApplicationData(NativeEngine* engine, NativeCallbackInfo* info) + { + JsAppManager* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnClearUpApplicationData(*engine, *info) : nullptr; + } + private: sptr appManager_ = nullptr; sptr abilityManager_ = nullptr; @@ -270,6 +282,80 @@ private: return result; } + NativeValue* OnkillProcess(NativeEngine &engine, NativeCallbackInfo &info) + { + HILOG_INFO("%{public}s is called", __FUNCTION__); + if (info.argc == 0) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + + std::string bundleName; + if (!ConvertFromJsValue(engine, info.argv[0], bundleName)) { + HILOG_ERROR("get bundelName failed!"); + return engine.CreateUndefined(); + } + + HILOG_INFO("kill process [%{public}s]", bundleName.c_str()); + AsyncTask::CompleteCallback complete = [bundleName, abilityManager = abilityManager_](NativeEngine& engine, + AsyncTask& task, int32_t status) { + if (abilityManager == nullptr) { + HILOG_WARN("abilityManager nullptr"); + task.Reject(engine, CreateJsError(engine, ERROR_CODE_ONE, "abilityManager nullptr")); + return; + } + auto errcode = abilityManager->KillProcess(bundleName); + if (errcode == 0) { + task.Resolve(engine, CreateJsValue(engine, errcode)); + } else { + task.Reject(engine, CreateJsError(engine, errcode, "kill process failed.")); + } + }; + + NativeValue* lastParam = (info.argc == 1) ? nullptr : info.argv[1]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; + } + + NativeValue* OnClearUpApplicationData(NativeEngine &engine, NativeCallbackInfo &info) + { + HILOG_INFO("%{public}s is called", __FUNCTION__); + if (info.argc == 0) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + + std::string bundleName; + if (!ConvertFromJsValue(engine, info.argv[0], bundleName)) { + HILOG_ERROR("get bundelName failed!"); + return engine.CreateUndefined(); + } + + HILOG_INFO("kill process [%{public}s]", bundleName.c_str()); + AsyncTask::CompleteCallback complete = [bundleName, abilityManager = abilityManager_](NativeEngine& engine, + AsyncTask& task, int32_t status) { + if (abilityManager == nullptr) { + HILOG_WARN("abilityManager nullptr"); + task.Reject(engine, CreateJsError(engine, ERROR_CODE_ONE, "abilityManager nullptr")); + return; + } + auto errcode = abilityManager->ClearUpApplicationData(bundleName); + if (errcode == 0) { + task.Resolve(engine, CreateJsValue(engine, errcode)); + } else { + task.Reject(engine, CreateJsError(engine, errcode, "clear up application failed.")); + } + }; + + NativeValue* lastParam = (info.argc == 1) ? nullptr : info.argv[1]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; + } + NativeValue* OnKillProcessWithAccount(NativeEngine &engine, NativeCallbackInfo &info) { HILOG_INFO("%{public}s is called", __FUNCTION__); @@ -359,6 +445,10 @@ NativeValue* JsAppManagerInit(NativeEngine* engine, NativeValue* exportObj) JsAppManager::IsRunningInStabilityTest); BindNativeFunction(*engine, *object, "killProcessWithAccount", JsAppManager::KillProcessWithAccount); + BindNativeFunction(*engine, *object, "killProcessesByBundleName", + JsAppManager::KillProcessesByBundleName); + BindNativeFunction(*engine, *object, "clearUpApplicationData", + JsAppManager::ClearUpApplicationData); HILOG_INFO("JsAppManagerInit end"); return engine->CreateUndefined(); } @@ -444,7 +534,7 @@ void JSApplicationStateObserver::HandleOnExtensionStateChanged(const AbilityStat { HILOG_INFO("HandleOnExtensionStateChanged begin"); NativeValue* argv[] = {CreateJsAbilityStateData(engine_, abilityStateData)}; - CallJsFunction("onExtensionStateChanged", argv, ARGC_ONE); + CallJsFunction("onAbilityStateChanged", argv, ARGC_ONE); } void JSApplicationStateObserver::OnProcessCreated(const ProcessData &processData) diff --git a/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager_utils.cpp b/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager_utils.cpp index e4d2c3e858e4e478dd7dfe3cdf2b28429c1a7c1b..19c5fbbc3933185d9f12b372bf9d9a9944bee24e 100644 --- a/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager_utils.cpp +++ b/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager_utils.cpp @@ -66,6 +66,7 @@ NativeValue* CreateJsAbilityStateData(NativeEngine &engine, const AbilityStateDa object->SetProperty("pid", CreateJsValue(engine, abilityStateData.pid)); object->SetProperty("uid", CreateJsValue(engine, abilityStateData.uid)); object->SetProperty("state", CreateJsValue(engine, abilityStateData.abilityState)); + object->SetProperty("abilityType", CreateJsValue(engine, abilityStateData.abilityType)); HILOG_INFO("%{public}s end.", __func__); return objValue; } diff --git a/interfaces/kits/napi/aafwk/app/test_runner/test_runner.js b/interfaces/kits/napi/aafwk/app/test_runner/test_runner.js index 4bd372f476960f9045f0a076cd86f148c45aa484..7e517c5b51b1647f6a1b7280261c9a14bfbb1a9c 100755 --- a/interfaces/kits/napi/aafwk/app/test_runner/test_runner.js +++ b/interfaces/kits/napi/aafwk/app/test_runner/test_runner.js @@ -15,8 +15,8 @@ class TestRunner { constructor() {} - onPrepare​() {} - onRun​() {} + onPrepare() {} + onRun() {} } export default TestRunner diff --git a/interfaces/kits/napi/aafwk/caller/caller.js b/interfaces/kits/napi/aafwk/caller/caller.js index 102bf466adb485276d13f1d1d2a8dfd9af2d9fc2..0ccfdb0ff54c804c2ac2652a5f9531a262aa512d 100644 --- a/interfaces/kits/napi/aafwk/caller/caller.js +++ b/interfaces/kits/napi/aafwk/caller/caller.js @@ -74,6 +74,7 @@ class Caller { } async callWithResult(method, data) { + console.log("Caller callWithResult method [" + method + "]"); if (typeof method !== 'string' || typeof data !== 'object') { console.log("Caller callWithResult " + typeof method + ", " + typeof data); return undefined; diff --git a/interfaces/kits/napi/aafwk/configuration_constant/BUILD.gn b/interfaces/kits/napi/aafwk/configuration_constant/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..f56f62c2ef9084c8cf012e0fb3386e0a8eeb1de2 --- /dev/null +++ b/interfaces/kits/napi/aafwk/configuration_constant/BUILD.gn @@ -0,0 +1,29 @@ +# 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("//build/ohos.gni") + +ohos_shared_library("configurationconstant_napi") { + include_dirs = + [ "//base/global/resmgr_standard/interfaces/innerkits/include" ] + + sources = [ "configuration_constant_module.cpp" ] + + deps = [ "//utils/native/base:utils" ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module/application" + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/kits/napi/aafwk/configuration_constant/configuration_constant_module.cpp b/interfaces/kits/napi/aafwk/configuration_constant/configuration_constant_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..81a7eda824cebf76c71fa18199faa61695331447 --- /dev/null +++ b/interfaces/kits/napi/aafwk/configuration_constant/configuration_constant_module.cpp @@ -0,0 +1,124 @@ +/* + * 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 "res_common.h" +#include "napi/native_api.h" +#include "napi/native_common.h" + +namespace OHOS { +namespace AAFwk { +static napi_status SetEnumItem(napi_env env, napi_value object, const char* name, int32_t value) +{ + napi_status status; + napi_value itemName; + napi_value itemValue; + + NAPI_CALL_BASE(env, status = napi_create_string_utf8(env, name, NAPI_AUTO_LENGTH, &itemName), status); + NAPI_CALL_BASE(env, status = napi_create_int32(env, value, &itemValue), status); + + NAPI_CALL_BASE(env, status = napi_set_property(env, object, itemName, itemValue), status); + NAPI_CALL_BASE(env, status = napi_set_property(env, object, itemValue, itemName), status); + + return napi_ok; +} + +static napi_value InitColorModeObject(napi_env env) +{ + napi_value object; + NAPI_CALL(env, napi_create_object(env, &object)); + + NAPI_CALL(env, SetEnumItem(env, object, "COLOR_MODE_NOT_SET", Global::Resource::COLOR_MODE_NOT_SET)); + NAPI_CALL(env, SetEnumItem(env, object, "COLOR_MODE_DARK", Global::Resource::DARK)); + NAPI_CALL(env, SetEnumItem(env, object, "COLOR_MODE_LIGHT", Global::Resource::LIGHT)); + + return object; +} + +static napi_value InitDirectionObject(napi_env env) +{ + napi_value object; + NAPI_CALL(env, napi_create_object(env, &object)); + + NAPI_CALL(env, SetEnumItem(env, object, "DIRECTION_NOT_SET", Global::Resource::DIRECTION_NOT_SET)); + NAPI_CALL(env, SetEnumItem(env, object, "DIRECTION_VERTICAL", Global::Resource::DIRECTION_VERTICAL)); + NAPI_CALL(env, SetEnumItem(env, object, "DIRECTION_HORIZONTAL", Global::Resource::DIRECTION_HORIZONTAL)); + + return object; +} + +static napi_value InitScreenDensityObject(napi_env env) +{ + napi_value object; + NAPI_CALL(env, napi_create_object(env, &object)); + + NAPI_CALL(env, SetEnumItem(env, object, "SCREEN_DENSITY_NOT_SET", Global::Resource::SCREEN_DENSITY_NOT_SET)); + NAPI_CALL(env, SetEnumItem(env, object, "SCREEN_DENSITY_SDPI", Global::Resource::SCREEN_DENSITY_SDPI)); + NAPI_CALL(env, SetEnumItem(env, object, "SCREEN_DENSITY_MDPI", Global::Resource::SCREEN_DENSITY_MDPI)); + NAPI_CALL(env, SetEnumItem(env, object, "SCREEN_DENSITY_LDPI", Global::Resource::SCREEN_DENSITY_LDPI)); + NAPI_CALL(env, SetEnumItem(env, object, "SCREEN_DENSITY_XLDPI", Global::Resource::SCREEN_DENSITY_XLDPI)); + NAPI_CALL(env, SetEnumItem(env, object, "SCREEN_DENSITY_XXLDPI", Global::Resource::SCREEN_DENSITY_XXLDPI)); + NAPI_CALL(env, SetEnumItem(env, object, "SCREEN_DENSITY_XXXLDPI", Global::Resource::SCREEN_DENSITY_XXXLDPI)); + + return object; +} + +/* + * The module initialization. + */ +static napi_value ConfigurationConstantInit(napi_env env, napi_value exports) +{ + napi_value colorMode = InitColorModeObject(env); + NAPI_ASSERT(env, colorMode != nullptr, "failed to create color mode object"); + + napi_value direction = InitDirectionObject(env); + NAPI_ASSERT(env, direction != nullptr, "failed to create direction object"); + + napi_value screenDensity = InitScreenDensityObject(env); + NAPI_ASSERT(env, screenDensity != nullptr, "failed to create screen density object"); + + napi_property_descriptor exportObjs[] = { + DECLARE_NAPI_PROPERTY("ColorMode", colorMode), + DECLARE_NAPI_PROPERTY("Direction", direction), + DECLARE_NAPI_PROPERTY("ScreenDensity", screenDensity), + }; + + napi_status status = napi_define_properties(env, exports, sizeof(exportObjs) / sizeof(exportObjs[0]), exportObjs); + NAPI_ASSERT(env, status == napi_ok, "failed to define properties for exports"); + + return exports; +} + +/* + * The module definition. + */ +static napi_module _module = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = ConfigurationConstantInit, + .nm_modname = "application.ConfigurationConstant", + .nm_priv = ((void *)0), + .reserved = {0} +}; + +/* + * The module registration. + */ +extern "C" __attribute__((constructor)) void RegisterModule(void) +{ + napi_module_register(&_module); +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/dataShare/BUILD.gn b/interfaces/kits/napi/aafwk/dataShare/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..46974434f6a95dfcba0199e19aa86de21357f4a1 --- /dev/null +++ b/interfaces/kits/napi/aafwk/dataShare/BUILD.gn @@ -0,0 +1,69 @@ +# 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("//build/ohos.gni") + +ohos_shared_library("datashare") { + include_dirs = [ + "//foundation/ace/napi/interfaces/kits", + "//third_party/node/src", + "//third_party/libuv/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/dataShare", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_rdb/include", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/common/include", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_dataability/include", + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_resultset/include", + ] + + sources = [ + "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/common/src/js_utils.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", + "napi_datashare_helper.cpp", + "native_datashare_module.cpp", + ] + + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/dataobs_manager:dataobs_manager", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", + "//foundation/ace/napi:ace_napi", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/libuv:uv_static", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:want", + "ability_runtime:ability_manager", + "ability_runtime:app_manager", + "ability_runtime:napi_base_context", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "native_appdatamgr:native_appdatafwk", + "native_appdatamgr:native_dataability", + "native_appdatamgr:native_rdb", + ] + + relative_install_dir = "module/data" + + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/kits/napi/aafwk/dataShare/data_share_common.h b/interfaces/kits/napi/aafwk/dataShare/data_share_common.h new file mode 100644 index 0000000000000000000000000000000000000000..b462002faa4063d97b4cdce433f89a989e8dca4f --- /dev/null +++ b/interfaces/kits/napi/aafwk/dataShare/data_share_common.h @@ -0,0 +1,360 @@ +/* + * 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_COMMON_H +#define OHOS_APPEXECFWK_DATASHARE_COMMON_H +#include "ability.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" +#include "napi_common.h" +#include "napi_common_util.h" +#include "values_bucket.h" +#include "want.h" + +using Want = OHOS::AAFwk::Want; +using Ability = OHOS::AppExecFwk::Ability; +using AbilityStartSetting = OHOS::AppExecFwk::AbilityStartSetting; + +namespace OHOS { +namespace AppExecFwk { +struct CallAbilityParam { + Want want; + int requestCode = 0; + bool forResultOption = false; + std::shared_ptr setting = nullptr; +}; + +struct OnAbilityCallback { + int requestCode = 0; + int resultCode = 0; + Want resultData; + CallbackInfo cb; +}; + +struct ContinueAbilityOptionsInfo { + bool reversible = false; + std::string deviceId; +}; + +struct AsyncCallbackInfo { + CallbackInfo cbInfo; + napi_async_work asyncWork = nullptr; + napi_deferred deferred = nullptr; + Ability *ability = nullptr; + CallAbilityParam param; + CallbackInfo aceCallback; + bool native_result; + AbilityType abilityType = AbilityType::UNKNOWN; + int errCode = 0; + ContinueAbilityOptionsInfo optionInfo; +}; + +struct CBBase { + CallbackInfo cbInfo; + napi_async_work asyncWork; + napi_deferred deferred; + Ability *ability = nullptr; + AbilityType abilityType = AbilityType::UNKNOWN; + int errCode = 0; +}; + +struct AppInfo_ { + std::string name; + std::string description; + int32_t descriptionId = 0; + bool systemApp = false; + bool enabled = true; // no data + std::string label; + std::string labelId; + std::string icon; + std::string iconId; + std::string process; + int32_t supportedModes = 0; + std::vector moduleSourceDirs; + std::vector permissions; + std::vector moduleInfos; + std::string entryDir; +}; + +struct AppInfoCB { + CBBase cbBase; + AppInfo_ appInfo; +}; + +struct AppTypeCB { + CBBase cbBase; + std::string name; +}; + +struct AbilityInfo_ { + std::string bundleName; + std::string name; + std::string label; + std::string description; + std::string icon; + int32_t labelId; + int32_t descriptionId; + int32_t iconId; + std::string moduleName; + std::string process; + std::string targetAbility; // no data + int32_t backgroundModes; // no data + bool isVisible = true; + bool formEnabled = false; // no data + int32_t type = 0; + int32_t subType = 0; // no data + int32_t orientation = 0; + int32_t launchMode = 0; + std::vector permissions; + std::vector deviceTypes; + std::vector deviceCapabilities; + std::string readPermission; // no data + std::string writePermission; // no data + AppInfo_ appInfo; + int32_t formEntity; // no data + int32_t minFormHeight; // no data + int32_t defaultFormHeight; // no data + int32_t minFormWidth; // no data + int32_t defaultFormWidth; // no data + std::string uri; +}; +struct AbilityInfoCB { + CBBase cbBase; + AbilityInfo_ abilityInfo; +}; + +struct AbilityNameCB { + CBBase cbBase; + std::string name; +}; + +struct ProcessInfoCB { + CBBase cbBase; + pid_t pid = 0; + std::string processName; +}; + +struct ProcessNameCB { + CBBase cbBase; + std::string processName; +}; + +struct CallingBundleCB { + CBBase cbBase; + std::string callingBundleName; +}; + +struct GetOrCreateLocalDirCB { + CBBase cbBase; + std::string rootDir; +}; + +struct DatabaseDirCB { + CBBase cbBase; + std::string dataBaseDir; +}; + +struct PreferencesDirCB { + CBBase cbBase; + std::string preferencesDir; +}; + +struct ElementNameCB { + CBBase cbBase; + std::string deviceId; + std::string bundleName; + std::string abilityName; + std::string uri; + std::string shortName; +}; + +struct HapModuleInfo_ { + std::string name; + std::string description; + int32_t descriptionId = 0; // no data + std::string icon; + std::string label; + int32_t labelId = 0; // no data + int32_t iconId = 0; // no data + std::string backgroundImg; + int32_t supportedModes = 0; + std::vector reqCapabilities; + std::vector deviceTypes; + std::vector abilityInfos; + std::string moduleName; + std::string mainAbilityName; // no data + bool installationFree; // no data +}; + +struct HapModuleInfoCB { + CBBase cbBase; + HapModuleInfo_ hapModuleInfo; +}; + +struct DataShareHelperCB { + CBBase cbBase; + napi_ref uri = nullptr; + napi_value result = nullptr; +}; + +struct DSHelperInsertCB { + CBBase cbBase; + DataShareHelper *dataShareHelper = nullptr; + std::string uri; + NativeRdb::ValuesBucket valueBucket; + int result = 0; + int execResult; +}; + +class NAPIAbilityConnection; +struct AbilityConnectionCB { + napi_env env; + napi_ref callback[3] = {0}; // onConnect/onDisconnect/onFailed + int resultCode = 0; + ElementName elementName; + sptr connection; +}; +struct ConnectAbilityCB { + CBBase cbBase; + Want want; + sptr abilityConnection; + AbilityConnectionCB abilityConnectionCB; + int64_t id; + bool result; + int errCode = 0; +}; + +struct DSHelperNotifyChangeCB { + CBBase cbBase; + DataShareHelper *dataShareHelper = nullptr; + std::string uri; + int execResult; +}; + +class NAPIDataShareObserver; +struct DSHelperOnOffCB { + CBBase cbBase; + DataShareHelper *dataShareHelper = nullptr; + sptr observer; + std::string uri; + int result = 0; + std::vector NotifyList; + std::vector DestoryList; +}; + +struct ShowOnLockScreenCB { + CBBase cbBase; + bool isShow; +}; + +struct DSHelperGetTypeCB { + CBBase cbBase; + DataShareHelper *dataShareHelper = nullptr; + std::string uri; + std::string result = ""; + int execResult; +}; + +struct DSHelperGetFileTypesCB { + CBBase cbBase; + DataShareHelper *dataShareHelper = nullptr; + std::string uri; + std::string mimeTypeFilter; + std::vector result; + int execResult; +}; + +struct DSHelperNormalizeUriCB { + CBBase cbBase; + DataShareHelper *dataShareHelper = nullptr; + std::string uri; + std::string result = ""; + int execResult; +}; + +struct DSHelperDenormalizeUriCB { + CBBase cbBase; + DataShareHelper *dataShareHelper = nullptr; + std::string uri; + std::string result = ""; + int execResult; +}; + +struct DSHelperDeleteCB { + CBBase cbBase; + DataShareHelper *dataShareHelper = nullptr; + std::string uri; + NativeRdb::DataAbilityPredicates predicates; + int result = 0; + int execResult; +}; + +struct DSHelperQueryCB { + CBBase cbBase; + DataShareHelper *dataShareHelper = nullptr; + std::string uri; + std::vector columns; + NativeRdb::DataAbilityPredicates predicates; + std::shared_ptr result; + int execResult; +}; + +struct DSHelperUpdateCB { + CBBase cbBase; + DataShareHelper *dataShareHelper = nullptr; + std::string uri; + NativeRdb::ValuesBucket valueBucket; + NativeRdb::DataAbilityPredicates predicates; + int result = 0; + int execResult; +}; + +struct DSHelperBatchInsertCB { + CBBase cbBase; + DataShareHelper *dataShareHelper = nullptr; + std::string uri; + std::vector values; + int result = 0; + int execResult; +}; + +struct DSHelperOpenFileCB { + CBBase cbBase; + DataShareHelper *dataShareHelper = nullptr; + std::string uri; + std::string mode; + int result = 0; + int execResult; +}; + +struct DSHelperReleaseCB { + CBBase cbBase; + DataShareHelper *dataShareHelper = nullptr; + bool result = false; +}; + +struct DSHelperExecuteBatchCB { + CBBase cbBase; + std::string uri; + std::vector> operations; + DataShareHelper *dataShareHelper = nullptr; + std::vector> result; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif /* OHOS_APPEXECFWK_DATASHARE_COMMON_H */ diff --git a/interfaces/kits/napi/aafwk/dataShare/napi_datashare_helper.cpp b/interfaces/kits/napi/aafwk/dataShare/napi_datashare_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..98c264fbbfa049baa115f9168ef468fd1891ff9a --- /dev/null +++ b/interfaces/kits/napi/aafwk/dataShare/napi_datashare_helper.cpp @@ -0,0 +1,3322 @@ +/* + * 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 "napi_datashare_helper.h" + +#include +#include +#include + +#include "datashare_helper.h" +#include "data_ability_observer_interface.h" +#include "uri.h" + +#include "data_ability_result.h" +#include "hilog_wrapper.h" +#include "message_parcel.h" +#include "napi_base_context.h" +#include "napi_data_ability_predicates.h" +#include "napi_rdb_predicates.h" +#include "napi_result_set.h" +#include "securec.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace AppExecFwk { +namespace { +const std::string DATASHARE_CLASS_NAME = "DataShareHelper"; +constexpr int NO_ERROR = 0; +constexpr int INVALID_PARAMETER = -1; + +std::string NapiValueToStringUtf8(napi_env env, napi_value value) +{ + std::string result = ""; + return UnwrapStringFromJS(env, value, result); +} + +bool NapiValueToArrayStringUtf8(napi_env env, napi_value param, std::vector &result) +{ + return UnwrapArrayStringFromJS(env, param, result); +} +} + +std::list> g_dataShareHelperList; +static napi_ref g_constructorRef = nullptr; + +/** + * @brief acquireDataAbilityHelper processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param dataShareHelperCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value AcquireDataShareHelperWrap(napi_env env, napi_callback_info info, DataShareHelperCB *dataShareHelperCB) +{ + HILOG_INFO("%{public}s,called", __func__); + if (dataShareHelperCB == nullptr) { + HILOG_ERROR("%{public}s,dataShareHelperCB == nullptr", __func__); + return nullptr; + } + + size_t requireArgc = ARGS_THREE; + size_t argc = ARGS_THREE; + napi_value args[ARGS_THREE] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + if (argc > requireArgc) { + HILOG_ERROR("%{public}s, Wrong argument count %{public}zu.", __func__, argc); + return nullptr; + } + + napi_value result = nullptr; + napi_value cons = nullptr; + if (napi_get_reference_value(env, g_constructorRef, &cons) != napi_ok) { + return nullptr; + } + NAPI_CALL(env, napi_new_instance(env, cons, ARGS_THREE, args, &result)); + + if (!IsTypeForNapiValue(env, result, napi_object)) { + HILOG_ERROR("%{public}s, IsTypeForNapiValue isn`t object", __func__); + return nullptr; + } + + if (IsTypeForNapiValue(env, result, napi_null)) { + HILOG_ERROR("%{public}s, IsTypeForNapiValue is null", __func__); + return nullptr; + } + + if (IsTypeForNapiValue(env, result, napi_undefined)) { + HILOG_ERROR("%{public}s, IsTypeForNapiValue is undefined", __func__); + return nullptr; + } + + delete dataShareHelperCB; + dataShareHelperCB = nullptr; + HILOG_INFO("%{public}s,end", __func__); + return result; +} + +/** + * @brief AcquireDataAbilityHelper. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_AcquireDataShareHelperCommon(napi_env env, napi_callback_info info, AbilityType abilityType) +{ + HILOG_INFO("%{public}s,called", __func__); + DataShareHelperCB *dataShareHelperCB = new (std::nothrow) DataShareHelperCB; + if (dataShareHelperCB == nullptr) { + HILOG_ERROR("%{public}s, dataShareHelperCB == nullptr", __func__); + return WrapVoidToJS(env); + } + + dataShareHelperCB->cbBase.cbInfo.env = env; + dataShareHelperCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + dataShareHelperCB->cbBase.abilityType = abilityType; + napi_value ret = AcquireDataShareHelperWrap(env, info, dataShareHelperCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s, ret == nullptr", __func__); + if (dataShareHelperCB != nullptr) { + delete dataShareHelperCB; + dataShareHelperCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +/** + * @brief DataShareHelper NAPI method : CreateDataShareHelper. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_CreateDataShareHelper(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s, called", __func__); + return NAPI_AcquireDataShareHelperCommon(env, info, AbilityType::EXTENSION); +} + +/** + * @brief DataShareHelper NAPI module registration. + * + * @param env The environment that the Node-API call is invoked under. + * @param exports An empty object via the exports parameter as a convenience. + * + * @return The return value from Init is treated as the exports object for the module. + */ +napi_value DataShareHelperInit(napi_env env, napi_value exports) +{ + HILOG_INFO("%{public}s,called", __func__); + napi_property_descriptor properties[] = { + DECLARE_NAPI_FUNCTION("insert", NAPI_Insert), + DECLARE_NAPI_FUNCTION("notifyChange", NAPI_NotifyChange), + DECLARE_NAPI_FUNCTION("on", NAPI_Register), + DECLARE_NAPI_FUNCTION("off", NAPI_UnRegister), + DECLARE_NAPI_FUNCTION("delete", NAPI_Delete), + DECLARE_NAPI_FUNCTION("query", NAPI_Query), + DECLARE_NAPI_FUNCTION("update", NAPI_Update), + DECLARE_NAPI_FUNCTION("batchInsert", NAPI_BatchInsert), + DECLARE_NAPI_FUNCTION("openFile", NAPI_OpenFile), + DECLARE_NAPI_FUNCTION("getType", NAPI_GetType), + DECLARE_NAPI_FUNCTION("getFileTypes", NAPI_GetFileTypes), + DECLARE_NAPI_FUNCTION("normalizeUri", NAPI_NormalizeUri), + DECLARE_NAPI_FUNCTION("denormalizeUri", NAPI_DenormalizeUri), + DECLARE_NAPI_FUNCTION("release", NAPI_Release), + }; + + napi_value cons = nullptr; + NAPI_CALL(env, + napi_define_class(env, + DATASHARE_CLASS_NAME.c_str(), + NAPI_AUTO_LENGTH, + DataShareHelperConstructor, + nullptr, + sizeof(properties) / sizeof(*properties), + properties, + &cons)); + g_dataShareHelperList.clear(); + NAPI_CALL(env, napi_create_reference(env, cons, 1, &g_constructorRef)); + NAPI_CALL(env, napi_set_named_property(env, exports, DATASHARE_CLASS_NAME.c_str(), cons)); + + napi_property_descriptor export_properties[] = { + DECLARE_NAPI_FUNCTION("createDataShareHelper", NAPI_CreateDataShareHelper), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(export_properties) / sizeof(export_properties[0]), + export_properties)); + return exports; +} + +napi_value DataShareHelperConstructor(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s, called", __func__); + size_t argc = ARGS_THREE; + napi_value argv[ARGS_THREE] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + NAPI_ASSERT(env, argc > 0, "Wrong number of arguments"); + AAFwk::Want want; + OHOS::AppExecFwk::UnwrapWant(env, argv[PARAM1], want); + std::string strUri = NapiValueToStringUtf8(env, argv[PARAM2]); + std::shared_ptr dataShareHelper = nullptr; + bool isStageMode = false; + napi_status status = AbilityRuntime::IsStageContext(env, argv[PARAM0], isStageMode); + if (status != napi_ok || !isStageMode) { + auto ability = OHOS::AbilityRuntime::GetCurrentAbility(env); + NAPI_ASSERT(env, ability != nullptr, "DataShareHelperConstructor: failed to get native ability"); + HILOG_INFO("FA Model: ability = %{public}p strUri = %{public}s", ability, strUri.c_str()); + dataShareHelper = DataShareHelper::Creator(ability->GetContext(), want, std::make_shared(strUri)); + } else { + auto context = OHOS::AbilityRuntime::GetStageModeContext(env, argv[PARAM0]); + NAPI_ASSERT(env, context != nullptr, "DataShareHelperConstructor: failed to get native context"); + HILOG_INFO("Stage Model: context = %{public}p strUri = %{public}s", context.get(), strUri.c_str()); + dataShareHelper = DataShareHelper::Creator(context, want, std::make_shared(strUri)); + } + NAPI_ASSERT(env, dataShareHelper != nullptr, "DataShareHelperConstructor: dataShareHelper is nullptr"); + g_dataShareHelperList.emplace_back(dataShareHelper); + napi_wrap(env, thisVar, dataShareHelper.get(), [](napi_env env, void *data, void *hint) { + DataShareHelper *objectInfo = static_cast(data); + auto helper = std::find_if(registerInstances_.begin(), registerInstances_.end(), + [&objectInfo](const DSHelperOnOffCB *helper) { return helper->dataShareHelper == objectInfo; }); + if (helper != registerInstances_.end()) { + HILOG_INFO("DataShareHelper finalize_cb find helper"); + (*helper)->dataShareHelper->Release(); + delete *helper; + registerInstances_.erase(helper); + } + g_dataShareHelperList.remove_if([objectInfo](const std::shared_ptr &dataShareHelper) { + return objectInfo == dataShareHelper.get(); + }); + }, nullptr, nullptr); + HILOG_INFO("%{public}s,called end", __func__); + return thisVar; +} + +/** + * @brief DataShareHelper NAPI method : insert. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_Insert(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s, called", __func__); + DSHelperInsertCB *insertCB = new (std::nothrow) DSHelperInsertCB; + if (insertCB == nullptr) { + HILOG_ERROR("%{public}s, insertCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + insertCB->cbBase.cbInfo.env = env; + insertCB->cbBase.asyncWork = nullptr; + insertCB->cbBase.deferred = nullptr; + insertCB->cbBase.ability = nullptr; + + napi_value ret = InsertWrap(env, info, insertCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s, ret == nullptr.", __func__); + if (insertCB != nullptr) { + delete insertCB; + insertCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,called end", __func__); + return ret; +} + +/** + * @brief Insert processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param insertCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value InsertWrap(napi_env env, napi_callback_info info, DSHelperInsertCB *insertCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_THREE; + const size_t argcPromise = ARGS_TWO; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + insertCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, insertCB->uri.c_str()); + } else { + HILOG_ERROR("%{public}s, Wrong argument type.", __func__); + } + + insertCB->valueBucket.Clear(); + AnalysisValuesBucket(insertCB->valueBucket, env, args[PARAM1]); + + DataShareHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataShareHelper objectInfo = %{public}p", __func__, objectInfo); + insertCB->dataShareHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = InsertAsync(env, args, ARGS_TWO, insertCB); + } else { + ret = InsertPromise(env, insertCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +void AnalysisValuesBucket(NativeRdb::ValuesBucket &valuesBucket, const napi_env &env, const napi_value &arg) +{ + napi_value keys = 0; + napi_get_property_names(env, arg, &keys); + uint32_t arrLen = 0; + napi_status status = napi_get_array_length(env, keys, &arrLen); + if (status != napi_ok) { + HILOG_ERROR("ValuesBucket errr"); + return; + } + HILOG_INFO("ValuesBucket num:%{public}d ", arrLen); + for (size_t i = 0; i < arrLen; ++i) { + napi_value key = 0; + status = napi_get_element(env, keys, i, &key); + std::string keyStr = UnwrapStringFromJS(env, key); + napi_value value = 0; + napi_get_property(env, arg, key, &value); + + SetValuesBucketObject(valuesBucket, env, keyStr, value); + } +} + +void SetValuesBucketObject( + NativeRdb::ValuesBucket &valuesBucket, const napi_env &env, std::string keyStr, napi_value value) +{ + napi_valuetype valueType = napi_undefined; + napi_typeof(env, value, &valueType); + if (valueType == napi_string) { + std::string valueString = UnwrapStringFromJS(env, value); + HILOG_INFO("ValueObject type:%{public}d, key:%{public}s, value:%{public}s", + valueType, + keyStr.c_str(), + valueString.c_str()); + valuesBucket.PutString(keyStr, valueString); + } else if (valueType == napi_number) { + double valueNumber = 0; + napi_get_value_double(env, value, &valueNumber); + valuesBucket.PutDouble(keyStr, valueNumber); + HILOG_INFO( + "ValueObject type:%{public}d, key:%{public}s, value:%{public}lf", valueType, keyStr.c_str(), valueNumber); + } else if (valueType == napi_boolean) { + bool valueBool = false; + napi_get_value_bool(env, value, &valueBool); + HILOG_INFO( + "ValueObject type:%{public}d, key:%{public}s, value:%{public}d", valueType, keyStr.c_str(), valueBool); + valuesBucket.PutBool(keyStr, valueBool); + } else if (valueType == napi_null) { + valuesBucket.PutNull(keyStr); + HILOG_INFO("ValueObject type:%{public}d, key:%{public}s, value:null", valueType, keyStr.c_str()); + } else if (valueType == napi_object) { + HILOG_INFO("ValueObject type:%{public}d, key:%{public}s, value:Uint8Array", valueType, keyStr.c_str()); + valuesBucket.PutBlob(keyStr, ConvertU8Vector(env, value)); + } else { + HILOG_ERROR("valuesBucket error"); + } +} +napi_value InsertAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperInsertCB *insertCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || insertCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &insertCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + InsertExecuteCB, + InsertAsyncCompleteCB, + (void *)insertCB, + &insertCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, insertCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end", __func__); + return result; +} + +napi_value InsertPromise(napi_env env, DSHelperInsertCB *insertCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (insertCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + insertCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + InsertExecuteCB, + InsertPromiseCompleteCB, + (void *)insertCB, + &insertCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, insertCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end", __func__); + return promise; +} + +void InsertExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_Insert, worker pool thread execute."); + DSHelperInsertCB *insertCB = static_cast(data); + if (insertCB->dataShareHelper != nullptr) { + insertCB->execResult = INVALID_PARAMETER; + if (!insertCB->uri.empty()) { + OHOS::Uri uri(insertCB->uri); + insertCB->result = insertCB->dataShareHelper->Insert(uri, insertCB->valueBucket); + insertCB->execResult = NO_ERROR; + } + } else { + HILOG_ERROR("NAPI_Insert, dataShareHelper == nullptr."); + } + HILOG_INFO("NAPI_Insert, worker pool thread execute end."); +} + +void InsertAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_Insert, main event thread complete."); + DSHelperInsertCB *insertCB = static_cast(data); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, insertCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, insertCB->execResult); + napi_create_int32(env, insertCB->result, &result[PARAM1]); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (insertCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, insertCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, insertCB->cbBase.asyncWork)); + delete insertCB; + insertCB = nullptr; + HILOG_INFO("NAPI_Insert, main event thread complete end."); +} + +void InsertPromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_Insert, main event thread complete."); + DSHelperInsertCB *insertCB = static_cast(data); + napi_value result = nullptr; + napi_create_int32(env, insertCB->result, &result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, insertCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, insertCB->cbBase.asyncWork)); + delete insertCB; + insertCB = nullptr; + HILOG_INFO("NAPI_Insert, main event thread complete end."); +} + +/** + * @brief Parse the ValuesBucket parameters. + * + * @param param Indicates the want parameters saved the parse result. + * @param env The environment that the Node-API call is invoked under. + * @param args Indicates the arguments passed into the callback. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value UnwrapValuesBucket(std::string &value, napi_env env, napi_value args) +{ + HILOG_INFO("%{public}s,called", __func__); + napi_valuetype valueType = napi_undefined; + napi_typeof(env, args, &valueType); + if (valueType != napi_object) { + HILOG_ERROR("%{public}s, valueType != napi_object.", __func__); + return nullptr; + } + + std::string strValue = ""; + if (UnwrapStringByPropertyName(env, args, "value", strValue)) { + HILOG_INFO("%{public}s,strValue=%{public}s", __func__, strValue.c_str()); + value = strValue; + } else { + HILOG_ERROR("%{public}s, value == nullptr.", __func__); + return nullptr; + } + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + HILOG_INFO("%{public}s,end", __func__); + return result; +} + +/** + * @brief DataShareHelper NAPI method : notifyChange. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_NotifyChange(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DSHelperNotifyChangeCB *notifyChangeCB = new (std::nothrow) DSHelperNotifyChangeCB; + if (notifyChangeCB == nullptr) { + HILOG_ERROR("%{public}s, notifyChangeCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + notifyChangeCB->cbBase.cbInfo.env = env; + notifyChangeCB->cbBase.asyncWork = nullptr; + notifyChangeCB->cbBase.deferred = nullptr; + notifyChangeCB->cbBase.ability = nullptr; + + napi_value ret = NotifyChangeWrap(env, info, notifyChangeCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s, ret == nullptr.", __func__); + if (notifyChangeCB != nullptr) { + delete notifyChangeCB; + notifyChangeCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +/** + * @brief NotifyChange processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param notifyChangeCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value NotifyChangeWrap(napi_env env, napi_callback_info info, DSHelperNotifyChangeCB *notifyChangeCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_TWO; + const size_t argcPromise = ARGS_ONE; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + notifyChangeCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, notifyChangeCB->uri.c_str()); + } else { + HILOG_ERROR("%{public}s, Wrong argument type.", __func__); + } + + DataShareHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("DataShareHelper objectInfo = %{public}p", objectInfo); + notifyChangeCB->dataShareHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = NotifyChangeAsync(env, args, argcAsync, argcPromise, notifyChangeCB); + } else { + ret = NotifyChangePromise(env, notifyChangeCB); + } + return ret; +} + +napi_value NotifyChangeAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DSHelperNotifyChangeCB *notifyChangeCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || notifyChangeCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, ¬ifyChangeCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + NotifyChangeExecuteCB, + NotifyChangeAsyncCompleteCB, + (void *)notifyChangeCB, + ¬ifyChangeCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, notifyChangeCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + return result; +} + +napi_value NotifyChangePromise(napi_env env, DSHelperNotifyChangeCB *notifyChangeCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (notifyChangeCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + notifyChangeCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + NotifyChangeExecuteCB, + NotifyChangePromiseCompleteCB, + (void *)notifyChangeCB, + ¬ifyChangeCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, notifyChangeCB->cbBase.asyncWork)); + return promise; +} + +void NotifyChangeExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_NotifyChange, worker pool thread execute."); + DSHelperNotifyChangeCB *notifyChangeCB = static_cast(data); + if (notifyChangeCB->dataShareHelper != nullptr) { + notifyChangeCB->execResult = INVALID_PARAMETER; + if (!notifyChangeCB->uri.empty()) { + OHOS::Uri uri(notifyChangeCB->uri); + notifyChangeCB->dataShareHelper->NotifyChange(uri); + notifyChangeCB->execResult = NO_ERROR; + } else { + HILOG_ERROR("%{public}s, notifyChangeCB uri is empty.", __func__); + } + } +} + +void NotifyChangeAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_NotifyChange, main event thread complete."); + DSHelperNotifyChangeCB *notifyChangeCB = static_cast(data); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, notifyChangeCB->cbBase.cbInfo.callback, &callback)); + + if (!IsTypeForNapiValue(env, callback, napi_function)) { + delete notifyChangeCB; + notifyChangeCB = nullptr; + HILOG_INFO("NAPI_NotifyChange, callback is invalid."); + return; + } + + result[PARAM0] = GetCallbackErrorValue(env, notifyChangeCB->execResult); + result[PARAM1] = WrapVoidToJS(env); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (notifyChangeCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, notifyChangeCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, notifyChangeCB->cbBase.asyncWork)); + delete notifyChangeCB; + notifyChangeCB = nullptr; +} + +void NotifyChangePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_NotifyChange, main event thread complete."); + DSHelperNotifyChangeCB *notifyChangeCB = static_cast(data); + napi_value result = nullptr; + napi_create_int32(env, 0, &result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, notifyChangeCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, notifyChangeCB->cbBase.asyncWork)); + delete notifyChangeCB; + notifyChangeCB = nullptr; +} + +/** + * @brief DataShareHelper NAPI method : on. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_Register(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DSHelperOnOffCB *onCB = new (std::nothrow) DSHelperOnOffCB; + if (onCB == nullptr) { + HILOG_ERROR("%{public}s, onCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + onCB->cbBase.cbInfo.env = env; + onCB->cbBase.asyncWork = nullptr; + onCB->cbBase.deferred = nullptr; + onCB->cbBase.ability = nullptr; + + napi_value ret = RegisterWrap(env, info, onCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s, ret == nullptr.", __func__); + if (onCB != nullptr) { + delete onCB; + onCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,called end", __func__); + return ret; +} + +/** + * @brief On processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param insertCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value RegisterWrap(napi_env env, napi_callback_info info, DSHelperOnOffCB *onCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_THREE; + const size_t argcPromise = ARGS_TWO; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + onCB->result = NO_ERROR; + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + std::string type = NapiValueToStringUtf8(env, args[PARAM0]); + if (type == "dataChange") { + HILOG_INFO("%{public}s, Wrong type=%{public}s", __func__, type.c_str()); + } else { + HILOG_ERROR("%{public}s, Wrong argument type is %{public}s.", __func__, type.c_str()); + onCB->result = INVALID_PARAMETER; + } + } else { + HILOG_ERROR("%{public}s, Wrong argument type.", __func__); + onCB->result = INVALID_PARAMETER; + } + + NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); + if (valuetype == napi_string) { + onCB->uri = NapiValueToStringUtf8(env, args[PARAM1]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, onCB->uri.c_str()); + } else { + HILOG_ERROR("%{public}s, Wrong argument type.", __func__); + onCB->result = INVALID_PARAMETER; + } + + DataShareHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("DataShareHelper objectInfo = %{public}p", objectInfo); + onCB->dataShareHelper = objectInfo; + + ret = RegisterAsync(env, args, argcAsync, argcPromise, onCB); + return ret; +} + +napi_value RegisterAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DSHelperOnOffCB *onCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || onCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); + if (valuetype == napi_function) { + HILOG_INFO("valuetype is napi_function"); + NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &onCB->cbBase.cbInfo.callback)); + } else { + HILOG_INFO("not valuetype isn't napi_function"); + onCB->result = INVALID_PARAMETER; + } + + sptr observer(new (std::nothrow) NAPIDataShareObserver()); + observer->SetEnv(env); + observer->SetCallbackRef(onCB->cbBase.cbInfo.callback); + onCB->observer = observer; + + if (onCB->result == NO_ERROR) { + registerInstances_.emplace_back(onCB); + } + + NAPI_CALL(env, + napi_create_async_work( + env, + nullptr, + resourceName, + RegisterExecuteCB, + RegisterCompleteCB, + (void *)onCB, + &onCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, onCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + return result; +} + +void RegisterExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_Register, worker pool thread execute."); + DSHelperOnOffCB *onCB = static_cast(data); + if (onCB->dataShareHelper != nullptr) { + if (onCB->result != INVALID_PARAMETER && !onCB->uri.empty() && onCB->cbBase.cbInfo.callback != nullptr) { + OHOS::Uri uri(onCB->uri); + onCB->dataShareHelper->RegisterObserver(uri, onCB->observer); + } else { + HILOG_ERROR("%{public}s, dataShareHelper uri is empty or callback is nullptr.", __func__); + } + } +} + +void RegisterCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_Register, main event thread complete."); + DSHelperOnOffCB *onCB = static_cast(data); + if (onCB == nullptr) { + HILOG_ERROR("%{public}s, input params onCB is nullptr.", __func__); + return; + } + if (onCB->result == NO_ERROR) { + return; + } + HILOG_INFO("NAPI_Register, input params onCB is invalid params, will be release"); + onCB->observer->ReleaseJSCallback(); + delete onCB; + onCB = nullptr; + HILOG_INFO("NAPI_Register, main event thread complete over an release invalid onCB."); +} + +/** + * @brief DataShareHelper NAPI method : Off. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_UnRegister(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DSHelperOnOffCB *offCB = new (std::nothrow) DSHelperOnOffCB; + if (offCB == nullptr) { + HILOG_ERROR("%{public}s, offCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + offCB->cbBase.cbInfo.env = env; + offCB->cbBase.asyncWork = nullptr; + offCB->cbBase.deferred = nullptr; + offCB->cbBase.ability = nullptr; + + napi_value ret = UnRegisterWrap(env, info, offCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s, ret == nullptr.", __func__); + if (offCB != nullptr) { + delete offCB; + offCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,called end", __func__); + return ret; +} + +/** + * @brief Off processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param insertCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value UnRegisterWrap(napi_env env, napi_callback_info info, DSHelperOnOffCB *offCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argc = ARGS_THREE; + const size_t argcPromise = ARGS_TWO; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); + NAPI_ASSERT(env, argc <= argCountWithAsync && argc <= ARGS_MAX_COUNT, "UnRegisterWrap: Wrong argument count"); + offCB->result = INVALID_PARAMETER; + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + std::string type = NapiValueToStringUtf8(env, args[PARAM0]); + if (type == "dataChange") { + offCB->result = NO_ERROR; + } + } + offCB->uri = ""; + if (argc > ARGS_TWO) { + NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); + if (valuetype == napi_string) { + offCB->uri = NapiValueToStringUtf8(env, args[PARAM1]); + } else { + offCB->result = INVALID_PARAMETER; + } + NAPI_CALL(env, napi_typeof(env, args[PARAM2], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[PARAM2], 1, &offCB->cbBase.cbInfo.callback)); + } else { + offCB->result = INVALID_PARAMETER; + } + } else { + NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); + if (valuetype == napi_string) { + offCB->uri = NapiValueToStringUtf8(env, args[PARAM1]); + } else if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[PARAM1], 1, &offCB->cbBase.cbInfo.callback)); + } else { + offCB->result = INVALID_PARAMETER; + } + } + HILOG_INFO("%{public}s,uri=%{public}s", __func__, offCB->uri.c_str()); + DataShareHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + offCB->dataShareHelper = objectInfo; + ret = UnRegisterAsync(env, args, argc, argcPromise, offCB); + return ret; +} + +napi_value UnRegisterAsync( + napi_env env, napi_value *args, size_t argc, const size_t argcPromise, DSHelperOnOffCB *offCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || offCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + if (offCB->result == NO_ERROR) { + FindRegisterObs(env, offCB); + } + + NAPI_CALL(env, + napi_create_async_work( + env, + nullptr, + resourceName, + UnRegisterExecuteCB, + UnRegisterCompleteCB, + (void *)offCB, + &offCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, offCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + return result; +} + +static void FindRegisterObsByCallBack(napi_env env, DSHelperOnOffCB *data) +{ + HILOG_INFO("NAPI_UnRegister, UnRegisterExecuteCB callback is not null."); + if (data == nullptr || data->dataShareHelper == nullptr) { + HILOG_ERROR("NAPI_UnRegister, param is null."); + return; + } + napi_value callbackA = 0; + napi_get_reference_value(data->cbBase.cbInfo.env, data->cbBase.cbInfo.callback, &callbackA); + std::string strUri = data->uri; + do { + auto helper = std::find_if( + registerInstances_.begin(), + registerInstances_.end(), + [callbackA, strUri](const DSHelperOnOffCB *helper) { + bool result = false; + if (helper == nullptr || helper->cbBase.cbInfo.callback == nullptr) { + HILOG_ERROR("%{public}s is nullptr", ((helper == nullptr) ? "helper" : "cbBase.cbInfo.callback")); + return result; + } + if (helper->uri != strUri) { + HILOG_ERROR("uri inconsistent, h=[%{public}s] u=[%{public}s]", helper->uri.c_str(), strUri.c_str()); + return result; + } + napi_value callbackB = 0; + napi_get_reference_value(helper->cbBase.cbInfo.env, helper->cbBase.cbInfo.callback, &callbackB); + auto ret = napi_strict_equals(helper->cbBase.cbInfo.env, callbackA, callbackB, &result); + HILOG_INFO("NAPI_UnRegister cb equals status=%{public}d result=%{public}d.", ret, result); + return result; + }); + if (helper != registerInstances_.end()) { + data->NotifyList.emplace_back(*helper); + registerInstances_.erase(helper); + HILOG_INFO("NAPI_UnRegister Instances erase size = %{public}zu", registerInstances_.size()); + } else { + HILOG_INFO("NAPI_UnRegister not match any callback. %{public}zu", registerInstances_.size()); + break; + } + } while (true); + HILOG_INFO("NAPI_UnRegister, UnRegisterExecuteCB FindRegisterObsByCallBack Called End."); +} + +void FindRegisterObs(napi_env env, DSHelperOnOffCB *data) +{ + HILOG_INFO("NAPI_UnRegister, FindRegisterObs main event thread execute."); + if (data == nullptr || data->dataShareHelper == nullptr) { + HILOG_ERROR("NAPI_UnRegister, param is null."); + return; + } + if (data->cbBase.cbInfo.callback != nullptr) { + HILOG_INFO("NAPI_UnRegister, UnRegisterExecuteCB callback is not null."); + FindRegisterObsByCallBack(env, data); + } else { + if (data->uri.empty()) { + HILOG_ERROR("NAPI_UnRegister, error: uri is empty."); + return; + } + + HILOG_INFO("NAPI_UnRegister, uri=%{public}s.", data->uri.c_str()); + std::string strUri = data->uri; + do { + auto helper = std::find_if(registerInstances_.begin(), registerInstances_.end(), + [strUri](const DSHelperOnOffCB *helper) { return helper->uri == strUri; }); + if (helper != registerInstances_.end()) { + OHOS::Uri uri((*helper)->uri); + data->NotifyList.emplace_back(*helper); + registerInstances_.erase(helper); + HILOG_INFO("NAPI_UnRegister Instances erase size = %{public}zu", registerInstances_.size()); + } else { + HILOG_INFO("NAPI_UnRegister not match any uri."); + break; + } + } while (true); + } + HILOG_INFO("NAPI_UnRegister, FindRegisterObs main event thread execute.end %{public}zu", data->NotifyList.size()); +} + +void UnRegisterExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_UnRegister, UnRegisterExecuteCB main event thread execute."); + DSHelperOnOffCB *offCB = static_cast(data); + if (offCB == nullptr || offCB->dataShareHelper == nullptr) { + HILOG_ERROR("NAPI_UnRegister, param is null."); + if (offCB != nullptr) { + delete offCB; + offCB = nullptr; + } + return; + } + HILOG_INFO("NAPI_UnRegister, offCB->DestoryList size is %{public}zu", offCB->NotifyList.size()); + for (auto &iter : offCB->NotifyList) { + if (iter != nullptr && iter->observer != nullptr) { + OHOS::Uri uri(iter->uri); + iter->dataShareHelper->UnregisterObserver(uri, iter->observer); + offCB->DestoryList.emplace_back(iter); + } + } + offCB->NotifyList.clear(); + HILOG_INFO("NAPI_UnRegister, UnRegisterExecuteCB main event thread execute. end"); +} + +void UnRegisterCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_UnRegister, main event thread complete."); + // cannot run it in executeCB, because need to use napi_strict_equals compare callbacks. + DSHelperOnOffCB *offCB = static_cast(data); + if (offCB == nullptr || offCB->dataShareHelper == nullptr) { + HILOG_ERROR("NAPI_UnRegister, param is null."); + if (offCB != nullptr) { + delete offCB; + offCB = nullptr; + } + return; + } + HILOG_INFO("NAPI_UnRegister, offCB->DestoryList size is %{public}zu", offCB->DestoryList.size()); + for (auto &iter : offCB->DestoryList) { + HILOG_INFO("NAPI_UnRegister ReleaseJSCallback. 1 ---"); + if (iter->observer != nullptr) { + if (iter->observer->GetWorkPre() == 1 && iter->observer->GetWorkRun() == 0) { + iter->observer->SetAssociatedObject(iter); + iter->observer->ChangeWorkInt(); + HILOG_INFO("NAPI_UnRegister ReleaseJSCallback. 3 ---"); + } else { + iter->observer->ReleaseJSCallback(); + delete iter; + iter = nullptr; + HILOG_INFO("NAPI_UnRegister ReleaseJSCallback. 4 ---"); + } + } + } + + offCB->DestoryList.clear(); + if (offCB != nullptr) { + delete offCB; + offCB = nullptr; + } + + HILOG_INFO("NAPI_UnRegister, main event thread complete. end"); +} + +void NAPIDataShareObserver::ReleaseJSCallback() +{ + if (ref_ == nullptr) { + HILOG_ERROR("NAPIDataShareObserver::ReleaseJSCallback, ref_ is null."); + return; + } + napi_delete_reference(env_, ref_); + HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end", __func__); +} + +void NAPIDataShareObserver::SetAssociatedObject(DSHelperOnOffCB* object) +{ + onCB_ = object; + HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end", __func__); +} + +void NAPIDataShareObserver::ChangeWorkPre() +{ + HILOG_INFO("NAPIDataShareObserver::%{public}s, called.", __func__); + std::lock_guard lock_l(mutex_); + workPre_ = 1; + HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end %{public}d", __func__, workPre_); +} +void NAPIDataShareObserver::ChangeWorkRun() +{ + workRun_ = 1; + HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end %{public}d", __func__, workRun_); +} +void NAPIDataShareObserver::ChangeWorkInt() +{ + intrust_ = 1; + HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end %{public}d", __func__, intrust_); +} + +void NAPIDataShareObserver::ChangeWorkPreDone() +{ + HILOG_INFO("NAPIDataShareObserver::%{public}s, called.", __func__); + std::lock_guard lock_l(mutex_); + workPre_ = 0; + HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end %{public}d", __func__, workPre_); +} + +void NAPIDataShareObserver::ChangeWorkRunDone() +{ + workRun_ = 0; + intrust_ = 0; + HILOG_INFO("NAPIDataShareObserver::%{public}s, called end %{public}d %{public}d", __func__, workRun_, intrust_); +} + +int NAPIDataShareObserver::GetWorkPre() +{ + HILOG_INFO("NAPIDataShareObserver::%{public}s, called.", __func__); + std::lock_guard lock_l(mutex_); + HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end %{public}d", __func__, workPre_); + return workPre_; +} + +int NAPIDataShareObserver::GetWorkInt() +{ + HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end %{public}d", __func__, intrust_); + return intrust_; +} + +int NAPIDataShareObserver::GetWorkRun() +{ + HILOG_INFO("NAPIDataShareObserver::%{public}s, called. %{public}d", __func__, workRun_); + return workRun_; +} + +const DSHelperOnOffCB* NAPIDataShareObserver::GetAssociatedObject(void) +{ + HILOG_INFO("NAPIDataShareObserver::%{public}s, called.", __func__); + return onCB_; +} + +void NAPIDataShareObserver::SetEnv(const napi_env &env) +{ + env_ = env; + HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end", __func__); +} + +void NAPIDataShareObserver::SetCallbackRef(const napi_ref &ref) +{ + ref_ = ref; + HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end", __func__); +} + +static void OnChangeJSThreadWorker(uv_work_t *work, int status) +{ + HILOG_INFO("OnChange, uv_queue_work"); + if (work == nullptr) { + HILOG_ERROR("OnChange, uv_queue_work input work is nullptr"); + return; + } + DSHelperOnOffCB *onCB = (DSHelperOnOffCB *)work->data; + NAPIDataShareObserver* obs = onCB->observer; + onCB->observer = nullptr; + if (obs != nullptr) { + obs->ChangeWorkRun(); + } + napi_value result[ARGS_TWO] = {0}; + result[PARAM0] = GetCallbackErrorValue(onCB->cbBase.cbInfo.env, NO_ERROR); + napi_value callback = 0; + napi_value undefined = 0; + napi_get_undefined(onCB->cbBase.cbInfo.env, &undefined); + napi_value callResult = 0; + napi_get_reference_value(onCB->cbBase.cbInfo.env, onCB->cbBase.cbInfo.callback, &callback); + napi_call_function(onCB->cbBase.cbInfo.env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); + if (obs != nullptr) { + if (obs->GetWorkInt() == 1) { + obs->ReleaseJSCallback(); + const DSHelperOnOffCB* assicuated = obs->GetAssociatedObject(); + if (assicuated != nullptr) { + HILOG_INFO("OnChange, uv_queue_work ReleaseJSCallback Called"); + obs->SetAssociatedObject(nullptr); + delete assicuated; + assicuated = nullptr; + } + } else { + obs->ChangeWorkRunDone(); + obs->ChangeWorkPreDone(); + } + } + if (onCB != nullptr) { + delete onCB; + onCB = nullptr; + } + if (work != nullptr) { + delete work; + work = nullptr; + } + HILOG_INFO("OnChange, uv_queue_work. end"); +} + +void NAPIDataShareObserver::OnChange() +{ + if (ref_ == nullptr) { + HILOG_ERROR("%{public}s, OnChange ref is nullptr.", __func__); + return; + } + ChangeWorkPre(); + uv_loop_s *loop = nullptr; + napi_get_uv_event_loop(env_, &loop); + if (loop == nullptr) { + HILOG_ERROR("%{public}s, loop == nullptr.", __func__); + ChangeWorkPreDone(); + return; + } + uv_work_t *work = new uv_work_t; + if (work == nullptr) { + HILOG_ERROR("%{public}s, work==nullptr.", __func__); + ChangeWorkPreDone(); + return; + } + DSHelperOnOffCB *onCB = new (std::nothrow) DSHelperOnOffCB; + if (onCB == nullptr) { + HILOG_ERROR("%{public}s, onCB == nullptr.", __func__); + if (work != nullptr) { + delete work; + work = nullptr; + } + ChangeWorkPreDone(); + return; + } + onCB->cbBase.cbInfo.env = env_; + onCB->cbBase.cbInfo.callback = ref_; + onCB->observer = this; + work->data = (void *)onCB; + int rev = uv_queue_work( + loop, + work, + [](uv_work_t *work) {}, + OnChangeJSThreadWorker); + if (rev != 0) { + if (onCB != nullptr) { + delete onCB; + onCB = nullptr; + } + if (work != nullptr) { + delete work; + work = nullptr; + } + } + HILOG_INFO("%{public}s, called. end", __func__); +} + +napi_value NAPI_GetType(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DSHelperGetTypeCB *gettypeCB = new (std::nothrow) DSHelperGetTypeCB; + if (gettypeCB == nullptr) { + HILOG_ERROR("%{public}s, gettypeCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + gettypeCB->cbBase.cbInfo.env = env; + gettypeCB->cbBase.asyncWork = nullptr; + gettypeCB->cbBase.deferred = nullptr; + gettypeCB->cbBase.ability = nullptr; + + napi_value ret = GetTypeWrap(env, info, gettypeCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (gettypeCB != nullptr) { + delete gettypeCB; + gettypeCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value GetTypeWrap(napi_env env, napi_callback_info info, DSHelperGetTypeCB *gettypeCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_TWO; + const size_t argcPromise = ARGS_ONE; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + gettypeCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, gettypeCB->uri.c_str()); + } else { + HILOG_ERROR("%{public}s, Wrong argument type.", __func__); + } + + DataShareHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataShareHelper objectInfo = %{public}p", __func__, objectInfo); + gettypeCB->dataShareHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = GetTypeAsync(env, args, ARGS_ONE, gettypeCB); + } else { + ret = GetTypePromise(env, gettypeCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value GetTypeAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperGetTypeCB *gettypeCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || gettypeCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &gettypeCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetTypeExecuteCB, + GetTypeAsyncCompleteCB, + (void *)gettypeCB, + &gettypeCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, gettypeCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end", __func__); + return result; +} + +napi_value GetTypePromise(napi_env env, DSHelperGetTypeCB *gettypeCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (gettypeCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + gettypeCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetTypeExecuteCB, + GetTypePromiseCompleteCB, + (void *)gettypeCB, + &gettypeCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, gettypeCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +void GetTypeExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_GetType, worker pool thread execute."); + DSHelperGetTypeCB *gettypeCB = static_cast(data); + if (gettypeCB->dataShareHelper != nullptr) { + gettypeCB->execResult = INVALID_PARAMETER; + if (!gettypeCB->uri.empty()) { + OHOS::Uri uri(gettypeCB->uri); + gettypeCB->result = gettypeCB->dataShareHelper->GetType(uri); + gettypeCB->execResult = NO_ERROR; + } else { + HILOG_ERROR("NAPI_GetType, dataShareHelper uri is empty."); + } + } else { + HILOG_ERROR("NAPI_GetType, dataShareHelper == nullptr."); + } + HILOG_INFO("NAPI_GetType, worker pool thread execute end."); +} + +void GetTypeAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetType, main event thread complete."); + DSHelperGetTypeCB *gettypeCB = static_cast(data); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, gettypeCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, gettypeCB->execResult); + napi_create_string_utf8(env, gettypeCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1]); + + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (gettypeCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, gettypeCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, gettypeCB->cbBase.asyncWork)); + delete gettypeCB; + gettypeCB = nullptr; + HILOG_INFO("NAPI_GetType, main event thread complete end."); +} + +void GetTypePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetType, main event thread complete."); + DSHelperGetTypeCB *gettypeCB = static_cast(data); + napi_value result = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, gettypeCB->result.c_str(), NAPI_AUTO_LENGTH, &result)); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, gettypeCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, gettypeCB->cbBase.asyncWork)); + delete gettypeCB; + gettypeCB = nullptr; + HILOG_INFO("NAPI_GetType, main event thread complete end."); +} + +napi_value NAPI_GetFileTypes(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DSHelperGetFileTypesCB *getfiletypesCB = new (std::nothrow) DSHelperGetFileTypesCB; + if (getfiletypesCB == nullptr) { + HILOG_ERROR("%{public}s, getfiletypesCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + getfiletypesCB->cbBase.cbInfo.env = env; + getfiletypesCB->cbBase.asyncWork = nullptr; + getfiletypesCB->cbBase.deferred = nullptr; + getfiletypesCB->cbBase.ability = nullptr; + + napi_value ret = GetFileTypesWrap(env, info, getfiletypesCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (getfiletypesCB != nullptr) { + delete getfiletypesCB; + getfiletypesCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value GetFileTypesWrap(napi_env env, napi_callback_info info, DSHelperGetFileTypesCB *getfiletypesCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_THREE; + const size_t argcPromise = ARGS_TWO; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + getfiletypesCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, getfiletypesCB->uri.c_str()); + } + + NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); + if (valuetype == napi_string) { + getfiletypesCB->mimeTypeFilter = NapiValueToStringUtf8(env, args[PARAM1]); + HILOG_INFO("%{public}s,mimeTypeFilter=%{public}s", __func__, getfiletypesCB->mimeTypeFilter.c_str()); + } + + DataShareHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataShareHelper objectInfo = %{public}p", __func__, objectInfo); + getfiletypesCB->dataShareHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = GetFileTypesAsync(env, args, ARGS_TWO, getfiletypesCB); + } else { + ret = GetFileTypesPromise(env, getfiletypesCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} +napi_value GetFileTypesAsync( + napi_env env, napi_value *args, const size_t argCallback, DSHelperGetFileTypesCB *getfiletypesCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || getfiletypesCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &getfiletypesCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetFileTypesExecuteCB, + GetFileTypesAsyncCompleteCB, + (void *)getfiletypesCB, + &getfiletypesCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, getfiletypesCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +napi_value GetFileTypesPromise(napi_env env, DSHelperGetFileTypesCB *getfiletypesCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (getfiletypesCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + getfiletypesCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetFileTypesExecuteCB, + GetFileTypesPromiseCompleteCB, + (void *)getfiletypesCB, + &getfiletypesCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, getfiletypesCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +void GetFileTypesExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_GetFileTypes, worker pool thread execute."); + DSHelperGetFileTypesCB *getfiletypesCB = static_cast(data); + if (getfiletypesCB->dataShareHelper != nullptr) { + getfiletypesCB->execResult = INVALID_PARAMETER; + if (!getfiletypesCB->uri.empty()) { + OHOS::Uri uri(getfiletypesCB->uri); + HILOG_INFO("NAPI_GetFileTypes, uri:%{public}s", uri.ToString().c_str()); + HILOG_INFO("NAPI_GetFileTypes, mimeTypeFilter:%{public}s", getfiletypesCB->mimeTypeFilter.c_str()); + getfiletypesCB->result = getfiletypesCB->dataShareHelper->GetFileTypes( + uri, + getfiletypesCB->mimeTypeFilter); + getfiletypesCB->execResult = NO_ERROR; + } else { + HILOG_INFO("NAPI_GetFileTypes, dataShareHelper uri is empty."); + } + } else { + HILOG_INFO("NAPI_GetFileTypes, dataShareHelper == nullptr."); + } + HILOG_INFO("NAPI_GetFileTypes, worker pool thread execute end."); +} + +void GetFileTypesAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetFileTypes, main event thread complete."); + DSHelperGetFileTypesCB *getfiletypesCB = static_cast(data); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, getfiletypesCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, getfiletypesCB->execResult); + result[PARAM1] = WrapGetFileTypesCB(env, *getfiletypesCB); + + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (getfiletypesCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, getfiletypesCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, getfiletypesCB->cbBase.asyncWork)); + delete getfiletypesCB; + getfiletypesCB = nullptr; + HILOG_INFO("NAPI_GetFileTypes, main event thread complete end."); +} + +napi_value WrapGetFileTypesCB(napi_env env, const DSHelperGetFileTypesCB &getfiletypesCB) +{ + HILOG_INFO("WrapGetFileTypesCB, called."); + HILOG_INFO("NAPI_GetFileTypes, result.size:%{public}zu", getfiletypesCB.result.size()); + for (size_t i = 0; i < getfiletypesCB.result.size(); i++) { + HILOG_INFO("NAPI_GetFileTypes, result[%{public}zu]:%{public}s", i, getfiletypesCB.result.at(i).c_str()); + } + napi_value proValue = nullptr; + + napi_value jsArrayresult = nullptr; + NAPI_CALL(env, napi_create_array(env, &jsArrayresult)); + for (size_t i = 0; i < getfiletypesCB.result.size(); i++) { + proValue = nullptr; + NAPI_CALL(env, napi_create_string_utf8(env, getfiletypesCB.result.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_set_element(env, jsArrayresult, i, proValue)); + } + HILOG_INFO("WrapGetFileTypesCB, end."); + return jsArrayresult; +} + +void GetFileTypesPromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_GetFileTypes, main event thread complete."); + DSHelperGetFileTypesCB *getfiletypesCB = static_cast(data); + napi_value result = nullptr; + + result = WrapGetFileTypesCB(env, *getfiletypesCB); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, getfiletypesCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, getfiletypesCB->cbBase.asyncWork)); + delete getfiletypesCB; + getfiletypesCB = nullptr; + HILOG_INFO("NAPI_GetFileTypes, main event thread complete end."); +} + +napi_value NAPI_NormalizeUri(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DSHelperNormalizeUriCB *normalizeuriCB = new (std::nothrow) DSHelperNormalizeUriCB; + if (normalizeuriCB == nullptr) { + HILOG_ERROR("%{public}s, normalizeuriCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + normalizeuriCB->cbBase.cbInfo.env = env; + normalizeuriCB->cbBase.asyncWork = nullptr; + normalizeuriCB->cbBase.deferred = nullptr; + normalizeuriCB->cbBase.ability = nullptr; + + napi_value ret = NormalizeUriWrap(env, info, normalizeuriCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (normalizeuriCB != nullptr) { + delete normalizeuriCB; + normalizeuriCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value NormalizeUriWrap(napi_env env, napi_callback_info info, DSHelperNormalizeUriCB *normalizeuriCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_TWO; + const size_t argcPromise = ARGS_ONE; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + normalizeuriCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, normalizeuriCB->uri.c_str()); + } + + DataShareHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataShareHelper objectInfo = %{public}p", __func__, objectInfo); + normalizeuriCB->dataShareHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = NormalizeUriAsync(env, args, ARGS_ONE, normalizeuriCB); + } else { + ret = NormalizeUriPromise(env, normalizeuriCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} +napi_value NormalizeUriAsync( + napi_env env, napi_value *args, const size_t argCallback, DSHelperNormalizeUriCB *normalizeuriCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || normalizeuriCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &normalizeuriCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + NormalizeUriExecuteCB, + NormalizeUriAsyncCompleteCB, + (void *)normalizeuriCB, + &normalizeuriCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, normalizeuriCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +napi_value NormalizeUriPromise(napi_env env, DSHelperNormalizeUriCB *normalizeuriCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (normalizeuriCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + normalizeuriCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + NormalizeUriExecuteCB, + NormalizeUriPromiseCompleteCB, + (void *)normalizeuriCB, + &normalizeuriCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, normalizeuriCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +void NormalizeUriExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_NormalizeUri, worker pool thread execute."); + DSHelperNormalizeUriCB *normalizeuriCB = static_cast(data); + Uri uriValue(normalizeuriCB->uri); + if (normalizeuriCB->dataShareHelper != nullptr) { + normalizeuriCB->execResult = INVALID_PARAMETER; + if (!normalizeuriCB->uri.empty()) { + OHOS::Uri uri(normalizeuriCB->uri); + uriValue = normalizeuriCB->dataShareHelper->NormalizeUri(uri); + normalizeuriCB->result = uriValue.ToString(); + normalizeuriCB->execResult = NO_ERROR; + } + } else { + HILOG_INFO("NAPI_NormalizeUri, dataShareHelper == nullptr"); + } + HILOG_INFO("NAPI_NormalizeUri, worker pool thread execute end."); +} + +void NormalizeUriAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_NormalizeUri, main event thread complete."); + DSHelperNormalizeUriCB *normalizeuriCB = static_cast(data); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, normalizeuriCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, normalizeuriCB->execResult); + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, normalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1])); + + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (normalizeuriCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, normalizeuriCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, normalizeuriCB->cbBase.asyncWork)); + delete normalizeuriCB; + normalizeuriCB = nullptr; + HILOG_INFO("NAPI_NormalizeUri, main event thread complete end."); +} + +void NormalizeUriPromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_NormalizeUri, main event thread complete."); + DSHelperNormalizeUriCB *normalizeuriCB = static_cast(data); + napi_value result = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, normalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result)); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, normalizeuriCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, normalizeuriCB->cbBase.asyncWork)); + delete normalizeuriCB; + normalizeuriCB = nullptr; + HILOG_INFO("NAPI_NormalizeUri, main event thread complete end."); +} + +napi_value NAPI_DenormalizeUri(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DSHelperDenormalizeUriCB *denormalizeuriCB = new (std::nothrow) DSHelperDenormalizeUriCB; + if (denormalizeuriCB == nullptr) { + HILOG_ERROR("%{public}s, denormalizeuriCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + denormalizeuriCB->cbBase.cbInfo.env = env; + denormalizeuriCB->cbBase.asyncWork = nullptr; + denormalizeuriCB->cbBase.deferred = nullptr; + denormalizeuriCB->cbBase.ability = nullptr; + + napi_value ret = DenormalizeUriWrap(env, info, denormalizeuriCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (denormalizeuriCB != nullptr) { + delete denormalizeuriCB; + denormalizeuriCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value DenormalizeUriWrap(napi_env env, napi_callback_info info, DSHelperDenormalizeUriCB *denormalizeuriCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_TWO; + const size_t argcPromise = ARGS_ONE; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + denormalizeuriCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, denormalizeuriCB->uri.c_str()); + } + + DataShareHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataShareHelper objectInfo = %{public}p", __func__, objectInfo); + denormalizeuriCB->dataShareHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = DenormalizeUriAsync(env, args, ARGS_ONE, denormalizeuriCB); + } else { + ret = DenormalizeUriPromise(env, denormalizeuriCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} +napi_value DenormalizeUriAsync( + napi_env env, napi_value *args, const size_t argCallback, DSHelperDenormalizeUriCB *denormalizeuriCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || denormalizeuriCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &denormalizeuriCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + DenormalizeUriExecuteCB, + DenormalizeUriAsyncCompleteCB, + (void *)denormalizeuriCB, + &denormalizeuriCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, denormalizeuriCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +napi_value DenormalizeUriPromise(napi_env env, DSHelperDenormalizeUriCB *denormalizeuriCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (denormalizeuriCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + denormalizeuriCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + DenormalizeUriExecuteCB, + DenormalizeUriPromiseCompleteCB, + (void *)denormalizeuriCB, + &denormalizeuriCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, denormalizeuriCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +void DenormalizeUriExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_DenormalizeUri, worker pool thread execute."); + DSHelperDenormalizeUriCB *denormalizeuriCB = static_cast(data); + Uri uriValue(denormalizeuriCB->uri); + if (denormalizeuriCB->dataShareHelper != nullptr) { + denormalizeuriCB->execResult = INVALID_PARAMETER; + if (!denormalizeuriCB->uri.empty()) { + OHOS::Uri uri(denormalizeuriCB->uri); + uriValue = denormalizeuriCB->dataShareHelper->DenormalizeUri(uri); + denormalizeuriCB->result = uriValue.ToString(); + denormalizeuriCB->execResult = NO_ERROR; + } else { + HILOG_ERROR("NAPI_DenormalizeUri, dataShareHelper uri is empty"); + } + } else { + HILOG_ERROR("NAPI_DenormalizeUri, dataShareHelper == nullptr"); + } + HILOG_INFO("NAPI_DenormalizeUri, worker pool thread execute end."); +} + +void DenormalizeUriAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_DenormalizeUri, main event thread complete."); + DSHelperDenormalizeUriCB *denormalizeuriCB = static_cast(data); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, denormalizeuriCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, denormalizeuriCB->execResult); + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, denormalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1])); + + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (denormalizeuriCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, denormalizeuriCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, denormalizeuriCB->cbBase.asyncWork)); + delete denormalizeuriCB; + denormalizeuriCB = nullptr; + HILOG_INFO("NAPI_DenormalizeUri, main event thread complete end."); +} + +void DenormalizeUriPromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_DenormalizeUri, main event thread complete."); + DSHelperDenormalizeUriCB *denormalizeuriCB = static_cast(data); + napi_value result = nullptr; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, denormalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result)); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, denormalizeuriCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, denormalizeuriCB->cbBase.asyncWork)); + delete denormalizeuriCB; + denormalizeuriCB = nullptr; + HILOG_INFO("NAPI_DenormalizeUri, main event thread complete end."); +} + +void UnwrapDataAbilityPredicates(NativeRdb::DataAbilityPredicates &predicates, napi_env env, napi_value value) +{ + auto tempPredicates = DataAbilityJsKit::DataAbilityPredicatesProxy::GetNativePredicates(env, value); + if (tempPredicates == nullptr) { + HILOG_ERROR("%{public}s, GetNativePredicates retval Marshalling failed.", __func__); + return; + } + predicates = *tempPredicates; +} + +/** + * @brief DataShareHelper NAPI method : insert. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_Delete(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DSHelperDeleteCB *deleteCB = new (std::nothrow) DSHelperDeleteCB; + if (deleteCB == nullptr) { + HILOG_ERROR("%{public}s, deleteCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + deleteCB->cbBase.cbInfo.env = env; + deleteCB->cbBase.asyncWork = nullptr; + deleteCB->cbBase.deferred = nullptr; + deleteCB->cbBase.ability = nullptr; + + napi_value ret = DeleteWrap(env, info, deleteCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (deleteCB != nullptr) { + delete deleteCB; + deleteCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +/** + * @brief Insert processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param insertCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value DeleteWrap(napi_env env, napi_callback_info info, DSHelperDeleteCB *deleteCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_THREE; + const size_t argcPromise = ARGS_TWO; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + deleteCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, deleteCB->uri.c_str()); + } + + UnwrapDataAbilityPredicates(deleteCB->predicates, env, args[PARAM1]); + DataShareHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataShareHelper objectInfo = %{public}p", __func__, objectInfo); + deleteCB->dataShareHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = DeleteAsync(env, args, ARGS_TWO, deleteCB); + } else { + ret = DeletePromise(env, deleteCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value DeleteAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperDeleteCB *deleteCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || deleteCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &deleteCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + DeleteExecuteCB, + DeleteAsyncCompleteCB, + (void *)deleteCB, + &deleteCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, deleteCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +napi_value DeletePromise(napi_env env, DSHelperDeleteCB *deleteCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (deleteCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + deleteCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + DeleteExecuteCB, + DeletePromiseCompleteCB, + (void *)deleteCB, + &deleteCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, deleteCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +void DeleteExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_Delete, worker pool thread execute."); + DSHelperDeleteCB *deleteCB = static_cast(data); + if (deleteCB->dataShareHelper != nullptr) { + deleteCB->execResult = INVALID_PARAMETER; + if (!deleteCB->uri.empty()) { + OHOS::Uri uri(deleteCB->uri); + deleteCB->result = deleteCB->dataShareHelper->Delete(uri, deleteCB->predicates); + deleteCB->execResult = NO_ERROR; + } else { + HILOG_ERROR("NAPI_Delete, dataShareHelper uri is empty"); + } + } else { + HILOG_ERROR("NAPI_Delete, dataShareHelper == nullptr"); + } + HILOG_INFO("NAPI_Delete, worker pool thread execute end."); +} + +void DeleteAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_Delete, main event thread complete."); + DSHelperDeleteCB *DeleteCB = static_cast(data); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, DeleteCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, DeleteCB->execResult); + napi_create_int32(env, DeleteCB->result, &result[PARAM1]); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (DeleteCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, DeleteCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, DeleteCB->cbBase.asyncWork)); + delete DeleteCB; + DeleteCB = nullptr; + HILOG_INFO("NAPI_Delete, main event thread complete end."); +} + +void DeletePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_Delete, main event thread complete."); + DSHelperDeleteCB *DeleteCB = static_cast(data); + napi_value result = nullptr; + napi_create_int32(env, DeleteCB->result, &result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, DeleteCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, DeleteCB->cbBase.asyncWork)); + delete DeleteCB; + DeleteCB = nullptr; + HILOG_INFO("NAPI_Delete, main event thread complete end."); +} + +/** + * @brief DataShareHelper NAPI method : insert. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_Update(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DSHelperUpdateCB *updateCB = new (std::nothrow) DSHelperUpdateCB; + if (updateCB == nullptr) { + HILOG_ERROR("%{public}s, updateCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + updateCB->cbBase.cbInfo.env = env; + updateCB->cbBase.asyncWork = nullptr; + updateCB->cbBase.deferred = nullptr; + updateCB->cbBase.ability = nullptr; + + napi_value ret = UpdateWrap(env, info, updateCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (updateCB != nullptr) { + delete updateCB; + updateCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +/** + * @brief Insert processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param insertCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value UpdateWrap(napi_env env, napi_callback_info info, DSHelperUpdateCB *updateCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_FOUR; + const size_t argcPromise = ARGS_THREE; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + updateCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, updateCB->uri.c_str()); + } + + updateCB->valueBucket.Clear(); + AnalysisValuesBucket(updateCB->valueBucket, env, args[PARAM1]); + UnwrapDataAbilityPredicates(updateCB->predicates, env, args[PARAM2]); + DataShareHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataShareHelper objectInfo = %{public}p", __func__, objectInfo); + updateCB->dataShareHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = UpdateAsync(env, args, ARGS_THREE, updateCB); + } else { + ret = UpdatePromise(env, updateCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value UpdateAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperUpdateCB *updateCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || updateCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &updateCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + UpdateExecuteCB, + UpdateAsyncCompleteCB, + (void *)updateCB, + &updateCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, updateCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +napi_value UpdatePromise(napi_env env, DSHelperUpdateCB *updateCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (updateCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + updateCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + UpdateExecuteCB, + UpdatePromiseCompleteCB, + (void *)updateCB, + &updateCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, updateCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +void UpdateExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_Update, worker pool thread execute."); + DSHelperUpdateCB *updateCB = static_cast(data); + if (updateCB->dataShareHelper != nullptr) { + updateCB->execResult = INVALID_PARAMETER; + if (!updateCB->uri.empty()) { + OHOS::Uri uri(updateCB->uri); + updateCB->result = updateCB->dataShareHelper->Update(uri, updateCB->valueBucket, updateCB->predicates); + updateCB->execResult = NO_ERROR; + } else { + HILOG_ERROR("NAPI_Update, dataShareHelper uri is empty"); + } + } else { + HILOG_ERROR("NAPI_Update, dataShareHelper == nullptr"); + } + HILOG_INFO("NAPI_Update, worker pool thread execute end."); +} + +void UpdateAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_Update, main event thread complete."); + DSHelperUpdateCB *updateCB = static_cast(data); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, updateCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, updateCB->execResult); + napi_create_int32(env, updateCB->result, &result[PARAM1]); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (updateCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, updateCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, updateCB->cbBase.asyncWork)); + delete updateCB; + updateCB = nullptr; + HILOG_INFO("NAPI_Update, main event thread complete end."); +} + +void UpdatePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_Update, main event thread complete."); + DSHelperUpdateCB *updateCB = static_cast(data); + napi_value result = nullptr; + napi_create_int32(env, updateCB->result, &result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, updateCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, updateCB->cbBase.asyncWork)); + delete updateCB; + updateCB = nullptr; + HILOG_INFO("NAPI_Update, main event thread complete end."); +} + +/** + * @brief DataShareHelper NAPI method : insert. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_OpenFile(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DSHelperOpenFileCB *openFileCB = new (std::nothrow) DSHelperOpenFileCB; + if (openFileCB == nullptr) { + HILOG_ERROR("%{public}s, openFileCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + openFileCB->cbBase.cbInfo.env = env; + openFileCB->cbBase.asyncWork = nullptr; + openFileCB->cbBase.deferred = nullptr; + openFileCB->cbBase.ability = nullptr; + + napi_value ret = OpenFileWrap(env, info, openFileCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (openFileCB != nullptr) { + delete openFileCB; + openFileCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +/** + * @brief Insert processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param insertCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value OpenFileWrap(napi_env env, napi_callback_info info, DSHelperOpenFileCB *openFileCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_THREE; + const size_t argcPromise = ARGS_TWO; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + openFileCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, openFileCB->uri.c_str()); + } + + NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); + if (valuetype == napi_string) { + openFileCB->mode = NapiValueToStringUtf8(env, args[PARAM1]); + HILOG_INFO("%{public}s,mode=%{public}s", __func__, openFileCB->mode.c_str()); + } + + DataShareHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataShareHelper objectInfo = %{public}p", __func__, objectInfo); + openFileCB->dataShareHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = OpenFileAsync(env, args, ARGS_TWO, openFileCB); + } else { + ret = OpenFilePromise(env, openFileCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value OpenFileAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperOpenFileCB *openFileCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || openFileCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &openFileCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + OpenFileExecuteCB, + OpenFileAsyncCompleteCB, + (void *)openFileCB, + &openFileCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, openFileCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +napi_value OpenFilePromise(napi_env env, DSHelperOpenFileCB *openFileCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (openFileCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + openFileCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + OpenFileExecuteCB, + OpenFilePromiseCompleteCB, + (void *)openFileCB, + &openFileCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, openFileCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +void OpenFileExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_OpenFile, worker pool thread execute."); + DSHelperOpenFileCB *OpenFileCB = static_cast(data); + if (OpenFileCB->dataShareHelper != nullptr) { + OpenFileCB->execResult = INVALID_PARAMETER; + if (!OpenFileCB->uri.empty()) { + OHOS::Uri uri(OpenFileCB->uri); + OpenFileCB->result = OpenFileCB->dataShareHelper->OpenFile(uri, OpenFileCB->mode); + OpenFileCB->execResult = NO_ERROR; + } else { + HILOG_ERROR("NAPI_OpenFile, dataShareHelper uri is empty"); + } + } else { + HILOG_ERROR("NAPI_OpenFile, dataShareHelper == nullptr"); + } + HILOG_INFO("NAPI_OpenFile, worker pool thread execute end."); +} + +void OpenFileAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_OpenFile, main event thread complete."); + DSHelperOpenFileCB *OpenFileCB = static_cast(data); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, OpenFileCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, OpenFileCB->execResult); + napi_create_int32(env, OpenFileCB->result, &result[PARAM1]); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (OpenFileCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, OpenFileCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, OpenFileCB->cbBase.asyncWork)); + delete OpenFileCB; + OpenFileCB = nullptr; + HILOG_INFO("NAPI_OpenFile, main event thread complete end."); +} + +void OpenFilePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_OpenFileCB, main event thread complete."); + DSHelperOpenFileCB *OpenFileCB = static_cast(data); + napi_value result = nullptr; + napi_create_int32(env, OpenFileCB->result, &result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, OpenFileCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, OpenFileCB->cbBase.asyncWork)); + delete OpenFileCB; + OpenFileCB = nullptr; + HILOG_INFO("NAPI_OpenFileCB, main event thread complete end."); +} + +/** + * @brief DataShareHelper NAPI method : insert. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_BatchInsert(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DSHelperBatchInsertCB *BatchInsertCB = new (std::nothrow) DSHelperBatchInsertCB; + if (BatchInsertCB == nullptr) { + HILOG_ERROR("%{public}s, BatchInsertCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + BatchInsertCB->cbBase.cbInfo.env = env; + BatchInsertCB->cbBase.asyncWork = nullptr; + BatchInsertCB->cbBase.deferred = nullptr; + BatchInsertCB->cbBase.ability = nullptr; + + napi_value ret = BatchInsertWrap(env, info, BatchInsertCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (BatchInsertCB != nullptr) { + delete BatchInsertCB; + BatchInsertCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +std::vector NapiValueObject(napi_env env, napi_value param) +{ + HILOG_INFO("%{public}s,called", __func__); + std::vector result; + UnwrapArrayObjectFromJS(env, param, result); + return result; +} + +bool UnwrapArrayObjectFromJS(napi_env env, napi_value param, std::vector &value) +{ + HILOG_INFO("%{public}s,called", __func__); + uint32_t arraySize = 0; + napi_value jsValue = nullptr; + std::string strValue = ""; + + if (!IsArrayForNapiValue(env, param, arraySize)) { + HILOG_INFO("%{public}s, IsArrayForNapiValue is false", __func__); + return false; + } + + value.clear(); + for (uint32_t i = 0; i < arraySize; i++) { + jsValue = nullptr; + if (napi_get_element(env, param, i, &jsValue) != napi_ok) { + HILOG_INFO("%{public}s, napi_get_element is false", __func__); + return false; + } + + NativeRdb::ValuesBucket valueBucket; + valueBucket.Clear(); + AnalysisValuesBucket(valueBucket, env, jsValue); + + value.push_back(valueBucket); + } + HILOG_INFO("%{public}s,end", __func__); + return true; +} + +/** + * @brief Insert processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param insertCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value BatchInsertWrap(napi_env env, napi_callback_info info, DSHelperBatchInsertCB *batchInsertCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_THREE; + const size_t argcPromise = ARGS_TWO; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + batchInsertCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, batchInsertCB->uri.c_str()); + } + + batchInsertCB->values = NapiValueObject(env, args[PARAM1]); + + DataShareHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataShareHelper objectInfo = %{public}p", __func__, objectInfo); + batchInsertCB->dataShareHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = BatchInsertAsync(env, args, ARGS_TWO, batchInsertCB); + } else { + ret = BatchInsertPromise(env, batchInsertCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value BatchInsertAsync( + napi_env env, napi_value *args, const size_t argCallback, DSHelperBatchInsertCB *batchInsertCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || batchInsertCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &batchInsertCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + BatchInsertExecuteCB, + BatchInsertAsyncCompleteCB, + (void *)batchInsertCB, + &batchInsertCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, batchInsertCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +napi_value BatchInsertPromise(napi_env env, DSHelperBatchInsertCB *batchInsertCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (batchInsertCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + batchInsertCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + BatchInsertExecuteCB, + BatchInsertPromiseCompleteCB, + (void *)batchInsertCB, + &batchInsertCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, batchInsertCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +void BatchInsertExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_BatchInsert, worker pool thread execute."); + DSHelperBatchInsertCB *batchInsertCB = static_cast(data); + if (batchInsertCB->dataShareHelper != nullptr) { + batchInsertCB->execResult = INVALID_PARAMETER; + if (!batchInsertCB->uri.empty()) { + OHOS::Uri uri(batchInsertCB->uri); + batchInsertCB->result = batchInsertCB->dataShareHelper->BatchInsert(uri, batchInsertCB->values); + batchInsertCB->execResult = NO_ERROR; + } else { + HILOG_ERROR("NAPI_BatchInsert, dataShareHelper uri is empyt"); + } + } else { + HILOG_ERROR("NAPI_BatchInsert, dataShareHelper == nullptr"); + } + HILOG_INFO("NAPI_BatchInsert, worker pool thread execute end."); +} + +void BatchInsertAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_BatchInsert, main event thread complete."); + DSHelperBatchInsertCB *BatchInsertCB = static_cast(data); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, BatchInsertCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, BatchInsertCB->execResult); + napi_create_int32(env, BatchInsertCB->result, &result[PARAM1]); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (BatchInsertCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, BatchInsertCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, BatchInsertCB->cbBase.asyncWork)); + delete BatchInsertCB; + BatchInsertCB = nullptr; + HILOG_INFO("NAPI_BatchInsert, main event thread complete end."); +} + +void BatchInsertPromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_BatchInsertCB, main event thread complete."); + DSHelperBatchInsertCB *BatchInsertCB = static_cast(data); + napi_value result = nullptr; + napi_create_int32(env, BatchInsertCB->result, &result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, BatchInsertCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, BatchInsertCB->cbBase.asyncWork)); + delete BatchInsertCB; + BatchInsertCB = nullptr; + HILOG_INFO("NAPI_BatchInsertCB, main event thread complete end."); +} + +/** + * @brief DataShareHelper NAPI method : insert. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_Query(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DSHelperQueryCB *QueryCB = new (std::nothrow) DSHelperQueryCB; + if (QueryCB == nullptr) { + HILOG_ERROR("%{public}s, QueryCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + QueryCB->cbBase.cbInfo.env = env; + QueryCB->cbBase.asyncWork = nullptr; + QueryCB->cbBase.deferred = nullptr; + QueryCB->cbBase.ability = nullptr; + + napi_value ret = QueryWrap(env, info, QueryCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (QueryCB != nullptr) { + delete QueryCB; + QueryCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +/** + * @brief Insert processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param insertCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value QueryWrap(napi_env env, napi_callback_info info, DSHelperQueryCB *queryCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_FOUR; + const size_t argcPromise = ARGS_THREE; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + queryCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, queryCB->uri.c_str()); + } + + std::vector result; + bool arrayStringbool = false; + arrayStringbool = NapiValueToArrayStringUtf8(env, args[PARAM1], result); + if (!arrayStringbool) { + HILOG_ERROR("%{public}s, The return value of arraystringbool is false", __func__); + } + queryCB->columns = result; + for (size_t i = 0; i < queryCB->columns.size(); i++) { + HILOG_INFO("%{public}s,columns=%{public}s", __func__, queryCB->columns.at(i).c_str()); + } + + UnwrapDataAbilityPredicates(queryCB->predicates, env, args[PARAM2]); + DataShareHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataShareHelper objectInfo = %{public}p", __func__, objectInfo); + queryCB->dataShareHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = QueryAsync(env, args, ARGS_THREE, queryCB); + } else { + ret = QueryPromise(env, queryCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value QueryAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperQueryCB *queryCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || queryCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &queryCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + QueryExecuteCB, + QueryAsyncCompleteCB, + (void *)queryCB, + &queryCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, queryCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +napi_value QueryPromise(napi_env env, DSHelperQueryCB *queryCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (queryCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + queryCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + QueryExecuteCB, + QueryPromiseCompleteCB, + (void *)queryCB, + &queryCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, queryCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +void QueryPromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_DSHelperQueryCB, main event thread complete."); + DSHelperQueryCB *QueryCB = static_cast(data); + napi_value result = nullptr; + result = WrapResultSet(env, QueryCB->result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, QueryCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, QueryCB->cbBase.asyncWork)); + delete QueryCB; + QueryCB = nullptr; + HILOG_INFO("NAPI_DSHelperQueryCB, main event thread complete end."); +} + +void QueryExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_Query, worker pool thread execute."); + DSHelperQueryCB *queryCB = static_cast(data); + if (queryCB->dataShareHelper != nullptr) { + queryCB->execResult = INVALID_PARAMETER; + if (!queryCB->uri.empty()) { + OHOS::Uri uri(queryCB->uri); + auto resultset = queryCB->dataShareHelper->Query(uri, queryCB->columns, queryCB->predicates); + if (resultset != nullptr) { + queryCB->result = resultset; + queryCB->execResult = NO_ERROR; + } else { + HILOG_INFO("NAPI_Query, resultset == nullptr."); + } + } else { + HILOG_ERROR("NAPI_Query, dataShareHelper uri is empty"); + } + } else { + HILOG_ERROR("NAPI_Query, dataShareHelper == nullptr"); + } + HILOG_INFO("NAPI_Query, worker pool thread execute end."); +} + +void QueryAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_Query, main event thread complete."); + DSHelperQueryCB *queryCB = static_cast(data); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, queryCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, queryCB->execResult); + result[PARAM1] = WrapResultSet(env, queryCB->result); + + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (queryCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, queryCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, queryCB->cbBase.asyncWork)); + delete queryCB; + queryCB = nullptr; + HILOG_INFO("NAPI_Query, main event thread complete end."); +} + +napi_value WrapResultSet(napi_env env, const std::shared_ptr &resultSet) +{ + HILOG_INFO("%{public}s,called", __func__); + if (resultSet == nullptr) { + HILOG_ERROR("%{public}s, input parameter resultSet is nullptr", __func__); + return WrapVoidToJS(env); + } + + return RdbJsKit::ResultSetProxy::NewInstance(env, resultSet); +} + +napi_value NAPI_Release(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + DSHelperReleaseCB *releaseCB = new (std::nothrow) DSHelperReleaseCB; + if (releaseCB == nullptr) { + HILOG_ERROR("%{public}s, releaseCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + releaseCB->cbBase.cbInfo.env = env; + releaseCB->cbBase.asyncWork = nullptr; + releaseCB->cbBase.deferred = nullptr; + + napi_value ret = ReleaseWrap(env, info, releaseCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (releaseCB != nullptr) { + delete releaseCB; + releaseCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value ReleaseWrap(napi_env env, napi_callback_info info, DSHelperReleaseCB *releaseCB) +{ + HILOG_INFO("%{public}s,called", __func__); + size_t argcAsync = ARGS_ONE; + const size_t argcPromise = ARGS_ZERO; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = nullptr; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + DataShareHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("DataShareHelper ReleaseWrap objectInfo = %{public}p", objectInfo); + releaseCB->dataShareHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = ReleaseAsync(env, args, PARAM0, releaseCB); + } else { + ret = ReleasePromise(env, releaseCB); + } + HILOG_INFO("%{public}s,end", __func__); + return ret; +} + +napi_value ReleaseAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperReleaseCB *releaseCB) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || releaseCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &releaseCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + ReleaseExecuteCB, + ReleaseAsyncCompleteCB, + (void *)releaseCB, + &releaseCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, releaseCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + HILOG_INFO("%{public}s, asyncCallback end.", __func__); + return result; +} + +napi_value ReleasePromise(napi_env env, DSHelperReleaseCB *releaseCB) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (releaseCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + releaseCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + ReleaseExecuteCB, + ReleasePromiseCompleteCB, + (void *)releaseCB, + &releaseCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, releaseCB->cbBase.asyncWork)); + HILOG_INFO("%{public}s, promise end.", __func__); + return promise; +} + +void ReleaseExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_Release, worker pool thread execute."); + DSHelperReleaseCB *releaseCB = static_cast(data); + if (releaseCB->dataShareHelper != nullptr) { + releaseCB->result = releaseCB->dataShareHelper->Release(); + } else { + HILOG_ERROR("NAPI_Release, dataShareHelper == nullptr"); + } + HILOG_INFO("NAPI_Release, worker pool thread execute end."); +} + +void ReleaseAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_Release, main event thread complete."); + DSHelperReleaseCB *releaseCB = static_cast(data); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, releaseCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); + napi_get_boolean(env, releaseCB->result, &result[PARAM1]); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (releaseCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, releaseCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, releaseCB->cbBase.asyncWork)); + delete releaseCB; + releaseCB = nullptr; + HILOG_INFO("NAPI_Release, main event thread complete end."); +} + +void ReleasePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("NAPI_Release, main event thread complete."); + DSHelperReleaseCB *releaseCB = static_cast(data); + napi_value result = nullptr; + napi_get_boolean(env, releaseCB->result, &result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, releaseCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, releaseCB->cbBase.asyncWork)); + delete releaseCB; + releaseCB = nullptr; + HILOG_INFO("NAPI_Release, main event thread complete end."); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/kits/napi/aafwk/dataShare/napi_datashare_helper.h b/interfaces/kits/napi/aafwk/dataShare/napi_datashare_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..4cbaeafaf183dd74c3ad13fab596677fe860a8b4 --- /dev/null +++ b/interfaces/kits/napi/aafwk/dataShare/napi_datashare_helper.h @@ -0,0 +1,426 @@ +/* + * 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_NAPI_DATASHARE_HELPER_H +#define OHOS_APPEXECFWK_NAPI_DATASHARE_HELPER_H +#include "data_ability_observer_stub.h" +#include "data_share_common.h" + +namespace OHOS { +namespace AppExecFwk { +class NAPIDataShareObserver : public AAFwk::DataAbilityObserverStub { +public: + void OnChange() override; + void SetEnv(const napi_env &env); + void SetCallbackRef(const napi_ref &ref); + void ReleaseJSCallback(); + + void SetAssociatedObject(DSHelperOnOffCB* object); + const DSHelperOnOffCB* GetAssociatedObject(void); + + void ChangeWorkPre(); + void ChangeWorkRun(); + void ChangeWorkInt(); + void ChangeWorkPreDone(); + void ChangeWorkRunDone(); + int GetWorkPre(); + int GetWorkRun(); + int GetWorkInt(); + +private: + napi_env env_ = nullptr; + napi_ref ref_ = nullptr; + DSHelperOnOffCB* onCB_ = nullptr; + int workPre_ = 0; + int workRun_ = 0; + int intrust_ = 0; + std::mutex mutex_; +}; + +/** + * @brief DataShareHelper NAPI module registration. + * + * @param env The environment that the Node-API call is invoked under. + * @param exports An empty object via the exports parameter as a convenience. + * + * @return The return value from Init is treated as the exports object for the module. + */ +napi_value DataShareHelperInit(napi_env env, napi_value exports); +napi_value DataShareHelperConstructor(napi_env env, napi_callback_info info); + +/** + * @brief DataShareHelper NAPI method : insert. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_Insert(napi_env env, napi_callback_info info); + +/** + * @brief Insert processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param insertCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value InsertWrap(napi_env env, napi_callback_info info, DSHelperInsertCB *insertCB); + +/** + * @brief Insert Async. + * + * @param env The environment that the Node-API call is invoked under. + * @param args Indicates the arguments passed into the callback. + * @param argcPromise Asynchronous data processing. + * @param insertCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value InsertAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperInsertCB *insertCB); + +/** + * @brief Insert Promise. + * + * @param env The environment that the Node-API call is invoked under. + * @param insertCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value InsertPromise(napi_env env, DSHelperInsertCB *insertCB); + +/** + * @brief Insert asynchronous processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void InsertExecuteCB(napi_env env, void *data); + +/** + * @brief The callback at the end of the asynchronous callback. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void InsertAsyncCompleteCB(napi_env env, napi_status status, void *data); + +/** + * @brief The callback at the end of the Promise callback. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void InsertPromiseCompleteCB(napi_env env, napi_status status, void *data); + +/** + * @brief DataShareHelper NAPI method : notifyChange. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_NotifyChange(napi_env env, napi_callback_info info); + +/** + * @brief NotifyChange processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param notifyChangeCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value NotifyChangeWrap(napi_env env, napi_callback_info info, DSHelperNotifyChangeCB *notifyChangeCB); + +/** + * @brief NotifyChange Async. + * + * @param env The environment that the Node-API call is invoked under. + * @param args Indicates the arguments passed into the callback. + * @param argcPromise Asynchronous data processing. + * @param notifyChangeCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value NotifyChangeAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DSHelperNotifyChangeCB *notifyChangeCB); + +/** + * @brief NotifyChange Promise. + * + * @param env The environment that the Node-API call is invoked under. + * @param notifyChangeCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value NotifyChangePromise(napi_env env, DSHelperNotifyChangeCB *notifyChangeCB); + +/** + * @brief NotifyChange asynchronous processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void NotifyChangeExecuteCB(napi_env env, void *data); + +/** + * @brief The callback at the end of the asynchronous callback. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void NotifyChangeAsyncCompleteCB(napi_env env, napi_status status, void *data); + +/** + * @brief The callback at the end of the Promise callback. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void NotifyChangePromiseCompleteCB(napi_env env, napi_status status, void *data); + +/** + * @brief DataShareHelper NAPI method : on. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_Register(napi_env env, napi_callback_info info); + +/** + * @brief On processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param insertCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value RegisterWrap(napi_env env, napi_callback_info info, DSHelperOnOffCB *insertCB); + +/** + * @brief On Async. + * + * @param env The environment that the Node-API call is invoked under. + * @param args Indicates the arguments passed into the callback. + * @param argcPromise Asynchronous data processing. + * @param insertCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value RegisterAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DSHelperOnOffCB *insertCB); + +/** + * @brief On asynchronous processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void RegisterExecuteCB(napi_env env, void *data); +void RegisterCompleteCB(napi_env env, napi_status status, void *data); + +/** + * @brief DataShareHelper NAPI method : off. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_UnRegister(napi_env env, napi_callback_info info); + +/** + * @brief Off processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param insertCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value UnRegisterWrap(napi_env env, napi_callback_info info, DSHelperOnOffCB *insertCB); + +/** + * @brief Off Async. + * + * @param env The environment that the Node-API call is invoked under. + * @param args Indicates the arguments passed into the callback. + * @param argcPromise Asynchronous data processing. + * @param insertCB Process data asynchronously. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value UnRegisterAsync( + napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DSHelperOnOffCB *insertCB); + +/** + * @brief Off asynchronous processing function. + * + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. + */ +void UnRegisterExecuteCB(napi_env env, void *data); +void UnRegisterCompleteCB(napi_env env, napi_status status, void *data); +void FindRegisterObs(napi_env env, DSHelperOnOffCB *data); +/** + * @brief Parse the ValuesBucket parameters. + * + * @param param Indicates the want parameters saved the parse result. + * @param env The environment that the Node-API call is invoked under. + * @param args Indicates the arguments passed into the callback. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value UnwrapValuesBucket(std::string &value, napi_env env, napi_value args); + +static std::vector registerInstances_; +napi_value NAPI_Release(napi_env env, napi_callback_info info); + +napi_value ReleaseWrap(napi_env env, napi_callback_info info, DSHelperReleaseCB *releaseCB); + +napi_value ReleaseAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperReleaseCB *releaseCB); + +napi_value ReleasePromise(napi_env env, DSHelperReleaseCB *releaseCB); + +void ReleaseExecuteCB(napi_env env, void *data); + +void ReleaseAsyncCompleteCB(napi_env env, napi_status status, void *data); + +void ReleasePromiseCompleteCB(napi_env env, napi_status status, void *data); + +napi_value NAPI_GetType(napi_env env, napi_callback_info info); +napi_value NAPI_GetType(napi_env env, napi_callback_info info); +napi_value GetTypeWrap(napi_env env, napi_callback_info info, DSHelperGetTypeCB *gettypeCB); +napi_value GetTypeAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperGetTypeCB *gettypeCB); +napi_value GetTypePromise(napi_env env, DSHelperGetTypeCB *gettypeCB); +void GetTypeExecuteCB(napi_env env, void *data); +void GetTypeAsyncCompleteCB(napi_env env, napi_status status, void *data); +void GetTypePromiseCompleteCB(napi_env env, napi_status status, void *data); + +napi_value NAPI_GetFileTypes(napi_env env, napi_callback_info info); +napi_value NAPI_GetFileTypes(napi_env env, napi_callback_info info); +napi_value GetFileTypesWrap(napi_env env, napi_callback_info info, DSHelperGetFileTypesCB *getfiletypesCB); +napi_value GetFileTypesAsync( + napi_env env, napi_value *args, const size_t argCallback, DSHelperGetFileTypesCB *getfiletypesCB); +napi_value GetFileTypesPromise(napi_env env, DSHelperGetFileTypesCB *getfiletypesCB); +void GetFileTypesExecuteCB(napi_env env, void *data); +void GetFileTypesAsyncCompleteCB(napi_env env, napi_status status, void *data); +void GetFileTypesPromiseCompleteCB(napi_env env, napi_status status, void *data); +napi_value WrapGetFileTypesCB(napi_env env, const DSHelperGetFileTypesCB &getfiletypesCB); + +napi_value NAPI_NormalizeUri(napi_env env, napi_callback_info info); +napi_value NAPI_NormalizeUri(napi_env env, napi_callback_info info); +napi_value NormalizeUriWrap(napi_env env, napi_callback_info info, DSHelperNormalizeUriCB *normalizeuriCB); +napi_value NormalizeUriAsync( + napi_env env, napi_value *args, const size_t argCallback, DSHelperNormalizeUriCB *normalizeuriCB); +napi_value NormalizeUriPromise(napi_env env, DSHelperNormalizeUriCB *normalizeuriCB); +void NormalizeUriExecuteCB(napi_env env, void *data); +void NormalizeUriAsyncCompleteCB(napi_env env, napi_status status, void *data); +void NormalizeUriPromiseCompleteCB(napi_env env, napi_status status, void *data); + +napi_value NAPI_DenormalizeUri(napi_env env, napi_callback_info info); +napi_value NAPI_DenormalizeUri(napi_env env, napi_callback_info info); +napi_value DenormalizeUriWrap(napi_env env, napi_callback_info info, DSHelperDenormalizeUriCB *denormalizeuriCB); +napi_value DenormalizeUriAsync( + napi_env env, napi_value *args, const size_t argCallback, DSHelperDenormalizeUriCB *denormalizeuriCB); +napi_value DenormalizeUriPromise(napi_env env, DSHelperDenormalizeUriCB *denormalizeuriCB); +void DenormalizeUriExecuteCB(napi_env env, void *data); +void DenormalizeUriAsyncCompleteCB(napi_env env, napi_status status, void *data); +void DenormalizeUriPromiseCompleteCB(napi_env env, napi_status status, void *data); + +napi_value NAPI_Delete(napi_env env, napi_callback_info info); + +napi_value DeleteWrap(napi_env env, napi_callback_info info, DSHelperDeleteCB *deleteCB); +napi_value DeleteAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperDeleteCB *deleteCB); + +napi_value DeletePromise(napi_env env, DSHelperDeleteCB *deleteCB); + +void DeleteExecuteCB(napi_env env, void *data); + +void DeleteAsyncCompleteCB(napi_env env, napi_status status, void *data); + +void DeletePromiseCompleteCB(napi_env env, napi_status status, void *data); + +napi_value NAPI_Update(napi_env env, napi_callback_info info); + +napi_value UpdateWrap(napi_env env, napi_callback_info info, DSHelperUpdateCB *updateCB); +napi_value UpdateAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperUpdateCB *updateCB); + +napi_value UpdatePromise(napi_env env, DSHelperUpdateCB *updateCB); + +void UpdateExecuteCB(napi_env env, void *data); + +void UpdateAsyncCompleteCB(napi_env env, napi_status status, void *data); + +void UpdatePromiseCompleteCB(napi_env env, napi_status status, void *data); + +napi_value NAPI_OpenFile(napi_env env, napi_callback_info info); + +napi_value OpenFileWrap(napi_env env, napi_callback_info info, DSHelperOpenFileCB *openFileCB); +napi_value OpenFileAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperOpenFileCB *openFileCB); + +napi_value OpenFilePromise(napi_env env, DSHelperOpenFileCB *openFileCB); + +void OpenFileExecuteCB(napi_env env, void *data); + +void OpenFileAsyncCompleteCB(napi_env env, napi_status status, void *data); + +void OpenFilePromiseCompleteCB(napi_env env, napi_status status, void *data); + +napi_value NAPI_BatchInsert(napi_env env, napi_callback_info info); + +napi_value BatchInsertWrap(napi_env env, napi_callback_info info, DSHelperBatchInsertCB *batchInsertCB); +napi_value BatchInsertAsync( + napi_env env, napi_value *args, const size_t argCallback, DSHelperBatchInsertCB *batchInsertCB); + +napi_value BatchInsertPromise(napi_env env, DSHelperBatchInsertCB *batchInsertCB); + +void BatchInsertExecuteCB(napi_env env, void *data); + +void BatchInsertAsyncCompleteCB(napi_env env, napi_status status, void *data); + +void BatchInsertPromiseCompleteCB(napi_env env, napi_status status, void *data); + +std::vector NapiValueObject(napi_env env, napi_value param); + +bool UnwrapArrayObjectFromJS(napi_env env, napi_value param, std::vector &value); + +napi_value NAPI_Query(napi_env env, napi_callback_info info); + +napi_value QueryWrap(napi_env env, napi_callback_info info, DSHelperQueryCB *queryCB); + +napi_value QueryAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperQueryCB *queryCB); + +napi_value QueryPromise(napi_env env, DSHelperQueryCB *queryCB); + +void QueryExecuteCB(napi_env env, void *data); + +void QueryAsyncCompleteCB(napi_env env, napi_status status, void *data); + +void QueryPromiseCompleteCB(napi_env env, napi_status status, void *data); + +napi_value WrapResultSet(napi_env env, const std::shared_ptr &resultSet); + +void AnalysisValuesBucket(NativeRdb::ValuesBucket &value, const napi_env &env, const napi_value &arg); +void SetValuesBucketObject( + NativeRdb::ValuesBucket &valuesBucket, const napi_env &env, std::string keyStr, napi_value value); + +void UnwrapDataAbilityPredicates(NativeRdb::DataAbilityPredicates &predicates, napi_env env, napi_value value); +} // namespace AppExecFwk +} // namespace OHOS +#endif /* OHOS_APPEXECFWK_NAPI_DATASHARE_HELPER_H */ diff --git a/interfaces/kits/js/bundle/moduleInfo.d.ts b/interfaces/kits/napi/aafwk/dataShare/native_datashare_module.cpp similarity index 41% rename from interfaces/kits/js/bundle/moduleInfo.d.ts rename to interfaces/kits/napi/aafwk/dataShare/native_datashare_module.cpp index 437ca90fa900b5a314335a58234452900d3a78d8..078fee397f31628b7d2e4ac358ab6447b257b8c1 100644 --- a/interfaces/kits/js/bundle/moduleInfo.d.ts +++ b/interfaces/kits/napi/aafwk/dataShare/native_datashare_module.cpp @@ -1,43 +1,54 @@ -/* - * 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. - */ - -/** - * @name Stores module information about an application. - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @permission NA - * @devices phone, tablet, tv, wearable, car - */ -export interface ModuleInfo { - /** - * The module name. - * - * @default Indicates the name of the .hap package to which the capability belongs - * @devices phone, tablet, tv, wearable, car - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly moduleName: string; - - /** - * The module source path. - * - * @default Indicates the module source dir of this module - * @devices phone, tablet, tv, wearable, car - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - readonly moduleSourceDir: string; -} \ No newline at end of file +/* + * 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 "napi_datashare_helper.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace AppExecFwk { +EXTERN_C_START +/* + * The module initialization. + */ +static napi_value Init(napi_env env, napi_value exports) +{ + DataShareHelperInit(env, exports); + return exports; +} +EXTERN_C_END + +/* + * The module definition. + */ +static napi_module _module = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "data.dataShare", + .nm_priv = ((void *)0), + .reserved = {0} +}; + +/* + * The module registration. + */ +extern "C" __attribute__((constructor)) void RegisterModule(void) +{ + napi_module_register(&_module); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/dataShare/test/BUILD.gn b/interfaces/kits/napi/aafwk/dataShare/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4cf1996aa549c2000277cfa4067d6d4614c8ff32 --- /dev/null +++ b/interfaces/kits/napi/aafwk/dataShare/test/BUILD.gn @@ -0,0 +1,23 @@ +# 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("//build/test.gni") + +#################################group######################################### +group("unittest") { + testonly = true + deps = [] + + deps += [ "unittest:unittest" ] +} +############################################################################### diff --git a/interfaces/kits/napi/aafwk/dataShare/test/unittest/BUILD.gn b/interfaces/kits/napi/aafwk/dataShare/test/unittest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..73cdbe69155e57f3ddb6b04e5a7119be3d08897e --- /dev/null +++ b/interfaces/kits/napi/aafwk/dataShare/test/unittest/BUILD.gn @@ -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. + +import("//build/test.gni") + +module_output_path = "ability_runtime/datashare" + +ohos_js_unittest("DataShareJsTest") { + module_out_path = module_output_path + + hap_profile = "./config.json" + + if (is_standard_system) { + certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" + } else { + deps = [ "//test/developertest/adapter/examples/app_info/test/common/main:get_app_info_test_lib" ] + entry_app_dep = [ "//test/developertest/adapter/examples/app_info/test/common/shell:build_shell_execute" ] + } +} + +group("unittest") { + testonly = true + deps = [ ":DataShareJsTest" ] +} diff --git a/interfaces/kits/napi/aafwk/dataShare/test/unittest/DataShareJsunit.test.js b/interfaces/kits/napi/aafwk/dataShare/test/unittest/DataShareJsunit.test.js new file mode 100644 index 0000000000000000000000000000000000000000..65a03a220c340c3ce2f672d7e2b893b924f8ed74 --- /dev/null +++ b/interfaces/kits/napi/aafwk/dataShare/test/unittest/DataShareJsunit.test.js @@ -0,0 +1,1081 @@ +/* + * 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 {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import dataShare from '@ohos.data.dataShare'; +import dataAbility from '@ohos.data.dataAbility'; + +const TAG = "[DATASHARE_JSKITS_TEST]" +const URI = ("datashare:///com.samples.datasharetest.DataShare"); +let dseWant = { + "bundleName": "com.examples.datasharetest.service", + "abilityName": "DataShareExtAbility", +} + +describe('dataShareTest', function () { + beforeAll(async function () { + console.info(TAG + 'beforeAll') + }) + + beforeEach(function () { + console.info(TAG + 'beforeEach') + }) + + afterEach(function () { + console.info(TAG + 'afterEach') + }) + + afterAll(async function () { + console.info(TAG + 'afterAll') + }) + + console.log(TAG + "*************Unit Test Begin*************"); + + function onChangeNotify() { + console.info("==========================>onChangeNotify=======================>"); + } + + /** + * @tc.name data share createDataShareHelper test + * @tc.number SUB_DDM_DataShare_JS_createDataShareHelper_0000 + * @tc.desc data share createDataShareHelper test + */ + it('createDataShareHelper_0000', 0, async function (done) { + console.log(TAG + ":createDataShareHelper_0000 start"); + try { + let helper = dataShare.createDataShareHelper(this.context, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + expect(false).assertTrue(); + } catch (err) { + expect(true).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":createDataShareHelper_0000 end"); + }) + + /** + * @tc.name data share createDataShareHelper test + * @tc.number SUB_DDM_DataShare_JS_createDataShareHelper_0010 + * @tc.desc data share createDataShareHelper test + */ + it('createDataShareHelper_0010', 0, async function (done) { + console.log(TAG + ":createDataShareHelper_0010 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":createDataShareHelper_0010 end"); + }) + + /** + * @tc.name data share createDataShareHelper test + * @tc.number SUB_DDM_DataShare_JS_createDataShareHelper_0011 + * @tc.desc data share createDataShareHelper test + */ + it('createDataShareHelper_0011', 0, async function (done) { + console.log(TAG + ":createDataShareHelper_0011 start"); + try { + let helper = dataShare.createDataShareHelper(this.context, null, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + expect(false).assertTrue(); + } catch (err) { + expect(true).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":createDataShareHelper_0011 end"); + }) + + /** + * @tc.name data share createDataShareHelper test + * @tc.number SUB_DDM_DataShare_JS_createDataShareHelper_0012 + * @tc.desc data share createDataShareHelper test + */ + it('createDataShareHelper_0012', 0, async function (done) { + console.log(TAG + ":createDataShareHelper_0012 start"); + try { + let helper = dataShare.createDataShareHelper(this.context, dseWant, null); + console.log(TAG + ":DataShareHelper helper:" + helper); + expect(false).assertTrue(); + } catch (err) { + expect(true).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":createDataShareHelper_0012 end"); + }) + + /** + * @tc.name data share onEvent test + * @tc.number SUB_DDM_DataShare_JS_on_0020 + * @tc.desc data share onEvent test + */ + it('on_0020', 0, async function (done) { + console.log(TAG + ":on_0020 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + helper.on( + "dataChange", + URI, + onChangeNotify + ) + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":on_0020 end"); + }) + + /** + * @tc.name data share onEvent test + * @tc.number SUB_DDM_DataShare_JS_on_0021 + * @tc.desc data share onEvent test + */ + it('on_0021', 0, async function (done) { + console.log(TAG + ":on_0021 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + helper.on( + "dataChange", + null, + onChangeNotify + ) + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":on_0021 end"); + }) + + /** + * @tc.name data share offEvent test + * @tc.number SUB_DDM_DataShare_JS_off_0030 + * @tc.desc data share offEvent test + */ + it('off_0030', 0, async function (done) { + console.log(TAG + ":off_0030 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + helper.off( + "dataChange", + URI, + ) + helper.off( + "dataChange", + URI, + onChangeNotify + ) + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":off_0030 end"); + }) + + /** + * @tc.name data share offEvent test + * @tc.number SUB_DDM_DataShare_JS_off_0031 + * @tc.desc data share offEvent test + */ + it('off_0031', 0, async function (done) { + console.log(TAG + ":off_0031 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + helper.off( + "dataChange", + null, + onChangeNotify + ) + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":off_0031 end"); + }) + + /** + * @tc.name data share getType_callback test + * @tc.number SUB_DDM_DataShare_getType_0040 + * @tc.desc data share getType_callback test + */ + it('getType_callback_0040', 0, async function (done) { + console.log(TAG + ":getType_callback_0040 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + helper.getType( + URI, + (err, data) => { + console.info("==========================>Called=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":getType_callback_0040 end"); + }) + + /** + * @tc.name data share getType_promise test + * @tc.number SUB_DDM_DataShare_JS_getType_promise_0041 + * @tc.desc data share getType_promise test + */ + it('getType_promise_0041', 0, async function (done) { + console.log(TAG + ":getType_promise_0041 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + helper.getType( + URI + ).then((data) => { + console.info("==========================>getTypeCallback=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":getType_promise_0041 end"); + }) + + /** + * @tc.name data share getFileType_callback test + * @tc.number SUB_DDM_DataShare_JS_getFileType_callback_0050 + * @tc.desc data share getFileType_callback test + */ + it('getFileType_callback_0050', 0, async function (done) { + console.log(TAG + ":getFileType_callback_0050 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + helper.getFileTypes( + URI, + "image/*", + (err, data) => { + console.info("==========================>Called=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":getFileType_callback_0050 end"); + }) + + /** + * @tc.name data share getFileType_promise test + * @tc.number SUB_DDM_DataShare_JS_getFileType_promise_0051 + * @tc.desc data share getFileType_promise test + */ + it('getFileType_promise_0051', 0, async function (done) { + console.log(TAG + ":getFileType_promise_0051 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + helper.getFileTypes( + URI, + "image/*" + ).then((data) => { + console.info("==========================>getFileTypesCallback=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":getFileType_promise_0051 end"); + }) + + /** + * @tc.name data share getFileType_callback test + * @tc.number SUB_DDM_DataShare_JS_getFileType_callback_0052 + * @tc.desc data share getFileType_callback test + */ + it('getFileType_callback_0052', 0, async function (done) { + console.log(TAG + ":getFileType_callback_0052 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + helper.getFileTypes( + null, + "image/*", + (err, data) => { + console.info("==========================>Called=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":getFileType_callback_0052 end"); + }) + + /** + * @tc.name data share normalizeUri_callback test + * @tc.number SUB_DDM_DataShare_JS_normalizeUri_0060 + * @tc.desc data share normalizeUri_callback test + */ + it('normalizeUri_callback_0060', 0, async function (done) { + console.log(TAG + ":normalizeUri_callback_0060 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + helper.normalizeUri( + URI, + (err, data) => { + console.info("==========================>Called=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":normalizeUri_callback_0060 end"); + }) + + /** + * @tc.name data share normalizeUri_promise test + * @tc.number SUB_DDM_DataShare_JS_normalizeUri_promise_0061 + * @tc.desc data share normalizeUri_promise test + */ + it('normalizeUri_promise_0061', 0, async function (done) { + console.log(TAG + ":normalizeUri_promise_0061 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + helper.normalizeUri( + URI, + ).then((data) => { + console.info("==========================>normalizeUriCallback=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":normalizeUri_promise_0061 end"); + }) + + /** + * @tc.name data share normalizeUri_callback test + * @tc.number SUB_DDM_DataShare_JS_normalizeUri_0062 + * @tc.desc data share normalizeUri_callback test + */ + it('normalizeUri_callback_0062', 0, async function (done) { + console.log(TAG + ":normalizeUri_callback_0062 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + helper.normalizeUri( + null, + (err, data) => { + console.info("==========================>Called=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":normalizeUri_callback_0062 end"); + }) + + /** + * @tc.name data share denormalizeUri_callback test + * @tc.number SUB_DDM_DataShare_JS_denormalizeUri_callback_0060 + * @tc.desc data share denormalizeUri_callback test + */ + it('denormalizeUri_callback_0070', 0, async function (done) { + console.log(TAG + ":denormalizeUri_callback_0070 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + helper.denormalizeUri( + URI, + (err, data) => { + console.info("==========================>Called=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":denormalizeUri_callback_0070 end"); + }) + + /** + * @tc.name data share denormalizeUri_promise test + * @tc.number SUB_DDM_DataShare_JS_denormalizeUri_promise_0061 + * @tc.desc data share denormalizeUri_promise test + */ + it('denormalizeUri_promise_0071', 0, async function (done) { + console.log(TAG + ":denormalizeUri_promise_0071 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + helper.denormalizeUri( + URI, + ).then((data) => { + console.info("==========================>denormalizeUriCallback=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":denormalizeUri_promise_0071 end"); + }) + + /** + * @tc.name data share denormalizeUri_callback test + * @tc.number SUB_DDM_DataShare_JS_denormalizeUri_callback_0072 + * @tc.desc data share denormalizeUri_callback test + */ + it('denormalizeUri_callback_0072', 0, async function (done) { + console.log(TAG + ":denormalizeUri_callback_0072 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + helper.denormalizeUri( + null, + (err, data) => { + console.info("==========================>Called=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":denormalizeUri_callback_0072 end"); + }) + + /** + * @tc.name data share notifyChange_callback test + * @tc.number SUB_DDM_DataShare_JS_notifyChange_callback_0080 + * @tc.desc data share notifyChange_callback test + */ + it('notifyChange_callback_0080', 0, async function (done) { + console.log(TAG + ":notifyChange_callback_0080 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + helper.notifyChange( + URI, + (err) => { + console.info("==========================>Called=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":notifyChange_callback_0080 end"); + }) + + /** + * @tc.name data share notifyChange_promise test + * @tc.number SUB_DDM_DataShare_JS_notifyChange_promise_0081 + * @tc.desc data share notifyChange_promise test + */ + it('notifyChange_promise_0081', 0, async function (done) { + console.log(TAG + ":notifyChange_promise_0081 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + helper.notifyChange( + URI, + ).then(() => { + console.info("==========================>notifyChangeCallback=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":notifyChange_promise_0081 end"); + }) + + /** + * @tc.name data share notifyChange_callback test + * @tc.number SUB_DDM_DataShare_JS_notifyChange_callback_0082 + * @tc.desc data share notifyChange_callback test + */ + it('notifyChange_callback_0082', 0, async function (done) { + console.log(TAG + ":notifyChange_callback_0082 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + helper.notifyChange( + null, + (err) => { + console.info("==========================>Called=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":notifyChange_callback_0082 end"); + }) + + /** + * @tc.name data share insert_callback test + * @tc.number SUB_DDM_DataShare_JS_insert_callback_0090 + * @tc.desc data share insert_callback test + */ + it('insert_callback_0090', 0, async function (done) { + console.log(TAG + ":insert_callback_0090 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + const valueBucket = { + "name": "rose", + "age": 22, + "salary": 200.5, + "blobType": u8, + } + helper.insert( + URI, + valueBucket, + (err, data) => { + console.info("==========================>Called=======================>"); + }); + expect(false).assertTrue(); + } catch (err) { + expect(true).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":insert_callback_0090 end"); + }) + + /** + * @tc.name data share insert_promise test + * @tc.number SUB_DDM_DataShare_JS_insert_promise_0091 + * @tc.desc data share insert_promise test + */ + it('insert_promise_0091', 0, async function (done) { + console.log(TAG + ":insert_promise_0081 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + const valueBucket = { + "name": "rose1", + "age": 221, + "salary": 20.5, + "blobType": u8, + } + helper.insert( + URI, + valueBucket + ).then((data) => { + console.info("==========================>insertCallback=======================>"); + }); + expect(false).assertTrue(); + } catch (err) { + expect(true).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":insert_promise_0091 end"); + }) + + /** + * @tc.name data share insert_callback test + * @tc.number SUB_DDM_DataShare_JS_insert_callback_0092 + * @tc.desc data share insert_callback test + */ + it('insert_callback_0092', 0, async function (done) { + console.log(TAG + ":insert_callback_0092 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + const valueBucket = { + "name": "rose", + "age": 22, + "salary": 200.5, + "blobType": u8, + } + helper.insert( + null, + valueBucket, + (err, data) => { + console.info("==========================>Called=======================>"); + }); + expect(false).assertTrue(); + } catch (err) { + expect(true).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":insert_callback_0092 end"); + }) + + /** + * @tc.name data share batchInsert_callback test + * @tc.number SUB_DDM_DataShare_JS_batchInsert_callback_0090 + * @tc.desc data share batchInsert_callback test + */ + it('batchInsert_callback_0100', 0, async function (done) { + console.log(TAG + ":batchInsert_callback_0100 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": u8,}, + {"name": "roe12", "age": 21, "salary": 20.5, "blobType": u8,}, + {"name": "roe13", "age": 21, "salary": 20.5, "blobType": u8,}) + helper.batchInsert( + URI, + cars, + (err, data) => { + console.info("==========================>Called=======================>"); + }); + expect(false).assertTrue(); + } catch (err) { + expect(true).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":batchInsert_callback_0100 end"); + }) + + /** + * @tc.name data share batchInsert_promise test + * @tc.number SUB_DDM_DataShare_JS_batchInsert_promise_0101 + * @tc.desc data share createDataShareHelper test + */ + it('batchInsert_promise_0101', 0, async function (done) { + console.log(TAG + ":batchInsert_promise_0101 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": u8,}, + {"name": "roe12", "age": 21, "salary": 20.5, "blobType": u8,}, + {"name": "roe13", "age": 21, "salary": 20.5, "blobType": u8,}) + helper.batchInsert( + URI, + cars + ).then((data) => { + console.info("==========================>batchInsertCallback=======================>"); + }); + expect(false).assertTrue(); + } catch (err) { + expect(true).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":batchInsert_promise_0101 end"); + }) + + /** + * @tc.name data share batchInsert_callback test + * @tc.number SUB_DDM_DataShare_JS_batchInsert_callback_0102 + * @tc.desc data share batchInsert_callback test + */ + it('batchInsert_callback_0102', 0, async function (done) { + console.log(TAG + ":batchInsert_callback_0102 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": u8,}, + {"name": "roe12", "age": 21, "salary": 20.5, "blobType": u8,}, + {"name": "roe13", "age": 21, "salary": 20.5, "blobType": u8,}) + helper.batchInsert( + null, + cars, + (err, data) => { + console.info("==========================>Called=======================>"); + }); + expect(false).assertTrue(); + } catch (err) { + expect(true).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":batchInsert_callback_0102 end"); + }) + + /** + * @tc.name data share delete_callback test + * @tc.number SUB_DDM_DataShare_JS_delete_callback_0110 + * @tc.desc data share delete_callback test + */ + it('delete_callback_0110', 0, async function (done) { + console.log(TAG + ":delete_callback_0110 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + let da = new dataAbility.DataAbilityPredicates() + helper.delete( + URI, + da, + (err, data) => { + console.info("==========================>Called=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":delete_callback_0110 end"); + }) + + /** + * @tc.name data share delete_promise test + * @tc.number SUB_DDM_DataShare_JS_delete_promise_0111 + * @tc.desc data share delete_promise test + */ + it('delete_promise_0111', 0, async function (done) { + console.log(TAG + ":delete_promise_0111 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + let da = new dataAbility.DataAbilityPredicates() + helper.delete( + URI, + da + ).then((data) => { + console.info("==========================>deleteCallback=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":delete_promise_0111 end"); + }) + + /** + * @tc.name data share delete_callback test + * @tc.number SUB_DDM_DataShare_JS_delete_callback_0112 + * @tc.desc data share delete_callback test + */ + it('delete_callback_0112', 0, async function (done) { + console.log(TAG + ":delete_callback_0112 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + let da = new dataAbility.DataAbilityPredicates() + helper.delete( + null, + da, + (err, data) => { + console.info("==========================>Called=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":delete_callback_0112 end"); + }) + + /** + * @tc.name data share delete_callback test + * @tc.number SUB_DDM_DataShare_JS_delete_callback_0113 + * @tc.desc data share delete_callback test + */ + it('delete_callback_0113', 0, async function (done) { + console.log(TAG + ":delete_callback_0113 start"); + try { + let helper = dataShare.createDataShareHelper(this.context, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + let da = new dataAbility.DataAbilityPredicates() + helper.delete( + URI, + da, + (err, data) => { + console.info("==========================>Called=======================>"); + }); + expect(false).assertTrue(); + } catch (err) { + expect(true).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":delete_callback_0113 end"); + }) + + /** + * @tc.name data share update_callback test + * @tc.number SUB_DDM_DataShare_JS_update_callback_0120 + * @tc.desc data share update_callback test + */ + it('update_callback_0120', 0, async function (done) { + console.log(TAG + ":update_callback_0120 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + const va = { + "name": "roe1", + "age": 21, + "salary": 20.5, + "blobType": u8, + } + let da = new dataAbility.DataAbilityPredicates() + helper.update( + URI, + va, + da, + (err, data) => { + console.info("==========================>Called=======================>"); + }); + expect(false).assertTrue(); + } catch (err) { + expect(true).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":update_callback_0120 end"); + }) + + /** + * @tc.name data share update_promise test + * @tc.number SUB_DDM_DataShare_JS_update_promise_0121 + * @tc.desc data share update_promise test + */ + it('update_promise_0121', 0, async function (done) { + console.log(TAG + ":update_promise_0121 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + const va = { + "name": "roe1", + "age": 21, + "salary": 20.5, + "blobType": u8, + } + let da = new dataAbility.DataAbilityPredicates() + helper.update( + URI, + va, + da + ).then((data) => { + console.info("==========================>updateCallback=======================>"); + }); + expect(false).assertTrue(); + } catch (err) { + expect(true).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":update_promise_0121 end"); + }) + + /** + * @tc.name data share update_callback test + * @tc.number SUB_DDM_DataShare_JS_update_callback_0122 + * @tc.desc data share update_callback test + */ + it('update_callback_0122', 0, async function (done) { + console.log(TAG + ":update_callback_0122 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + const va = { + "name": "roe1", + "age": 21, + "salary": 20.5, + "blobType": u8, + } + let da = new dataAbility.DataAbilityPredicates() + helper.update( + null, + va, + da, + (err, data) => { + console.info("==========================>Called=======================>"); + }); + expect(false).assertTrue(); + } catch (err) { + expect(true).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":update_callback_0122 end"); + }) + + /** + * @tc.name data share update_callback test + * @tc.number SUB_DDM_DataShare_JS_update_callback_0123 + * @tc.desc data share update_callback test + */ + it('update_callback_0123', 0, async function (done) { + console.log(TAG + ":update_callback_0123 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + let da = new dataAbility.DataAbilityPredicates() + helper.update( + URI, + null, + da, + (err, data) => { + console.info("==========================>Called=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":update_callback_0123 end"); + }) + + /** + * @tc.name data share query_callback test + * @tc.number SUB_DDM_DataShare_JS_query_callback_0130 + * @tc.desc data share query_callback test + */ + it('query_callback_0130', 0, async function (done) { + console.log(TAG + ":query_callback_0130 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + let da = new dataAbility.DataAbilityPredicates() + helper.query( + URI, + ["*"], + da, + (err, data) => { + console.info("==========================>Called=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":query_callback_0130 end"); + }) + + /** + * @tc.name data share query_promise test + * @tc.number SUB_DDM_DataShare_JS_query_promise_0131 + * @tc.desc data share query_promise test + */ + it('query_promise_0131', 0, async function (done) { + console.log(TAG + ":query_promise_0131 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + let da = new dataAbility.DataAbilityPredicates() + helper.query( + URI, + ["*"], + da + ).then((data) => { + console.info("==========================>queryCallback=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":query_promise_0131 end"); + }) + + /** + * @tc.name data share query_callback test + * @tc.number SUB_DDM_DataShare_JS_query_callback_0132 + * @tc.desc data share query_callback test + */ + it('query_callback_0132', 0, async function (done) { + console.log(TAG + ":query_callback_0132 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + let da = new dataAbility.DataAbilityPredicates() + helper.query( + null, + ["*"], + da, + (err, data) => { + console.info("==========================>Called=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":query_callback_0130 end"); + }) + + /** + * @tc.name data share query_promise test + * @tc.number SUB_DDM_DataShare_JS_query_promise_0133 + * @tc.desc data share query_promise test + */ + it('query_promise_0133', 0, async function (done) { + console.log(TAG + ":query_promise_0133 start"); + try { + let helper = dataShare.createDataShareHelper(null, dseWant, URI); + console.log(TAG + ":DataShareHelper helper:" + helper); + let da = new dataAbility.DataAbilityPredicates() + helper.query( + URI, + null, + da + ).then((data) => { + console.info("==========================>queryCallback=======================>"); + }); + expect(true).assertTrue(); + } catch (err) { + expect(false).assertTrue(); + console.log(TAG + ":DataShareHelper catch err:" + err); + } + done(); + console.log(TAG + ":query_promise_0133 end"); + }) + + console.log(TAG + "*************Unit Test End*************"); +}) diff --git a/interfaces/kits/napi/aafwk/dataShare/test/unittest/config.json b/interfaces/kits/napi/aafwk/dataShare/test/unittest/config.json new file mode 100644 index 0000000000000000000000000000000000000000..c5d82560491628b93fd180f2497144a2fb8060ae --- /dev/null +++ b/interfaces/kits/napi/aafwk/dataShare/test/unittest/config.json @@ -0,0 +1,60 @@ +{ + "app": { + "bundleName": "com.example.myapplication", + "vendor": "example", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 4, + "target": 5 + } + }, + "deviceConfig": {}, + "module": { + "package": "com.example.myapplication", + "name": ".MyApplication", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "entry", + "moduleType": "entry" + }, + "abilities": [ + { + "visible": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "name": "com.example.myapplication.MainAbility", + "icon": "$media:icon", + "description": "$string:mainability_description", + "label": "MyApplication", + "type": "page", + "launchType": "standard" + } + ], + "js": [ + { + "pages": [ + "pages/index/index" + ], + "name": "default", + "window": { + "designWidth": 720, + "autoDesignWidth": false + } + } + ] + } +} diff --git a/interfaces/kits/napi/aafwk/dataUriUtils/BUILD.gn b/interfaces/kits/napi/aafwk/dataUriUtils/BUILD.gn index 514a76bd990facda8c3ee9fcf817fa4c22e5ba9d..eb8629cb21e3de09f62217f06570141a13e7735f 100644 --- a/interfaces/kits/napi/aafwk/dataUriUtils/BUILD.gn +++ b/interfaces/kits/napi/aafwk/dataUriUtils/BUILD.gn @@ -39,9 +39,9 @@ ohos_shared_library("datauriutils") { ] external_deps = [ + "ability_base:want", "ability_runtime:ability_manager", "ability_runtime:app_manager", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "eventhandler:libeventhandler", diff --git a/interfaces/kits/napi/aafwk/dataUriUtils/napi_data_uri_utils.cpp b/interfaces/kits/napi/aafwk/dataUriUtils/napi_data_uri_utils.cpp index 60c2d24a3500c52021cdca09be287cc793726dd3..f1488e83dafb8bc5b16c83661fe351df73116b88 100644 --- a/interfaces/kits/napi/aafwk/dataUriUtils/napi_data_uri_utils.cpp +++ b/interfaces/kits/napi/aafwk/dataUriUtils/napi_data_uri_utils.cpp @@ -14,8 +14,8 @@ */ #include "napi_data_uri_utils.h" +#include #include -#include #include #include "data_uri_utils.h" @@ -201,4 +201,4 @@ napi_value NAPI_UpdateIdSync(napi_env env, napi_callback_info info) return uriUpdated; } } // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/interfaces/kits/napi/aafwk/datashare_ext_ability/BUILD.gn b/interfaces/kits/napi/aafwk/datashare_ext_ability/BUILD.gn index d2dac83fb47137ddb2b0eb2781d1e454d7be0fc9..b6f58ee3e56e3770777b256bf17639d3be700a32 100644 --- a/interfaces/kits/napi/aafwk/datashare_ext_ability/BUILD.gn +++ b/interfaces/kits/napi/aafwk/datashare_ext_ability/BUILD.gn @@ -34,7 +34,7 @@ gen_js_obj("datashare_ext_ability_abc") { dep = ":gen_datashare_ext_ability_abc" } -ohos_shared_library("datashareextability_napi") { +ohos_shared_library("datashareextensionability_napi") { sources = [ "datashare_ext_ability_module.cpp" ] deps = [ 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 index a9217854ec838a95cf62a17ef93ab93c63448586..3ab00cd1480fa5cb2226cf2b4c60be7a3f98184c 100644 --- a/interfaces/kits/napi/aafwk/datashare_ext_ability/datashare_ext_ability.js +++ b/interfaces/kits/napi/aafwk/datashare_ext_ability/datashare_ext_ability.js @@ -13,7 +13,7 @@ * limitations under the License. */ -class DataShareExtAbility { +class DataShareExtensionAbility { onCreate(want) { console.log('onCreate, want:' + want.abilityName); } @@ -63,4 +63,4 @@ class DataShareExtAbility { } } -export default DataShareExtAbility \ No newline at end of file +export default DataShareExtensionAbility \ 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 index a481dbf8ba6dcaa0666939fec65461b782cce961..9e0d46b7a17f52d0cd1ad94669b6cd58be631ad3 100644 --- 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 @@ -21,19 +21,19 @@ 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() +void NAPI_application_DataShareExtensionAbility_AutoRegister() { auto moduleManager = NativeModuleManager::GetInstance(); NativeModule newModuleInfo = { - .name = "application.DataShareExtAbility", - .fileName = "application/libdatashareextability_napi.so/DataShareExtAbility.js", + .name = "application.DataShareExtensionAbility", + .fileName = "application/libdatashareextensionability_napi.so/DataShareExtensionAbility.js", }; moduleManager->Register(&newModuleInfo); } extern "C" __attribute__((visibility("default"))) -void NAPI_application_DataShareExtAbility_GetJSCode(const char **buf, int *bufLen) +void NAPI_application_DataShareExtensionAbility_GetJSCode(const char **buf, int *bufLen) { if (buf != nullptr) { *buf = _binary_datashare_ext_ability_js_start; @@ -44,9 +44,9 @@ void NAPI_application_DataShareExtAbility_GetJSCode(const char **buf, int *bufLe } } -// datashare_ext_ability JS register +// datashare extension ability JS register extern "C" __attribute__((visibility("default"))) -void NAPI_application_DataShareExtAbility_GetABCCode(const char **buf, int *buflen) +void NAPI_application_DataShareExtensionAbility_GetABCCode(const char **buf, int *buflen) { if (buf != nullptr) { *buf = _binary_datashare_ext_ability_abc_start; diff --git a/interfaces/kits/napi/aafwk/datashare_ext_ability_context/BUILD.gn b/interfaces/kits/napi/aafwk/datashare_ext_ability_context/BUILD.gn index fea405b54aa8c4bc6e72dcba756f2d2e6a65a50c..fc18df9c42897e05d91df4d43e12ae1a324f96fc 100644 --- a/interfaces/kits/napi/aafwk/datashare_ext_ability_context/BUILD.gn +++ b/interfaces/kits/napi/aafwk/datashare_ext_ability_context/BUILD.gn @@ -35,7 +35,7 @@ gen_js_obj("datashare_ext_ability_context_abc") { dep = ":gen_datashare_ext_ability_context_abc" } -ohos_shared_library("datashareextabilitycontext_napi") { +ohos_shared_library("datashareextensionabilitycontext_napi") { sources = [ "datashare_ext_ability_context_module.cpp" ] deps = [ 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 index 9da9778d8cb91df032218462b418eb1da487ec92..68ddf9c897f35b6969b8c5a9611e775692c6b951 100644 --- 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 @@ -15,10 +15,10 @@ var ExtensionContext = requireNapi("application.ExtensionContext") -class DataShareExtAbilityContext extends ExtensionContext { +class DataShareExtensionAbilityContext extends ExtensionContext { constructor(obj) { super(obj); } } -export default DataShareExtAbilityContext \ No newline at end of file +export default DataShareExtensionAbilityContext \ 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 index a5cf65bb9ed7ae3558322af937f6d201a58e2cac..145456c2d85567eceaf93e4a3380748802ec651b 100644 --- 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 @@ -21,19 +21,19 @@ 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() +void NAPI_application_DataShareExtensionAbilityContext_AutoRegister() { auto moduleManager = NativeModuleManager::GetInstance(); NativeModule newModuleInfo = { - .name = "application.DataShareExtAbilityContext", - .fileName = "application/libdatashareextabilitycontext_napi.so/DataShareExtAbilityContext.js", + .name = "application.DataShareExtensionAbilityContext", + .fileName = "application/libdatashareextensionabilitycontext_napi.so/DataShareExtensionAbilityContext.js", }; moduleManager->Register(&newModuleInfo); } extern "C" __attribute__((visibility("default"))) -void NAPI_application_DataShareExtAbilityContext_GetJSCode(const char **buf, int *bufLen) +void NAPI_application_DataShareExtensionAbilityContext_GetJSCode(const char **buf, int *bufLen) { if (buf != nullptr) { *buf = _binary_datashare_ext_ability_context_js_start; @@ -44,9 +44,9 @@ void NAPI_application_DataShareExtAbilityContext_GetJSCode(const char **buf, int } } -// ability_context JS register +// datashare extension ability context JS register extern "C" __attribute__((visibility("default"))) -void NAPI_application_DataShareExtAbilityContext_GetABCCode(const char **buf, int *buflen) +void NAPI_application_DataShareExtensionAbilityContext_GetABCCode(const char **buf, int *buflen) { if (buf != nullptr) { *buf = _binary_datashare_ext_ability_context_abc_start; diff --git a/interfaces/kits/napi/aafwk/ext_ability_context/BUILD.gn b/interfaces/kits/napi/aafwk/ext_ability_context/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..b686072176d3360447d7fd63c27ecd24adf7c3fa --- /dev/null +++ b/interfaces/kits/napi/aafwk/ext_ability_context/BUILD.gn @@ -0,0 +1,50 @@ +# 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("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") + +ts2abc_gen_abc("gen_ext_ability_context_abc") { + src_js = rebase_path("ext_ability_context.js") + dst_file = rebase_path(target_out_dir + "/ext_ability_context.abc") + in_puts = [ "ext_ability_context.js" ] + out_puts = [ target_out_dir + "/ext_ability_context.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("ext_ability_context_js") { + input = "ext_ability_context.js" + output = target_out_dir + "/ext_ability_context.o" +} + +gen_js_obj("ext_ability_context_abc") { + input = get_label_info(":gen_ext_ability_context_abc", "target_out_dir") + + "/ext_ability_context.abc" + output = target_out_dir + "/ext_ability_context_abc.o" + dep = ":gen_ext_ability_context_abc" +} + +ohos_shared_library("extabilitycontext_napi") { + sources = [ "ext_ability_context_module.cpp" ] + + deps = [ + ":ext_ability_context_abc", + ":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/js/bundle/customizedata.ts b/interfaces/kits/napi/aafwk/ext_ability_context/ext_ability_context.js similarity index 62% rename from interfaces/kits/js/bundle/customizedata.ts rename to interfaces/kits/napi/aafwk/ext_ability_context/ext_ability_context.js index 68258099d6e4dec6021fa7070566f877cbc7fb76..9f0af27655c3370e67947ed7da63f97c6909e1b3 100644 --- a/interfaces/kits/js/bundle/customizedata.ts +++ b/interfaces/kits/napi/aafwk/ext_ability_context/ext_ability_context.js @@ -12,8 +12,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +var Context = requireNapi("application.Context") -export interface CustomizeData { - name: string; - value: string; -} \ No newline at end of file +class ExtAbilityContext extends Context { + constructor(obj) { + super(obj); + this.currentHapModuleInfo = obj.currentHapModuleInfo + this.config = obj.config + } + + onUpdateConfiguration(config) { + this.config = config + } +} + +export default ExtAbilityContext \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/ext_ability_context/ext_ability_context_module.cpp b/interfaces/kits/napi/aafwk/ext_ability_context/ext_ability_context_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8dd6d814cf9379431647f8ed15cf8c7a33215a9f --- /dev/null +++ b/interfaces/kits/napi/aafwk/ext_ability_context/ext_ability_context_module.cpp @@ -0,0 +1,57 @@ +/* + * 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 "native_engine/native_engine.h" + +extern const char _binary_ext_ability_context_js_start[]; +extern const char _binary_ext_ability_context_js_end[]; +extern const char _binary_ext_ability_context_abc_start[]; +extern const char _binary_ext_ability_context_abc_end[]; + +extern "C" __attribute__((constructor)) +void NAPI_application_ExtAbilityContext_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.ExtAbilityContext", + .fileName = "application/libextensioncontext_napi.so/ext_ability_context.js", + }; + + moduleManager->Register(&newModuleInfo); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_application_ExtAbilityContext_GetJSCode(const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_ext_ability_context_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_ext_ability_context_js_end - _binary_ext_ability_context_js_start; + } +} + +// extension_context JS register +extern "C" __attribute__((visibility("default"))) +void NAPI_application_ExtAbilityContext_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_ext_ability_context_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_ext_ability_context_abc_end - _binary_ext_ability_context_abc_start; + } +} \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/extensioncontext/extension_context.js b/interfaces/kits/napi/aafwk/extensioncontext/extension_context.js index d1cfa0916dbbe7367f8829efeacde51e49e98f69..efd518fc1b7f3a4ff4530a95646de4f7bb61ef95 100755 --- a/interfaces/kits/napi/aafwk/extensioncontext/extension_context.js +++ b/interfaces/kits/napi/aafwk/extensioncontext/extension_context.js @@ -18,6 +18,11 @@ class ExtensionContext extends Context { constructor(obj) { super(obj); this.currentHapModuleInfo = obj.currentHapModuleInfo + this.config = obj.config + } + + onUpdateConfiguration(config) { + this.config = config } } diff --git a/interfaces/kits/napi/aafwk/featureAbility/BUILD.gn b/interfaces/kits/napi/aafwk/featureAbility/BUILD.gn index aba4e97bab37c9690808522133e976bbc3157e82..a8503a0897b16eb00348ee50a8fdcf290d42cda2 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/BUILD.gn +++ b/interfaces/kits/napi/aafwk/featureAbility/BUILD.gn @@ -54,10 +54,10 @@ ohos_shared_library("featureability") { ] external_deps = [ + "ability_base:want", "ability_runtime:ability_manager", "ability_runtime:app_manager", "ability_runtime:napi_base_context", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "eventhandler:libeventhandler", diff --git a/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp b/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp index 2c4f15aafefcc5a29ca60cffe3ab83b9c6afc440..cd99c9c60af892543801fa17433d52fa0dc6408e 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp +++ b/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp @@ -183,7 +183,7 @@ napi_value StartAbilityForResultAsync(napi_env env, AsyncCallbackInfo *asyncCall HILOG_INFO("NAPI_StartAbilityForResult, worker pool thread execute."); AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); if (asyncCallbackInfo != nullptr) { - AbilityProcess::GetInstance()->StartAbility( + asyncCallbackInfo->errCode = AbilityProcess::GetInstance()->StartAbility( asyncCallbackInfo->ability, asyncCallbackInfo->param, asyncCallbackInfo->aceCallback); } else { HILOG_ERROR("NAPI_StartAbilityForResult, asyncCallbackInfo == nullptr"); @@ -191,8 +191,13 @@ napi_value StartAbilityForResultAsync(napi_env env, AsyncCallbackInfo *asyncCall HILOG_INFO("NAPI_StartAbilityForResult, worker pool thread execute end."); }, [](napi_env env, napi_status status, void *data) { - HILOG_INFO("NAPI_StartAbilityForResult, main event thread complete."); AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); + HILOG_INFO("NAPI_StartAbilityForResult, complete. err:%{public}d", asyncCallbackInfo->errCode); + if (asyncCallbackInfo->errCode != ERR_OK) { + Want resultData; // Callback the errcode when StartAbilityForResult failed. + AbilityProcess::GetInstance()->OnAbilityResult(asyncCallbackInfo->ability, + asyncCallbackInfo->param.requestCode, 0, resultData); + } // remove asynccallback from startabilityforresult if (asyncCallbackInfo->cbInfo.callback != nullptr) { napi_delete_reference(env, asyncCallbackInfo->cbInfo.callback); @@ -233,7 +238,7 @@ napi_value StartAbilityForResultPromise(napi_env env, AsyncCallbackInfo *asyncCa HILOG_INFO("NAPI_StartAbilityForResult, worker pool thread execute."); AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); if (asyncCallbackInfo != nullptr) { - AbilityProcess::GetInstance()->StartAbility( + asyncCallbackInfo->errCode = AbilityProcess::GetInstance()->StartAbility( asyncCallbackInfo->ability, asyncCallbackInfo->param, asyncCallbackInfo->aceCallback); } else { HILOG_ERROR("NAPI_StartAbilityForResult, asyncCallbackInfo == nullptr"); @@ -241,8 +246,13 @@ napi_value StartAbilityForResultPromise(napi_env env, AsyncCallbackInfo *asyncCa HILOG_INFO("NAPI_StartAbilityForResult, worker pool thread execute end."); }, [](napi_env env, napi_status status, void *data) { - HILOG_INFO("NAPI_StartAbilityForResult, main event thread complete."); AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); + HILOG_INFO("NAPI_StartAbilityForResult, complete. err:%{public}d", asyncCallbackInfo->errCode); + if (asyncCallbackInfo->errCode != ERR_OK) { + Want resultData; // Callback the errcode when StartAbilityForResult failed. + AbilityProcess::GetInstance()->OnAbilityResult(asyncCallbackInfo->ability, + asyncCallbackInfo->param.requestCode, 0, resultData); + } // resolve it when call onAbilityResult napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; @@ -844,7 +854,7 @@ void CallOnAbilityResult(int requestCode, int resultCode, const Want &resultData // JS Thread OnAbilityCallback *onAbilityCB = static_cast(work->data); napi_value result[ARGS_TWO] = {0}; - result[PARAM0] = GetCallbackErrorValue(onAbilityCB->cb.env, NO_ERROR); + result[PARAM0] = GetCallbackErrorValue(onAbilityCB->cb.env, onAbilityCB->cb.errCode); napi_create_object(onAbilityCB->cb.env, &result[PARAM1]); // create resultCode @@ -1416,7 +1426,7 @@ napi_value ContinueAbilityWrap(napi_env env, napi_callback_info info, AsyncCallb HILOG_ERROR("%{public}s, Wrong argument type. Object or function expected.", __func__); return nullptr; } - if (0 == argc) { + if (argc == 0) { ret = ContinueAbilityPromise(env, args, asyncCallbackInfo, argc); } else if (PARA_SIZE_IS_ONE == argc) { if (valueType == napi_function) { 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 3e6eee3d2647b240b6ada64f5c56f2f37db3f25d..5335c41e15abcc8ee913ab933bdebf527bb2e236 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp +++ b/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp @@ -95,41 +95,41 @@ napi_value DataAbilityHelperConstructor(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); NAPI_ASSERT(env, argc > 0, "Wrong number of arguments"); - 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)); - } - } + 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)); + } + } if (dataAbilityHelper == nullptr) { HILOG_INFO("%{public}s, dataAbilityHelper is nullptr", __func__); @@ -2950,7 +2950,7 @@ napi_value QueryWrap(napi_env env, napi_callback_info info, DAHelperQueryCB *que std::vector result; bool arrayStringbool = false; arrayStringbool = NapiValueToArrayStringUtf8(env, args[PARAM1], result); - if (arrayStringbool == false) { + if (!arrayStringbool) { HILOG_ERROR("%{public}s, The return value of arraystringbool is false", __func__); } queryCB->columns = result; diff --git a/interfaces/kits/napi/aafwk/formManager/BUILD.gn b/interfaces/kits/napi/aafwk/formManager/BUILD.gn index 49a09746b3dd5fbe0285f4f13ca836cfb19e58e7..0b8bb64eb72bbdc9bf67d3bf1c470a4c2c755c15 100644 --- a/interfaces/kits/napi/aafwk/formManager/BUILD.gn +++ b/interfaces/kits/napi/aafwk/formManager/BUILD.gn @@ -35,9 +35,9 @@ ohos_shared_library("formmanager") { ] external_deps = [ + "ability_base:want", "ability_runtime:ability_manager", "ability_runtime:runtime", - "ability_runtime:want", "hiviewdfx_hilog_native:libhilog", ] diff --git a/interfaces/kits/napi/aafwk/formManager/native_module.cpp b/interfaces/kits/napi/aafwk/formManager/native_module.cpp index ae0c302a0411c726443b39271caad19b3b7af524..3983804a17795bfc79810deeabfcb88ef153e4f9 100644 --- a/interfaces/kits/napi/aafwk/formManager/native_module.cpp +++ b/interfaces/kits/napi/aafwk/formManager/native_module.cpp @@ -14,9 +14,9 @@ */ #include "napi/native_api.h" +#include +#include #include -#include -#include #include #include "napi/native_node_api.h" 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 e4abf671e7d39562b774487772a13effb0b3389b..7330ca429334f09c3055f7842f2d5ec024eb21fc 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 @@ -23,7 +23,7 @@ namespace AbilityRuntime { namespace { class FormBindingData { public: - FormBindingData(const std::shared_ptr& formProviderData) + explicit FormBindingData(const std::shared_ptr& formProviderData) : formProviderData_(formProviderData) {} ~FormBindingData() = default; @@ -67,7 +67,6 @@ NativeValue* FormBindingData::OnCreateFormBindingData(NativeEngine& engine, Nati } else if ((info.argv[0])->TypeOf() == NATIVE_OBJECT) { HILOG_DEBUG("%{public}s called, param type is object.", __func__); napi_env napiEnv = reinterpret_cast(&engine); - napi_value globalValue = nullptr; napi_get_global(napiEnv, &globalValue); napi_value jsonValue; @@ -93,7 +92,7 @@ NativeValue* FormBindingData::OnCreateFormBindingData(NativeEngine& engine, Nati NativeObject* object = ConvertNativeValueTo(objValue); formProviderData_->SetDataString(formDataStr); object->SetProperty("data", CreateJsValue(engine, formDataStr)); - HILOG_INFO("%{public}s called end.", __func__); + HILOG_INFO("%{public}s called:%{public}s", __func__, formDataStr.c_str()); return objValue; } @@ -139,4 +138,4 @@ NativeValue* FormBindingDataInit(NativeEngine* engine, NativeValue* exportObj) return exportObj; } } // namespace AbilityRuntime -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/interfaces/kits/napi/aafwk/form_extension_context/form_extension_context.js b/interfaces/kits/napi/aafwk/form_extension_context/form_extension_context.js index eaf347e222862575165f4f2018fed59224ea52e2..ae2371f61e20c2d3fbc53c505ae0f6f446a88d46 100644 --- a/interfaces/kits/napi/aafwk/form_extension_context/form_extension_context.js +++ b/interfaces/kits/napi/aafwk/form_extension_context/form_extension_context.js @@ -25,6 +25,10 @@ class FormExtensionContext extends ExtensionContext { return this.__context_impl__.updateForm(formId, formBindingData, callback); } + startAbility(want, options, callback) { + console.log("startAbility"); + return this.__context_impl__.startAbility(want, options, callback); + } } -export default FormExtensionContext \ No newline at end of file +export default FormExtensionContext diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn b/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn index 0cc0228b1c8c9e3376c3500a08a90663bd69a157..dd4f40fdbc273bb4fdb48a9cc6335cfc821e5c3f 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn +++ b/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn @@ -39,10 +39,12 @@ ohos_shared_library("napi_common") { ] external_deps = [ + "ability_base:configuration", + "ability_base:want", "ability_runtime:ability_manager", "ability_runtime:app_manager", "ability_runtime:napi_base_context", - "ability_runtime:want", + "ability_runtime:wantagent_innerkits", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "eventhandler:libeventhandler", diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/feature_ability_common.h b/interfaces/kits/napi/aafwk/inner/napi_common/feature_ability_common.h index 5441466206d55018796e8ed033023cf83520c0a8..39bf4287bc74d4ed2773e0305e55de6347bc2647 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/feature_ability_common.h +++ b/interfaces/kits/napi/aafwk/inner/napi_common/feature_ability_common.h @@ -58,6 +58,7 @@ struct AsyncCallbackInfo { napi_async_work asyncWork = nullptr; napi_deferred deferred = nullptr; Ability *ability = nullptr; + AbilityRuntime::WantAgent::WantAgent *wantAgent = nullptr; CallAbilityParam param; CallbackInfo aceCallback; bool native_result; 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 71d51480c3887c7cb8230f16a2dc033f858265b8..757021a27942948fb490ce894f816f95206a00e2 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 @@ -3501,5 +3501,340 @@ napi_value AcquireDataAbilityHelperWrap(napi_env env, napi_callback_info info, D HILOG_INFO("%{public}s,end", __func__); return result; } + +napi_value UnwrapParamForWantAgent(napi_env &env, napi_value &args, AbilityRuntime::WantAgent::WantAgent *&wantAgent) +{ + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + napi_value wantAgentParam = nullptr; + napi_value result = nullptr; + + bool hasProperty = false; + NAPI_CALL(env, napi_has_named_property(env, args, "wantAgent", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, args, "wantAgent", &wantAgentParam); + NAPI_CALL(env, napi_typeof(env, wantAgentParam, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + napi_unwrap(env, wantAgentParam, (void **)&wantAgent); + } + + napi_get_null(env, &result); + return result; +} + +void StartBackgroundRunningExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("%{public}s called.", __func__); + AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s asyncCallbackInfo == nullptr", __func__); + return; + } + if (asyncCallbackInfo->errCode == NAPI_ERR_PARAM_INVALID) { + HILOG_ERROR("parse input param failed"); + return; + } + if (asyncCallbackInfo->ability == nullptr) { + asyncCallbackInfo->errCode = NAPI_ERR_ACE_ABILITY; + HILOG_ERROR("%{public}s ability == nullptr", __func__); + return; + } + const std::shared_ptr info = asyncCallbackInfo->ability->GetAbilityInfo(); + if (info == nullptr) { + HILOG_ERROR("abilityinfo is null"); + asyncCallbackInfo->errCode = NAPI_ERR_ACE_ABILITY; + return; + } + + AbilityRuntime::WantAgent::WantAgent wantAgentObj; + if (!asyncCallbackInfo->wantAgent) { + HILOG_WARN("input param without wantAgent"); + wantAgentObj = AbilityRuntime::WantAgent::WantAgent(); + } else { + wantAgentObj = *asyncCallbackInfo->wantAgent; + } + asyncCallbackInfo->errCode = asyncCallbackInfo->ability->StartBackgroundRunning(wantAgentObj); + + HILOG_INFO("%{public}s end.", __func__); +} + +void BackgroundRunningCallbackCompletedCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("%{public}s called.", __func__); + AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); + napi_value callback = 0; + napi_value undefined = 0; + napi_value result[ARGS_TWO] = {0}; + napi_value callResult = 0; + napi_get_undefined(env, &undefined); + if (asyncCallbackInfo->errCode == NAPI_ERR_NO_ERROR) { + result[0] = WrapUndefinedToJS(env); + napi_create_int32(env, 0, &result[1]); + } else { + result[1] = WrapUndefinedToJS(env); + result[0] = GetCallbackErrorValue(env, asyncCallbackInfo->errCode); + } + + napi_get_reference_value(env, asyncCallbackInfo->cbInfo.callback, &callback); + napi_call_function(env, undefined, callback, ARGS_TWO, result, &callResult); + + if (asyncCallbackInfo->cbInfo.callback != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->cbInfo.callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + HILOG_INFO("%{public}s end.", __func__); +} + +void BackgroundRunningPromiseCompletedCB(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("%{public}s called.", __func__); + AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); + napi_value result = 0; + if (asyncCallbackInfo->errCode == NAPI_ERR_NO_ERROR) { + napi_create_int32(env, 0, &result); + napi_resolve_deferred(env, asyncCallbackInfo->deferred, result); + } else { + result = GetCallbackErrorValue(env, asyncCallbackInfo->errCode); + napi_reject_deferred(env, asyncCallbackInfo->deferred, result); + } + + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + HILOG_INFO("%{public}s, end.", __func__); + delete asyncCallbackInfo; +} + +napi_value StartBackgroundRunningAsync( + napi_env env, napi_value *args, const size_t argCallback, AsyncCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s asyncCallback.", __func__); + if (args == nullptr || asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &asyncCallbackInfo->cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + StartBackgroundRunningExecuteCB, + BackgroundRunningCallbackCompletedCB, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + HILOG_INFO("%{public}s asyncCallback end.", __func__); + return WrapVoidToJS(env); +} + +napi_value StartBackgroundRunningPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + StartBackgroundRunningExecuteCB, + BackgroundRunningPromiseCompletedCB, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + HILOG_INFO("%{public}s, end.", __func__); + return promise; +} + +napi_value StartBackgroundRunningWrap(napi_env &env, napi_callback_info &info, AsyncCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s called.", __func__); + size_t paramNums = 3; + const size_t minParamNums = 2; + const size_t maxParamNums = 3; + napi_value args[maxParamNums] = {nullptr}; + napi_value ret = 0; + + NAPI_CALL(env, napi_get_cb_info(env, info, ¶mNums, args, NULL, NULL)); + + if (paramNums < minParamNums || paramNums > maxParamNums) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + if (UnwrapParamForWantAgent(env, args[1], asyncCallbackInfo->wantAgent) == nullptr) { + asyncCallbackInfo->errCode = NAPI_ERR_PARAM_INVALID; + } + + if (paramNums == maxParamNums) { + ret = StartBackgroundRunningAsync(env, args, maxParamNums - 1, asyncCallbackInfo); + } else { + ret = StartBackgroundRunningPromise(env, asyncCallbackInfo); + } + + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +napi_value NAPI_StartBackgroundRunningCommon(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s asyncCallbackInfo == nullpter", __func__); + return WrapVoidToJS(env); + } + + asyncCallbackInfo->errCode = NAPI_ERR_NO_ERROR; + napi_value ret = StartBackgroundRunningWrap(env, info, asyncCallbackInfo); + if (ret == nullptr) { + HILOG_ERROR("%{public}s ret == nullpter", __func__); + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +void CancelBackgroundRunningExecuteCB(napi_env env, void *data) +{ + HILOG_INFO("NAPI_PACancelBackgroundRunning, worker pool thread execute."); + AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo->ability != nullptr) { + asyncCallbackInfo->ability->StopBackgroundRunning(); + } else { + HILOG_ERROR("NAPI_PACancelBackgroundRunning, ability == nullptr"); + } + HILOG_INFO("NAPI_PACancelBackgroundRunning, worker pool thread execute end."); +} + +napi_value CancelBackgroundRunningAsync( + napi_env env, napi_value *args, const size_t argCallback, AsyncCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s, asyncCallback.", __func__); + if (args == nullptr || asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + + napi_valuetype valuetype = napi_undefined; + napi_typeof(env, args[argCallback], &valuetype); + if (valuetype == napi_function) { + napi_create_reference(env, args[argCallback], 1, &asyncCallbackInfo->cbInfo.callback); + } + + napi_create_async_work( + env, + nullptr, + resourceName, + CancelBackgroundRunningExecuteCB, + BackgroundRunningCallbackCompletedCB, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + napi_value result = 0; + napi_get_null(env, &result); + HILOG_INFO("%{public}s, asyncCallback end", __func__); + return result; +} + +napi_value CancelBackgroundRunningPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s, promise.", __func__); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); + napi_deferred deferred; + napi_value promise = 0; + napi_create_promise(env, &deferred, &promise); + + asyncCallbackInfo->deferred = deferred; + + napi_create_async_work( + env, + nullptr, + resourceName, + CancelBackgroundRunningExecuteCB, + BackgroundRunningPromiseCompletedCB, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + HILOG_INFO("%{public}s, promise end", __func__); + return promise; +} + +napi_value CancelBackgroundRunningWrap(napi_env &env, napi_callback_info &info, AsyncCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s called.", __func__); + size_t argcAsync = 1; + const size_t argcPromise = 0; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, NULL, NULL)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + if (argcAsync > argcPromise) { + ret = CancelBackgroundRunningAsync(env, args, 0, asyncCallbackInfo); + } else { + ret = CancelBackgroundRunningPromise(env, asyncCallbackInfo); + } + + HILOG_INFO("%{public}s end.", __func__); + return ret; +} + +napi_value NAPI_CancelBackgroundRunningCommon(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("%{public}s asyncCallbackInfo == nullpter", __func__); + return WrapVoidToJS(env); + } + + asyncCallbackInfo->errCode = NAPI_ERR_NO_ERROR; + napi_value ret = CancelBackgroundRunningWrap(env, info, asyncCallbackInfo); + if (ret == nullptr) { + HILOG_ERROR("%{public}s ret == nullpter", __func__); + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s end.", __func__); + return ret; +} } // namespace AppExecFwk } // namespace OHOS 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 293bf2024146ca05df5f83b876d0294ebecf9d18..c15bb499a33e9a60b12ae6695c2c7f6007fe32f4 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 @@ -26,7 +26,7 @@ const std::int32_t STR_MAX_SIZE = 128; napi_value *GetGlobalClassContext(void); -napi_status SaveGlobalDataAbilityHelper(napi_env env, napi_value constructor); +napi_status SaveGlobalDataAbilityHelper(napi_env env, napi_value constructor); napi_value GetGlobalDataAbilityHelper(napi_env env); bool& GetDataAbilityHelperStatus(); @@ -227,6 +227,26 @@ napi_value NAPI_AcquireDataAbilityHelperCommon(napi_env env, napi_callback_info napi_value ConvertAbilityInfo(napi_env env, const AbilityInfo &abilityInfo); +/** + * @brief start background running. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_StartBackgroundRunningCommon(napi_env env, napi_callback_info info); + +/** + * @brief cancel background running. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_CancelBackgroundRunningCommon(napi_env env, napi_callback_info info); + bool CheckAbilityType(const CBBase *cbBase); struct ConnecttionKey { diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_configuration.cpp b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_configuration.cpp index 993e230ee528e7c1b59fc0e11ed5d2b621ab4b79..60ce79a71860553ec68476614996b8f2e2fb00a5 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_configuration.cpp +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_configuration.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,6 +14,8 @@ */ #include "napi_common_configuration.h" + +#include "configuration_convertor.h" #include "hilog_wrapper.h" #include "napi_common_util.h" @@ -41,21 +43,26 @@ napi_value WrapConfiguration(napi_env env, const AppExecFwk::Configuration &conf napi_value jsObject = nullptr; NAPI_CALL(env, napi_create_object(env, &jsObject)); - std::vector keys = OHOS::AppExecFwk::ConfigurationInner::SystemConfigurationKeyStore; - for (auto const &key : keys) { - std::string value = configuration.GetItem(key); - if (value.empty()) { - HILOG_INFO("value is empty"); - continue; - } + napi_value jsValue = nullptr; + jsValue = WrapStringToJS(env, configuration.GetItem(GlobalConfigurationKey::SYSTEM_LANGUAGE)); + SetPropertyValueByPropertyName(env, jsObject, "language", jsValue); + + jsValue = WrapInt32ToJS(env, ConvertColorMode(configuration.GetItem(GlobalConfigurationKey::SYSTEM_COLORMODE))); + SetPropertyValueByPropertyName(env, jsObject, "colorMode", jsValue); + + int32_t displayId = ConvertDisplayId(configuration.GetItem(ConfigurationInner::APPLICATION_DISPLAYID)); + + std::string direction = configuration.GetItem(displayId, ConfigurationInner::APPLICATION_DIRECTION); + jsValue = WrapInt32ToJS(env, ConvertDirection(direction)); + SetPropertyValueByPropertyName(env, jsObject, "direction", jsValue); + + std::string density = configuration.GetItem(displayId, ConfigurationInner::APPLICATION_DENSITYDPI); + jsValue = WrapInt32ToJS(env, ConvertDensity(density)); + SetPropertyValueByPropertyName(env, jsObject, "screenDensity", jsValue); + + jsValue = WrapInt32ToJS(env, displayId); + SetPropertyValueByPropertyName(env, jsObject, "displayId", jsValue); - std::size_t pos = key.rfind(DOT_STRING); - if (pos != std::string::npos) { - InnerWrapConfigurationString(env, jsObject, key.substr(pos+1), value); - } else { - InnerWrapConfigurationString(env, jsObject, key, value); - } - } return jsObject; } @@ -77,6 +84,15 @@ bool UnwrapConfiguration(napi_env env, napi_value param, Configuration &config) } } + int32_t colormode = -1; + if (UnwrapInt32ByPropertyName(env, param, "colorMode", colormode)) { + HILOG_DEBUG("The parsed colormode part %{public}d", colormode); + if (!config.AddItem(GlobalConfigurationKey::SYSTEM_COLORMODE, GetColorModeStr(colormode))) { + HILOG_ERROR("colorMode parsing failed"); + return false; + } + } + return true; } EXTERN_C_END diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_data.h b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_data.h index 859c51388c134ebf7d8a1a6a457cb672b36682da..a55b804321a89fcb448e1eea0c45fec00237814e 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_data.h +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_data.h @@ -62,6 +62,7 @@ struct CallbackInfo { napi_env env; napi_ref callback = 0; napi_deferred deferred; + int errCode = 0; }; struct CallAbilityParamData { diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.cpp b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.cpp index 9dff21cbd37d74ba198927c30e7e09cfda5094cb..4b3f081efc4da5019c7aa2384bdae3acf9120150 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.cpp +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.cpp @@ -686,6 +686,17 @@ bool InnerUnwrapWantParams(napi_env env, const std::string &key, napi_value para return false; } +bool BlackListFilter(const std::string &strProName) +{ + if (strProName == Want::PARAM_RESV_WINDOW_MODE) { + return true; + } + if (strProName == Want::PARAM_RESV_DISPLAY_ID) { + return true; + } + return false; +} + bool UnwrapWantParams(napi_env env, napi_value param, AAFwk::WantParams &wantParams) { HILOG_INFO("%{public}s called.", __func__); @@ -709,7 +720,8 @@ bool UnwrapWantParams(napi_env env, napi_value param, AAFwk::WantParams &wantPar std::string strProName = UnwrapStringFromJS(env, jsProName); /* skip reserved param */ - if (strProName == Want::PARAM_RESV_WINDOW_MODE) { + if (BlackListFilter(strProName)) { + HILOG_INFO("%{public}s is filtered.", strProName.c_str()); continue; } HILOG_INFO("%{public}s called. Property name=%{public}s.", __func__, strProName.c_str()); diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.h b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.h index 03130b2beb47fe2739057757c5430237aa9d4dcf..8cc4bcade3f0a802f4aec41a6732d159981af88a 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.h +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.h @@ -33,6 +33,7 @@ bool UnwrapElementName(napi_env env, napi_value param, ElementName &elementName) napi_value WrapWantParams(napi_env env, const AAFwk::WantParams &wantParams); bool UnwrapWantParams(napi_env env, napi_value param, AAFwk::WantParams &wantParams); +bool BlackListFilter(const std::string &strProName); napi_value WrapWant(napi_env env, const Want &want); bool UnwrapWant(napi_env env, napi_value param, Want &want); diff --git a/interfaces/kits/napi/aafwk/mission_manager/BUILD.gn b/interfaces/kits/napi/aafwk/mission_manager/BUILD.gn index 511654f5cdc1c0a6e1a1941e0d7924b0bda54833..54de57a91d3e910accecab15dd4c9cdc00737ae8 100644 --- a/interfaces/kits/napi/aafwk/mission_manager/BUILD.gn +++ b/interfaces/kits/napi/aafwk/mission_manager/BUILD.gn @@ -48,9 +48,9 @@ ohos_shared_library("missionmanager_napi") { ] external_deps = [ + "ability_base:want", "ability_runtime:ability_manager", "ability_runtime:runtime", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/interfaces/kits/napi/aafwk/mission_manager/distributed_mission_manager.cpp b/interfaces/kits/napi/aafwk/mission_manager/distributed_mission_manager.cpp index 4b63e20877fb2eee5d3645839bd28c60004959bb..b7de29b6154dac27a1377faef63573bec45007b8 100644 --- a/interfaces/kits/napi/aafwk/mission_manager/distributed_mission_manager.cpp +++ b/interfaces/kits/napi/aafwk/mission_manager/distributed_mission_manager.cpp @@ -55,6 +55,7 @@ bool SetStartSyncMissionsContext(const napi_env &env, const napi_value &value, HILOG_ERROR("%{public}s, fixConflict error type.", __func__); return false; } + napi_get_value_bool(env, fixConflictValue, &context->fixConflict); bool isTag = false; napi_has_named_property(env, value, "tag", &isTag); if (!isTag) { @@ -1394,7 +1395,7 @@ napi_value DistributedMissionManagerExport(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("stopSyncRemoteMissions", NAPI_StopSyncRemoteMissions), DECLARE_NAPI_FUNCTION("registerMissionListener", NAPI_RegisterMissionListener), DECLARE_NAPI_FUNCTION("unRegisterMissionListener", NAPI_UnRegisterMissionListener), - DECLARE_NAPI_FUNCTION("continueAbility", NAPI_ContinueAbility), + DECLARE_NAPI_FUNCTION("continueMission", NAPI_ContinueAbility), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(properties[0]), properties)); return exports; diff --git a/interfaces/kits/napi/aafwk/mission_manager/js_mission_info_utils.h b/interfaces/kits/napi/aafwk/mission_manager/js_mission_info_utils.h index 00c01039dd7e76e0d9fe8a797c2dad2883f97522..b35003211531e23e8aea4fecdade86c285bb38c9 100644 --- a/interfaces/kits/napi/aafwk/mission_manager/js_mission_info_utils.h +++ b/interfaces/kits/napi/aafwk/mission_manager/js_mission_info_utils.h @@ -13,6 +13,9 @@ * limitations under the License. */ +#ifndef OHOS_ABILITY_RUNTIME_JS_MISSION_INFO_UTILS_H +#define OHOS_ABILITY_RUNTIME_JS_MISSION_INFO_UTILS_H + #include "js_runtime_utils.h" #include "mission_info.h" #include "mission_snapshot.h" @@ -23,9 +26,6 @@ #include "ohos/aafwk/content/want_params_wrapper.h" #include "want.h" -#ifndef OHOS_ABILITY_RUNTIME_JS_MISSION_INFO_UTILS_H -#define OHOS_ABILITY_RUNTIME_JS_MISSION_INFO_UTILS_H - namespace OHOS { namespace AbilityRuntime { NativeValue* CreateJsMissionInfo(NativeEngine &engine, const AAFwk::MissionInfo &missionInfo); diff --git a/interfaces/kits/napi/aafwk/mission_manager/mission_manager.cpp b/interfaces/kits/napi/aafwk/mission_manager/mission_manager.cpp index 88a4ee42f45d7c082638c8fa4fee2d9cb058913a..c4a949a911da0ea0d5c43d0487dd1f640e128417 100644 --- a/interfaces/kits/napi/aafwk/mission_manager/mission_manager.cpp +++ b/interfaces/kits/napi/aafwk/mission_manager/mission_manager.cpp @@ -23,12 +23,15 @@ #include "js_mission_listener.h" #include "js_runtime_utils.h" #include "mission_snapshot.h" +#include "napi_common_start_options.h" #include "pixel_map_napi.h" +#include "start_options.h" #include namespace OHOS { namespace AbilityRuntime { +constexpr size_t ARGC_ONE = 1; using namespace OHOS::AppExecFwk; using AbilityManagerClient = AAFwk::AbilityManagerClient; namespace { @@ -156,7 +159,7 @@ private: return; } if (!missionListener) { - task.Resolve(engine, engine.CreateUndefined()); + task.Reject(engine, CreateJsError(engine, ERR_NOT_OK, "Not registered yet.")); return; } missionListener->RemoveJsListenerObject(missionListenerId); @@ -173,7 +176,7 @@ private: } }; - NativeValue* lastParam = (info.argc == 1) ? nullptr : info.argv[1]; + NativeValue* lastParam = (info.argc <= 1) ? nullptr : info.argv[1]; NativeValue* result = nullptr; AsyncTask::Schedule( engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); @@ -214,7 +217,7 @@ private: } }; - NativeValue* lastParam = (info.argc == 2) ? nullptr : info.argv[2]; + NativeValue* lastParam = (info.argc <= 2) ? nullptr : info.argv[2]; NativeValue* result = nullptr; AsyncTask::Schedule( engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); @@ -255,7 +258,7 @@ private: } }; - NativeValue* lastParam = (info.argc == 2) ? nullptr : info.argv[2]; + NativeValue* lastParam = (info.argc <= 2) ? nullptr : info.argv[2]; NativeValue* result = nullptr; AsyncTask::Schedule( engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); @@ -307,7 +310,7 @@ private: task.Reject(engine, CreateJsError(engine, ret, "Get mission snapshot failed.")); } }; - NativeValue* lastParam = (info.argc == ARG_COUNT_TWO) ? nullptr : info.argv[2]; + NativeValue* lastParam = (info.argc <= ARG_COUNT_TWO) ? nullptr : info.argv[2]; NativeValue* result = nullptr; AsyncTask::Schedule( engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); @@ -342,7 +345,7 @@ private: } }; - NativeValue* lastParam = (info.argc == 1) ? nullptr : info.argv[1]; + NativeValue* lastParam = (info.argc <= 1) ? nullptr : info.argv[1]; NativeValue* result = nullptr; AsyncTask::Schedule( engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); @@ -377,7 +380,7 @@ private: } }; - NativeValue* lastParam = (info.argc == 1) ? nullptr : info.argv[1]; + NativeValue* lastParam = (info.argc <= 1) ? nullptr : info.argv[1]; NativeValue* result = nullptr; AsyncTask::Schedule( engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); @@ -412,7 +415,7 @@ private: } }; - NativeValue* lastParam = (info.argc == 1) ? nullptr : info.argv[1]; + NativeValue* lastParam = (info.argc <= 1) ? nullptr : info.argv[1]; NativeValue* result = nullptr; AsyncTask::Schedule( engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); @@ -452,14 +455,23 @@ private: HILOG_ERROR("Parse missionId failed"); errCode = ERR_NOT_OK; } - + decltype(info.argc) unwrapArgc = 1; + + AAFwk::StartOptions startOptions; + if (info.argc > ARGC_ONE && info.argv[1]->TypeOf() == NATIVE_OBJECT) { + HILOG_INFO("OnMoveMissionToFront start options is used."); + AppExecFwk::UnwrapStartOptions(reinterpret_cast(&engine), + reinterpret_cast(info.argv[1]), startOptions); + unwrapArgc++; + } AsyncTask::CompleteCallback complete = - [missionId, errCode](NativeEngine &engine, AsyncTask &task, int32_t status) { + [missionId, errCode, startOptions, unwrapArgc](NativeEngine &engine, AsyncTask &task, int32_t status) { if (errCode != 0) { task.Reject(engine, CreateJsError(engine, errCode, "Invalidate params.")); return; } - auto ret = AbilityManagerClient::GetInstance()->MoveMissionToFront(missionId); + auto ret = (unwrapArgc == 1) ? AbilityManagerClient::GetInstance()->MoveMissionToFront(missionId) : + AbilityManagerClient::GetInstance()->MoveMissionToFront(missionId, startOptions); if (ret == 0) { task.Resolve(engine, engine.CreateUndefined()); } else { @@ -467,7 +479,7 @@ private: } }; - NativeValue* lastParam = (info.argc == 1) ? nullptr : info.argv[1]; + NativeValue* lastParam = (info.argc <= unwrapArgc) ? nullptr : info.argv[unwrapArgc]; NativeValue* result = nullptr; AsyncTask::Schedule( engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); @@ -505,7 +517,6 @@ NativeValue* JsMissionManagerInit(NativeEngine* engine, NativeValue* exportObj) BindNativeFunction(*engine, *object, "clearMission", JsMissionManager::ClearMission); BindNativeFunction(*engine, *object, "clearAllMissions", JsMissionManager::ClearAllMissions); BindNativeFunction(*engine, *object, "moveMissionToFront", JsMissionManager::MoveMissionToFront); - BindNativeFunction(*engine, *object, "moveMissionToFront", JsMissionManager::MoveMissionToFront); return engine->CreateUndefined(); } } // namespace AbilityRuntime diff --git a/interfaces/kits/napi/aafwk/mission_manager/mission_manager.h b/interfaces/kits/napi/aafwk/mission_manager/mission_manager.h index bf4af8eabcf25e2c712994d72ed211c387eae033..21e3c038a78382e6be8fa7b6762e4108d588dc02 100644 --- a/interfaces/kits/napi/aafwk/mission_manager/mission_manager.h +++ b/interfaces/kits/napi/aafwk/mission_manager/mission_manager.h @@ -13,12 +13,12 @@ * limitations under the License. */ -#include "mission_listener_stub.h" -#include "native_engine/native_engine.h" - #ifndef OHOS_ABILITY_RUNTIME_MISSION_MANAGER_H #define OHOS_ABILITY_RUNTIME_MISSION_MANAGER_H +#include "mission_listener_stub.h" +#include "native_engine/native_engine.h" + namespace OHOS { namespace AbilityRuntime { NativeValue* JsMissionManagerInit(NativeEngine* engine, NativeValue* exportObj); diff --git a/interfaces/kits/napi/aafwk/particleAbility/BUILD.gn b/interfaces/kits/napi/aafwk/particleAbility/BUILD.gn index e740320e542e53fa88349319d74f9c82bf7154fe..fd38c59346cdea59fe9e621e0d7c5776d1f0fb3e 100644 --- a/interfaces/kits/napi/aafwk/particleAbility/BUILD.gn +++ b/interfaces/kits/napi/aafwk/particleAbility/BUILD.gn @@ -53,10 +53,10 @@ ohos_shared_library("particleability") { ] external_deps = [ + "ability_base:want", "ability_runtime:ability_manager", "ability_runtime:app_manager", "ability_runtime:napi_base_context", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "eventhandler:libeventhandler", diff --git a/interfaces/kits/napi/aafwk/particleAbility/particle_ability.cpp b/interfaces/kits/napi/aafwk/particleAbility/particle_ability.cpp index c5dd1ae82d3aa0263fe4eeb7e83e6bbdabecf757..aa4f8065c8df8dfb983ff5380b7d93b94fa17f7b 100644 --- a/interfaces/kits/napi/aafwk/particleAbility/particle_ability.cpp +++ b/interfaces/kits/napi/aafwk/particleAbility/particle_ability.cpp @@ -182,6 +182,34 @@ napi_value NAPI_PAAcquireDataAbilityHelper(napi_env env, napi_callback_info info return NAPI_AcquireDataAbilityHelperCommon(env, info, AbilityType::UNKNOWN); } +/** + * @brief ParticleAbility NAPI method : startBackgroundRunning. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_PAStartBackgroundRunning(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + return NAPI_StartBackgroundRunningCommon(env, info); +} + +/** + * @brief ParticleAbility NAPI method : cancelBackgroundRunning. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_PACancelBackgroundRunning(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + return NAPI_CancelBackgroundRunningCommon(env, info); +} + /** * @brief ParticleAbility NAPI module registration. * @@ -205,6 +233,8 @@ napi_value ParticleAbilityInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("connectAbility", NAPI_PAConnectAbility), DECLARE_NAPI_FUNCTION("disconnectAbility", NAPI_PADisConnectAbility), DECLARE_NAPI_FUNCTION("acquireDataAbilityHelper", NAPI_PAAcquireDataAbilityHelper), + DECLARE_NAPI_FUNCTION("startBackgroundRunning", NAPI_PAStartBackgroundRunning), + DECLARE_NAPI_FUNCTION("cancelBackgroundRunning", NAPI_PACancelBackgroundRunning), }; napi_define_properties(env, exports, sizeof(properties) / sizeof(properties[0]), properties); diff --git a/interfaces/kits/napi/aafwk/service_ext_ability/BUILD.gn b/interfaces/kits/napi/aafwk/service_ext_ability/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e852cdf20141e8b1091bcb8d5a059a7a3cd17bfb --- /dev/null +++ b/interfaces/kits/napi/aafwk/service_ext_ability/BUILD.gn @@ -0,0 +1,50 @@ +# 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("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") + +ts2abc_gen_abc("gen_service_ext_ability_abc") { + src_js = rebase_path("service_ext_ability.js") + dst_file = rebase_path(target_out_dir + "/service_ext_ability.abc") + in_puts = [ "service_ext_ability.js" ] + out_puts = [ target_out_dir + "/service_ext_ability.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("service_ext_ability_js") { + input = "service_ext_ability.js" + output = target_out_dir + "/service_ext_ability.o" +} + +gen_js_obj("service_ext_ability_abc") { + input = get_label_info(":gen_service_ext_ability_abc", "target_out_dir") + + "/service_ext_ability.abc" + output = target_out_dir + "/service_ext_ability_abc.o" + dep = ":gen_service_ext_ability_abc" +} + +ohos_shared_library("serviceextability_napi") { + sources = [ "service_ext_ability_module.cpp" ] + + deps = [ + ":service_ext_ability_abc", + ":service_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/js/bundle/customizeData.d.ts b/interfaces/kits/napi/aafwk/service_ext_ability/service_ext_ability.js similarity index 53% rename from interfaces/kits/js/bundle/customizeData.d.ts rename to interfaces/kits/napi/aafwk/service_ext_ability/service_ext_ability.js index 17393229f1f5d422e1f3414d622b81f5ed62f950..01d0ea33c52f2579e99d724fc0f1ed6480071527 100644 --- a/interfaces/kits/js/bundle/customizeData.d.ts +++ b/interfaces/kits/napi/aafwk/service_ext_ability/service_ext_ability.js @@ -13,25 +13,26 @@ * limitations under the License. */ - /** - * @name Indicates the custom metadata - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @permission NA - * @devices phone, tablet, tv, wearable, car - */ -export interface CustomizeData { - /** - * @default Indicates the custom metadata name - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - name: string; +class ServiceExtAbility { + onCreate(want) { + console.log('onCreate, want:' + want.abilityName); + } + + onRequest(want, startId) { + console.log('onRequest, want:' + want.abilityName + ', startId:' + startId); + } + + onConnect(want) { + console.log('onConnect, want:' + want.abilityName); + } + + onDisconnect(want) { + console.log('onDisconnect'); + } + + onDestroy() { + console.log('onDestroy'); + } +} - /** - * @default Indicates the custom metadata value - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - value: string; -} \ No newline at end of file +export default ServiceExtAbility \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/service_ext_ability/service_ext_ability_module.cpp b/interfaces/kits/napi/aafwk/service_ext_ability/service_ext_ability_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..03b25ba25f1f540edc7a741ec73ef5e60d20c901 --- /dev/null +++ b/interfaces/kits/napi/aafwk/service_ext_ability/service_ext_ability_module.cpp @@ -0,0 +1,57 @@ +/* + * 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 "native_engine/native_engine.h" + +extern const char _binary_service_ext_ability_js_start[]; +extern const char _binary_service_ext_ability_js_end[]; +extern const char _binary_service_ext_ability_abc_start[]; +extern const char _binary_service_ext_ability_abc_end[]; + +extern "C" __attribute__((constructor)) +void NAPI_application_ServiceExtAbility_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.ServiceExtAbility", + .fileName = "application/libserviceextability_napi.so/service_ext_ability.js", + }; + + moduleManager->Register(&newModuleInfo); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_application_ServiceExtAbility_GetJSCode(const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_service_ext_ability_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_service_ext_ability_js_end - _binary_service_ext_ability_js_start; + } +} + +// service_extension JS register +extern "C" __attribute__((visibility("default"))) +void NAPI_application_ServiceExtAbility_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_service_ext_ability_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_service_ext_ability_abc_end - _binary_service_ext_ability_abc_start; + } +} \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/service_ext_ability_context/BUILD.gn b/interfaces/kits/napi/aafwk/service_ext_ability_context/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e67fb3dd80b29a59cb20649a447f3757ae2c1305 --- /dev/null +++ b/interfaces/kits/napi/aafwk/service_ext_ability_context/BUILD.gn @@ -0,0 +1,50 @@ +# 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("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") + +ts2abc_gen_abc("gen_service_ext_ability_context_abc") { + src_js = rebase_path("service_ext_ability_context.js") + dst_file = rebase_path(target_out_dir + "/service_ext_ability_context.abc") + in_puts = [ "service_ext_ability_context.js" ] + out_puts = [ target_out_dir + "/service_ext_ability_context.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("service_ext_ability_context_js") { + input = "service_ext_ability_context.js" + output = target_out_dir + "/service_ext_ability_context.o" +} + +gen_js_obj("service_ext_ability_context_abc") { + input = get_label_info(":gen_service_ext_ability_context_abc", + "target_out_dir") + "/service_ext_ability_context.abc" + output = target_out_dir + "/service_ext_ability_context_abc.o" + dep = ":gen_service_ext_ability_context_abc" +} + +ohos_shared_library("serviceextabilitycontext_napi") { + sources = [ "service_ext_ability_context_module.cpp" ] + + deps = [ + ":service_ext_ability_context_abc", + ":service_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/js/bundle/elementName.d.ts b/interfaces/kits/napi/aafwk/service_ext_ability_context/service_ext_ability_context.js similarity index 30% rename from interfaces/kits/js/bundle/elementName.d.ts rename to interfaces/kits/napi/aafwk/service_ext_ability_context/service_ext_ability_context.js index 68fe8ddda30ce97a540b5385085f530008f6cba2..b56e8128e240d860305c938f97f72f94fa145c18 100644 --- a/interfaces/kits/js/bundle/elementName.d.ts +++ b/interfaces/kits/napi/aafwk/service_ext_ability_context/service_ext_ability_context.js @@ -13,59 +13,43 @@ * limitations under the License. */ -/** - * Contains basic Ability information, which uniquely identifies an ability. - * You can use this class to obtain values of the fields set in an element, - * such as the device ID, bundle name, and ability name. - * @name Contains basic Ability information, which uniquely identifies an ability - * @since 7 - * @sysCap SystemCapability.Appexecfwk - * @devices phone, tablet, tv, wearable, car - * @permission N/A - */ -export interface ElementName { - /** - * device id - * @default - - * @devices phone, tablet, tv, wearable, car - * @since 7 - * @sysCap SystemCapability.Appexecfwk - */ - deviceId?: string; +var ExtAbilityContext = requireNapi("application.ExtAbilityContext") + +class ServiceExtAbilityContext extends ExtAbilityContext { + constructor(obj) { + super(obj); + this.extensionAbilityInfo = obj.extensionAbilityInfo + } + + startAbility(want, options, callback) { + console.log("startAbility"); + return this.__context_impl__.startAbility(want, options, callback); + } - /** - * bundle name - * @default - - * @devices phone, tablet, tv, wearable, car - * @since 7 - * @sysCap SystemCapability.Appexecfwk - */ - bundleName: string; + connectAbility(want, options) { + console.log("connectAbility"); + return this.__context_impl__.connectAbility(want, options); + } - /** - * ability name - * @default ability class name. - * @devices phone, tablet, tv, wearable, car - * @since 7 - * @sysCap SystemCapability.Appexecfwk - */ - abilityName: string; + startAbilityWithAccount(want, accountId, options, callback) { + console.log("startAbilityWithAccount"); + return this.__context_impl__.startAbilityWithAccount(want, accountId, options, callback); + } - /** - * uri - * @default - - * @devices phone, tablet, tv, wearable, car - * @since 7 - * @sysCap SystemCapability.Appexecfwk - */ - uri?: string; + connectAbilityWithAccount(want, accountId, options) { + console.log("connectAbilityWithAccount"); + return this.__context_impl__.connectAbilityWithAccount(want, accountId, options); + } - /** - * shortName - * @default - - * @devices phone, tablet, tv, wearable, car - * @since 7 - * @sysCap SystemCapability.Appexecfwk - */ - shortName?: string; + disconnectAbility(connection, callback) { + console.log("disconnectAbility"); + return this.__context_impl__.disconnectAbility(connection, callback); + } + + terminateSelf(callback) { + console.log("terminateSelf"); + return this.__context_impl__.terminateSelf(callback); + } } + +export default ServiceExtAbilityContext \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/service_ext_ability_context/service_ext_ability_context_module.cpp b/interfaces/kits/napi/aafwk/service_ext_ability_context/service_ext_ability_context_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..79d6e13f826126b606788abeb642b703a195e31d --- /dev/null +++ b/interfaces/kits/napi/aafwk/service_ext_ability_context/service_ext_ability_context_module.cpp @@ -0,0 +1,57 @@ +/* + * 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 "native_engine/native_engine.h" + +extern const char _binary_service_ext_ability_context_js_start[]; +extern const char _binary_service_ext_ability_context_js_end[]; +extern const char _binary_service_ext_ability_context_abc_start[]; +extern const char _binary_service_ext_ability_context_abc_end[]; + +extern "C" __attribute__((constructor)) +void NAPI_application_ServiceExtAbilityContext_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.ServiceExtAbilityContext", + .fileName = "application/libserviceextabilitycontext_napi.so/service_ext_ability_context.js", + }; + + moduleManager->Register(&newModuleInfo); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_application_ServiceExtAbilityContext_GetJSCode(const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_service_ext_ability_context_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_service_ext_ability_context_js_end - _binary_service_ext_ability_context_js_start; + } +} + +// ability_context JS register +extern "C" __attribute__((visibility("default"))) +void NAPI_application_ServiceExtAbilityContext_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_service_ext_ability_context_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_service_ext_ability_context_abc_end - _binary_service_ext_ability_context_abc_start; + } +} diff --git a/interfaces/kits/napi/aafwk/uri_permission/BUILD.gn b/interfaces/kits/napi/aafwk/uri_permission/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e53c2216f32cf0b1552c1833d93f35c435c5f4e2 --- /dev/null +++ b/interfaces/kits/napi/aafwk/uri_permission/BUILD.gn @@ -0,0 +1,46 @@ +# 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") +ohos_shared_library("uripermmgr_napi") { + sources = [ + "js_uri_perm_mgr.cpp", + "native_module.cpp", + ] + + configs = [ "//foundation/aafwk/standard/services/common:common_config" ] + + include_dirs = [ + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common", + ] + + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/uri_permission:uri_permission_mgr", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", + ] + + external_deps = [ + "ability_runtime:ability_manager", + "ability_runtime:runtime", + "bundle_framework:appexecfwk_base", + "dmsfwk_standard:zuri", + "hiviewdfx_hilog_native:libhilog", + ] + + relative_install_dir = "module/application" + + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/kits/napi/aafwk/uri_permission/js_uri_perm_mgr.cpp b/interfaces/kits/napi/aafwk/uri_permission/js_uri_perm_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e81aa417e6c688fef05b143650bc6924f971c88d --- /dev/null +++ b/interfaces/kits/napi/aafwk/uri_permission/js_uri_perm_mgr.cpp @@ -0,0 +1,125 @@ +/* + * 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_uri_perm_mgr.h" + +#include "hilog_wrapper.h" +#include "js_runtime_utils.h" +#include "napi_common_util.h" +#include "uri.h" +#include "uri_permission_manager_client.h" + +namespace OHOS { +namespace AbilityRuntime { +class JsUriPermMgr { +public: + JsUriPermMgr() = default; + ~JsUriPermMgr() = default; + + static void Finalizer(NativeEngine* engine, void* data, void* hint) + { + HILOG_INFO("JsUriPermMgr::Finalizer is called"); + std::unique_ptr(static_cast(data)); + } + + static NativeValue* VerifyUriPermission(NativeEngine* engine, NativeCallbackInfo* info) + { + JsUriPermMgr* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnVerifyUriPermission(*engine, *info) : nullptr; + } + +private: + NativeValue* OnVerifyUriPermission(NativeEngine& engine, NativeCallbackInfo& info) + { + HILOG_DEBUG("OnVerifyUriPermission is called"); + std::vector> args; + for (size_t i = 0; i < info.argc; ++i) { + args.emplace_back(engine.CreateReference(info.argv[i], 1)); + } + + constexpr int32_t argCountThree = 3; + AsyncTask::CompleteCallback complete = + [args, argCountThree](NativeEngine& engine, AsyncTask& task, int32_t status) { + constexpr int32_t argCountFour = 4; + if (args.size() != argCountThree && args.size() != argCountFour) { + HILOG_ERROR("Wrong number of parameters."); + task.Reject(engine, CreateJsError(engine, -1, "Wrong number of parameters.")); + return; + } + + std::string uriStr; + if (!OHOS::AppExecFwk::UnwrapStringFromJS2(reinterpret_cast(&engine), + reinterpret_cast(args[0].get()), uriStr)) { + HILOG_ERROR("%{public}s called, the first parameter is invalid.", __func__); + task.Reject(engine, CreateJsError(engine, -1, "uri conversion failed.")); + return; + } + + int flag = 0; + if (!OHOS::AppExecFwk::UnwrapInt32FromJS2(reinterpret_cast(&engine), + reinterpret_cast(args[1].get()), flag)) { + HILOG_ERROR("%{public}s called, the second parameter is invalid.", __func__); + task.Reject(engine, CreateJsError(engine, -1, "flag conversion failed.")); + return; + } + + int accessTokenId = 0; + constexpr int32_t index = 2; + if (!OHOS::AppExecFwk::UnwrapInt32FromJS2(reinterpret_cast(&engine), + reinterpret_cast(args[index].get()), accessTokenId)) { + HILOG_ERROR("%{public}s called, the third parameter is invalid.", __func__); + task.Reject(engine, CreateJsError(engine, -1, "accessTokenId conversion failed.")); + return; + } + + Uri uri(uriStr); + if (AAFwk::UriPermissionManagerClient::GetInstance()->VerifyUriPermission(uri, flag, accessTokenId)) { + task.Resolve(engine, 0); + } else { + task.Reject(engine, CreateJsError(engine, -1, "The app doesn't have the uri permission!")); + } + }; + + NativeValue* lastParam = (info.argc == argCountThree) ? nullptr : info.argv[argCountThree]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + HILOG_DEBUG("OnVerifyUriPermission is called end"); + return result; + } +}; + +NativeValue* CreateJsUriPermMgr(NativeEngine* engine, NativeValue* exportObj) +{ + HILOG_INFO("CreateJsUriPermMgr is called"); + if (engine == nullptr || exportObj == nullptr) { + HILOG_INFO("Invalid input parameters"); + return nullptr; + } + + NativeObject* object = ConvertNativeValueTo(exportObj); + if (object == nullptr) { + HILOG_INFO("object is nullptr"); + return nullptr; + } + + std::unique_ptr jsUriPermMgr = std::make_unique(); + object->SetNativePointer(jsUriPermMgr.release(), JsUriPermMgr::Finalizer, nullptr); + + BindNativeFunction(*engine, *object, "verifyUriPermission", JsUriPermMgr::VerifyUriPermission); + return engine->CreateUndefined(); +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/uri_permission/js_uri_perm_mgr.h b/interfaces/kits/napi/aafwk/uri_permission/js_uri_perm_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..b009e137d7dd8f90bf6d31d46f2dfa7727a41f75 --- /dev/null +++ b/interfaces/kits/napi/aafwk/uri_permission/js_uri_perm_mgr.h @@ -0,0 +1,26 @@ +/* + * 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_URI_PERM_MGR_H +#define ABILITY_RUNTIME_JS_URI_PERM_MGR_H + +#include "native_engine/native_engine.h" + +namespace OHOS { +namespace AbilityRuntime { +NativeValue* CreateJsUriPermMgr(NativeEngine* engine, NativeValue* exportObj); +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_JS_URI_PERM_MGR_H \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/uri_permission/native_module.cpp b/interfaces/kits/napi/aafwk/uri_permission/native_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ab5374b4a405d026c016373f3fa42bc988eeb962 --- /dev/null +++ b/interfaces/kits/napi/aafwk/uri_permission/native_module.cpp @@ -0,0 +1,30 @@ +/* + * 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_uri_perm_mgr.h" +#include "native_engine/native_engine.h" + +extern "C" __attribute__((constructor)) +void NAPI_application_uripermmgr_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.missionManager", + .fileName = "application/liburipermmgr_napi.so/uripermmgr.js", + .registerCallback = OHOS::AbilityRuntime::CreateJsUriPermMgr, + }; + + moduleManager->Register(&newModuleInfo); +} \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/wantConstant/BUILD.gn b/interfaces/kits/napi/aafwk/wantConstant/BUILD.gn index 91b36056afa2a2e9a19851a5384136942aab6009..5662cc289a61525c763f662ea41aa216b67e67ee 100644 --- a/interfaces/kits/napi/aafwk/wantConstant/BUILD.gn +++ b/interfaces/kits/napi/aafwk/wantConstant/BUILD.gn @@ -37,9 +37,9 @@ ohos_shared_library("wantconstant") { ] external_deps = [ + "ability_base:want", "ability_runtime:ability_manager", "ability_runtime:app_manager", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "eventhandler:libeventhandler", diff --git a/interfaces/kits/napi/aafwk/wantagent/BUILD.gn b/interfaces/kits/napi/aafwk/wantagent/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..97b4210658a628b7b4e6c056df0bced0aa285a96 --- /dev/null +++ b/interfaces/kits/napi/aafwk/wantagent/BUILD.gn @@ -0,0 +1,59 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +ohos_shared_library("wantagent") { + include_dirs = [ + "//third_party/node/src", + "//foundation/aafwk/standard/services/common/include", + "//utils/system/safwk/native/include", + "//third_party/libuv/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common", + "//foundation/aafwk/standard/services/common/include", + "./", + ] + + sources = [ + "napi_want_agent.cpp", + "native_module.cpp", + ] + + deps = [ + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_base:want", + "ability_runtime:abilitykit_native", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + + relative_install_dir = "module" + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/interfaces/kits/napi/aafwk/wantagent/napi_want_agent.cpp b/interfaces/kits/napi/aafwk/wantagent/napi_want_agent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b9b3ebdc108ffb178836753a61d76d5686f7db95 --- /dev/null +++ b/interfaces/kits/napi/aafwk/wantagent/napi_want_agent.cpp @@ -0,0 +1,1340 @@ +/* + * 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 "napi_want_agent.h" + +#include +#include +#include +#include + +#include "hilog_wrapper.h" +#include "napi_common.h" +#include "want_agent_helper.h" + +namespace OHOS { +#define NAPI_ASSERT_RETURN_NULL(env, assertion, message) \ +do { \ + if (!(assertion)) { \ + HILOG_INFO(message); \ + return nullptr; \ + } \ +} while (0) +constexpr int32_t BUSINESS_ERROR_CODE_OK = 0; + +TriggerCompleteCallBack::TriggerCompleteCallBack() +{} + +TriggerCompleteCallBack::~TriggerCompleteCallBack() +{} + +void TriggerCompleteCallBack::SetCallbackInfo(const napi_env &env, const napi_ref &ref) +{ + triggerCompleteInfo_.env = env; + triggerCompleteInfo_.ref = ref; +} + +void TriggerCompleteCallBack::SetWantAgentInstance(const std::shared_ptr &wantAgent) +{ + triggerCompleteInfo_.wantAgent = wantAgent; +} + +auto OnSendFinishedUvAfterWorkCallback = [](uv_work_t *work, int status) { + HILOG_INFO("TriggerCompleteCallBack::OnSendFinishedUvAfterWorkCallback:status = %{public}d", status); + + TriggerReceiveDataWorker *dataWorkerData = static_cast(work->data); + if (dataWorkerData == nullptr) { + HILOG_INFO("TriggerReceiveDataWorker instance(uv_work_t) is nullptr"); + delete work; + return; + } + napi_value result[NUMBER_OF_PARAMETERS_TWO] = {0}; + + result[0] = GetCallbackErrorResult(dataWorkerData->env, BUSINESS_ERROR_CODE_OK); + napi_create_object(dataWorkerData->env, &result[1]); + // wrap wantAgent + napi_value wantAgentClass = nullptr; + auto constructorcb = [](napi_env env, napi_callback_info info) -> napi_value { + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + return thisVar; + }; + napi_define_class( + dataWorkerData->env, "WantAgentClass", NAPI_AUTO_LENGTH, constructorcb, nullptr, 0, nullptr, &wantAgentClass); + napi_value jsWantAgent = nullptr; + napi_new_instance(dataWorkerData->env, wantAgentClass, 0, nullptr, &jsWantAgent); + auto finalizecb = [](napi_env env, void *data, void *hint) {}; + napi_wrap(dataWorkerData->env, jsWantAgent, (void *)dataWorkerData->wantAgent.get(), finalizecb, nullptr, nullptr); + napi_set_named_property(dataWorkerData->env, result[1], "wantAgent", jsWantAgent); + // wrap want + napi_value jsWant = WrapWant(dataWorkerData->env, dataWorkerData->want); + napi_set_named_property(dataWorkerData->env, result[1], "want", jsWant); + // wrap finalCode + napi_value jsFinalCode = nullptr; + napi_create_int32(dataWorkerData->env, dataWorkerData->resultCode, &jsFinalCode); + napi_set_named_property(dataWorkerData->env, result[1], "finalCode", jsFinalCode); + // wrap finalData + napi_value jsFinalData = nullptr; + napi_create_string_utf8(dataWorkerData->env, dataWorkerData->resultData.c_str(), NAPI_AUTO_LENGTH, &jsFinalData); + napi_set_named_property(dataWorkerData->env, result[1], "finalData", jsFinalData); + // wrap extraInfo + napi_value jsExtraInfo = WrapWantParams(dataWorkerData->env, dataWorkerData->resultExtras); + napi_set_named_property(dataWorkerData->env, result[1], "extraInfo", jsExtraInfo); + + napi_value callResult = nullptr; + napi_value undefined = nullptr; + napi_value callback = nullptr; + napi_get_undefined(dataWorkerData->env, &undefined); + napi_get_reference_value(dataWorkerData->env, dataWorkerData->ref, &callback); + napi_call_function(dataWorkerData->env, undefined, callback, NUMBER_OF_PARAMETERS_TWO, &result[0], &callResult); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; +}; + +void TriggerCompleteCallBack::OnSendFinished( + const AAFwk::Want &want, int resultCode, const std::string &resultData, const AAFwk::WantParams &resultExtras) +{ + HILOG_INFO("TriggerCompleteCallBack::OnSendFinished start"); + if (triggerCompleteInfo_.ref == nullptr) { + HILOG_INFO("triggerCompleteInfo_ CallBack is nullptr"); + return; + } + uv_loop_s *loop = nullptr; +#if NAPI_VERSION >= NUMBER_OF_PARAMETERS_TWO + napi_get_uv_event_loop(triggerCompleteInfo_.env, &loop); +#endif // NAPI_VERSION >= 2 + if (loop == nullptr) { + HILOG_INFO("loop instance is nullptr"); + return; + } + + uv_work_t *work = new (std::nothrow) uv_work_t; + if (work == nullptr) { + HILOG_INFO("uv_work_t instance is nullptr"); + return; + } + TriggerReceiveDataWorker *dataWorker = new (std::nothrow) TriggerReceiveDataWorker(); + if (dataWorker == nullptr) { + HILOG_INFO("TriggerReceiveDataWorker instance is nullptr"); + delete work; + work = nullptr; + return; + } + dataWorker->want = want; + dataWorker->resultCode = resultCode; + dataWorker->resultData = resultData; + dataWorker->resultExtras = resultExtras; + dataWorker->env = triggerCompleteInfo_.env; + dataWorker->ref = triggerCompleteInfo_.ref; + dataWorker->wantAgent = triggerCompleteInfo_.wantAgent; + work->data = (void *)dataWorker; + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, OnSendFinishedUvAfterWorkCallback); + if (ret != 0) { + delete dataWorker; + dataWorker = nullptr; + delete work; + work = nullptr; + } + + HILOG_INFO("TriggerCompleteCallBack::OnSendFinished end"); +} +napi_value WantAgentInit(napi_env env, napi_value exports) +{ + HILOG_INFO("napi_moudule Init start..."); + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("getBundleName", NAPI_GetBundleName), + DECLARE_NAPI_FUNCTION("getUid", NAPI_GetUid), + DECLARE_NAPI_FUNCTION("cancel", NAPI_Cancel), + DECLARE_NAPI_FUNCTION("trigger", NAPI_Trigger), + DECLARE_NAPI_FUNCTION("equal", NAPI_Equal), + DECLARE_NAPI_FUNCTION("getWant", NAPI_GetWant), + DECLARE_NAPI_FUNCTION("getWantAgent", NAPI_GetWantAgent), + }; + + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + HILOG_INFO("napi_moudule Init end..."); + return exports; +} + +void SetNamedPropertyByInteger(napi_env env, napi_value dstObj, int32_t objName, const std::string &propName) +{ + napi_value prop = nullptr; + if (napi_create_int32(env, objName, &prop) == napi_ok) { + napi_set_named_property(env, dstObj, propName.c_str(), prop); + } +} + +napi_value WantAgentFlagsInit(napi_env env, napi_value exports) +{ + HILOG_INFO("%{public}s, called", __func__); + + napi_value obj = nullptr; + napi_create_object(env, &obj); + + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_ZERO, "ONE_TIME_FLAG"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_ONE, "NO_BUILD_FLAG"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_TWO, "CANCEL_PRESENT_FLAG"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_THREE, "UPDATE_PRESENT_FLAG"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_FOUR, "CONSTANT_FLAG"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_FIVE, "REPLACE_ELEMENT"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_SIX, "REPLACE_ACTION"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_SEVEN, "REPLACE_URI"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_EIGHT, "REPLACE_ENTITIES"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_NINE, "REPLACE_BUNDLE"); + + napi_property_descriptor exportFuncs[] = { + DECLARE_NAPI_PROPERTY("WantAgentFlags", obj), + }; + + napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); + return exports; +} + +napi_value WantAgentOperationTypeInit(napi_env env, napi_value exports) +{ + HILOG_INFO("%{public}s, called", __func__); + + napi_value obj = nullptr; + napi_create_object(env, &obj); + + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_ZERO, "UNKNOWN_TYPE"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_ONE, "START_ABILITY"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_TWO, "START_ABILITIES"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_THREE, "START_SERVICE"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_FOUR, "SEND_COMMON_EVENT"); + SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_FIVE, "START_FOREGROUND_SERVICE"); + + napi_property_descriptor exportFuncs[] = { + DECLARE_NAPI_PROPERTY("OperationType", obj), + }; + + napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); + return exports; +} + +auto NAPI_GetBundleNameExecuteCallBack = [](napi_env env, void *data) { + HILOG_INFO("GetBundleName called(CallBack Mode)..."); + AsyncGetBundleNameCallbackInfo *asyncCallbackInfo = static_cast(data); + asyncCallbackInfo->bundleName = WantAgentHelper::GetBundleName(asyncCallbackInfo->wantAgent); +}; + +auto NAPI_GetBundleNameCompleteCallBack = [](napi_env env, napi_status status, void *data) { + HILOG_INFO("GetBundleName compeleted(CallBack Mode)..."); + AsyncGetBundleNameCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("asyncCallbackInfo is nullptr."); + return; + } + napi_value result[NUMBER_OF_PARAMETERS_TWO] = {0}; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value callResult = nullptr; + + result[0] = GetCallbackErrorResult(asyncCallbackInfo->env, BUSINESS_ERROR_CODE_OK); + napi_create_string_utf8(env, asyncCallbackInfo->bundleName.c_str(), NAPI_AUTO_LENGTH, &result[1]); + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); + napi_call_function(env, undefined, callback, NUMBER_OF_PARAMETERS_TWO, &result[0], &callResult); + + if (asyncCallbackInfo->callback[0] != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->callback[0]); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; +}; + +auto NAPI_GetBundleNamePromiseCompleteCallBack = [](napi_env env, napi_status status, void *data) { + HILOG_INFO("GetBundleName compeleted(Promise Mode)..."); + AsyncGetBundleNameCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("asyncCallbackInfo is nullptr."); + return; + } + napi_value result = nullptr; + napi_create_string_utf8(env, asyncCallbackInfo->bundleName.c_str(), NAPI_AUTO_LENGTH, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; +}; + +napi_value NAPI_GetBundleNameWrap( + napi_env env, napi_callback_info info, bool callBackMode, AsyncGetBundleNameCallbackInfo &asyncCallbackInfo) +{ + HILOG_INFO("NAPI_GetBundleNameWrap called..."); + if (callBackMode) { + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "NAPI_GetBundleNameCallBack", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work(env, + nullptr, + resourceName, + NAPI_GetBundleNameExecuteCallBack, + NAPI_GetBundleNameCompleteCallBack, + (void *)&asyncCallbackInfo, + &asyncCallbackInfo.asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo.asyncWork)); + // create reutrn + napi_value ret = nullptr; + NAPI_CALL(env, napi_create_int32(env, 0, &ret)); + return ret; + } else { + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "NAPI_GetBundleNamePromise", NAPI_AUTO_LENGTH, &resourceName); + + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo.deferred = deferred; + + napi_create_async_work(env, + nullptr, + resourceName, + NAPI_GetBundleNameExecuteCallBack, + NAPI_GetBundleNamePromiseCompleteCallBack, + (void *)&asyncCallbackInfo, + &asyncCallbackInfo.asyncWork); + napi_queue_async_work(env, asyncCallbackInfo.asyncWork); + return promise; + } +} + +napi_value NAPI_GetBundleName(napi_env env, napi_callback_info info) +{ + size_t argc = NUMBER_OF_PARAMETERS_TWO; + napi_value argv[NUMBER_OF_PARAMETERS_TWO] = {}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + HILOG_INFO("argc = [%{public}zu]", argc); + + napi_valuetype wantAgentType = napi_valuetype::napi_null; + napi_typeof(env, argv[0], &wantAgentType); + NAPI_ASSERT_RETURN_NULL(env, wantAgentType == napi_object, "Wrong argument type. Object expected."); + + WantAgent *pWantAgent = nullptr; + napi_unwrap(env, argv[0], (void **)&(pWantAgent)); + if (pWantAgent == nullptr) { + HILOG_INFO("WantAgent napi_unwrap error"); + return NapiGetNull(env); + } + + bool callBackMode = false; + if (argc >= NUMBER_OF_PARAMETERS_TWO) { + napi_valuetype valuetype = napi_valuetype::napi_null; + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT_RETURN_NULL(env, valuetype == napi_function, "Wrong argument type. Function expected."); + callBackMode = true; + } + AsyncGetBundleNameCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncGetBundleNameCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr, + }; + if (asyncCallbackInfo == nullptr) { + return NapiGetNull(env); + } + asyncCallbackInfo->wantAgent = std::make_shared(*pWantAgent); + + if (callBackMode) { + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback[0]); + } + napi_value ret = NAPI_GetBundleNameWrap(env, info, callBackMode, *asyncCallbackInfo); + if (ret == nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + return ((callBackMode) ? (NapiGetNull(env)) : (ret)); +} + +auto NAPI_GetUidWrapExecuteCallBack = [](napi_env env, void *data) { + HILOG_INFO("GetUid called(CallBack Mode)..."); + AsyncGetUidCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("asyncCallbackInfo is nullptr."); + return; + } + asyncCallbackInfo->uid = WantAgentHelper::GetUid(asyncCallbackInfo->wantAgent); +}; + +auto NAPI_GetUidWrapCompleteCallBack = [](napi_env env, napi_status status, void *data) { + HILOG_INFO("GetUid compeleted(CallBack Mode)..."); + AsyncGetUidCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("asyncCallbackInfo is nullptr."); + return; + } + napi_value result[NUMBER_OF_PARAMETERS_TWO] = {0}; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value callResult = nullptr; + + result[0] = GetCallbackErrorResult(asyncCallbackInfo->env, BUSINESS_ERROR_CODE_OK); + napi_create_int32(env, asyncCallbackInfo->uid, &result[1]); + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); + napi_call_function(env, undefined, callback, NUMBER_OF_PARAMETERS_TWO, &result[0], &callResult); + + if (asyncCallbackInfo->callback[0] != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->callback[0]); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; +}; + +auto NAPI_GetUidWrapPromiseCompleteCallBack = [](napi_env env, napi_status status, void *data) { + HILOG_INFO("GetUid compeleted(Promise Mode)..."); + AsyncGetUidCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("asyncCallbackInfo is nullptr."); + return; + } + napi_value result = nullptr; + napi_create_int32(env, asyncCallbackInfo->uid, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; +}; + +napi_value NAPI_GetUidWrap( + napi_env env, napi_callback_info info, bool callBackMode, AsyncGetUidCallbackInfo &asyncCallbackInfo) +{ + HILOG_INFO("NAPI_GetUidWrap called..."); + if (callBackMode) { + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "NAPI_GetUidCallBack", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work(env, + nullptr, + resourceName, + NAPI_GetUidWrapExecuteCallBack, + NAPI_GetUidWrapCompleteCallBack, + (void *)&asyncCallbackInfo, + &asyncCallbackInfo.asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo.asyncWork)); + // create reutrn + napi_value ret = nullptr; + NAPI_CALL(env, napi_create_int32(env, 0, &ret)); + return ret; + } else { + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "NAPI_GetUidPromise", NAPI_AUTO_LENGTH, &resourceName); + + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo.deferred = deferred; + + napi_create_async_work(env, + nullptr, + resourceName, + NAPI_GetUidWrapExecuteCallBack, + NAPI_GetUidWrapPromiseCompleteCallBack, + (void *)&asyncCallbackInfo, + &asyncCallbackInfo.asyncWork); + napi_queue_async_work(env, asyncCallbackInfo.asyncWork); + return promise; + } +} + +napi_value NAPI_GetUid(napi_env env, napi_callback_info info) +{ + size_t argc = NUMBER_OF_PARAMETERS_TWO; + napi_value argv[NUMBER_OF_PARAMETERS_TWO] = {}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + HILOG_INFO("argc = [%{public}zu]", argc); + + napi_valuetype wantAgentType = napi_valuetype::napi_null; + napi_typeof(env, argv[0], &wantAgentType); + NAPI_ASSERT_RETURN_NULL(env, wantAgentType == napi_object, "Wrong argument type. Object expected."); + + WantAgent *pWantAgent = nullptr; + napi_unwrap(env, argv[0], (void **)&(pWantAgent)); + if (pWantAgent == nullptr) { + return NapiGetNull(env); + } + + bool callBackMode = false; + if (argc >= NUMBER_OF_PARAMETERS_TWO) { + napi_valuetype valuetype = napi_valuetype::napi_null; + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT_RETURN_NULL(env, valuetype == napi_function, "Wrong argument type. Function expected."); + callBackMode = true; + } + AsyncGetUidCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncGetUidCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr, + }; + if (asyncCallbackInfo == nullptr) { + return NapiGetNull(env); + } + asyncCallbackInfo->wantAgent = std::make_shared(*pWantAgent); + + if (callBackMode) { + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback[0]); + } + napi_value ret = NAPI_GetUidWrap(env, info, callBackMode, *asyncCallbackInfo); + if (ret == nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + return ((callBackMode) ? (NapiGetNull(env)) : (ret)); +} + +auto NAPI_GetWantWrapExecuteCallBack = [](napi_env env, void *data) { + HILOG_INFO("GetWant called(CallBack Mode)..."); + AsyncGetWantCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("asyncCallbackInfo is nullptr."); + return; + } + asyncCallbackInfo->want = WantAgentHelper::GetWant(asyncCallbackInfo->wantAgent); +}; + +auto NAPI_GetWantWrapCompleteCallBack = [](napi_env env, napi_status status, void *data) { + HILOG_INFO("GetWant compeleted(CallBack Mode)..."); + AsyncGetWantCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr || asyncCallbackInfo->want == nullptr) { + HILOG_ERROR("asyncCallbackInfo or want is nullptr."); + return; + } + napi_value result[NUMBER_OF_PARAMETERS_TWO] = {}; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value callResult = nullptr; + + result[0] = GetCallbackErrorResult(asyncCallbackInfo->env, BUSINESS_ERROR_CODE_OK); + result[1] = WrapWant(env, *(asyncCallbackInfo->want)); + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); + napi_call_function(env, undefined, callback, NUMBER_OF_PARAMETERS_TWO, &result[0], &callResult); + if (asyncCallbackInfo->callback[0] != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->callback[0]); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; +}; + +auto NAPI_GetWantWrapPromiseCompleteCallBack = [](napi_env env, napi_status status, void *data) { + HILOG_INFO("GetWant compeleted(Promise Mode)..."); + AsyncGetWantCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr || asyncCallbackInfo->want == nullptr) { + HILOG_ERROR("asyncCallbackInfo or want is nullptr."); + return; + } + napi_value result = WrapWant(env, *(asyncCallbackInfo->want)); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; +}; + +napi_value NAPI_GetWantWrap( + napi_env env, napi_callback_info info, bool callBackMode, AsyncGetWantCallbackInfo &asyncCallbackInfo) +{ + HILOG_INFO("NAPI_GetWantWrap called..."); + if (callBackMode) { + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "NAPI_GetWantCallBack", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work(env, + nullptr, + resourceName, + NAPI_GetWantWrapExecuteCallBack, + NAPI_GetWantWrapCompleteCallBack, + (void *)&asyncCallbackInfo, + &asyncCallbackInfo.asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo.asyncWork)); + // create reutrn + napi_value ret = nullptr; + NAPI_CALL(env, napi_create_int32(env, 0, &ret)); + return ret; + } else { + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_GetWantPromise", NAPI_AUTO_LENGTH, &resourceName); + + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo.deferred = deferred; + + napi_create_async_work(env, + nullptr, + resourceName, + NAPI_GetWantWrapExecuteCallBack, + NAPI_GetWantWrapPromiseCompleteCallBack, + (void *)&asyncCallbackInfo, + &asyncCallbackInfo.asyncWork); + napi_queue_async_work(env, asyncCallbackInfo.asyncWork); + return promise; + } +} + +napi_value NAPI_GetWant(napi_env env, napi_callback_info info) +{ + size_t argc = NUMBER_OF_PARAMETERS_TWO; + napi_value argv[NUMBER_OF_PARAMETERS_TWO] = {}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + HILOG_INFO("argc = [%{public}zu]", argc); + + napi_valuetype wantAgentType = napi_valuetype::napi_null; + napi_typeof(env, argv[0], &wantAgentType); + NAPI_ASSERT_RETURN_NULL(env, wantAgentType == napi_object, "Wrong argument type. Object expected."); + + WantAgent *pWantAgent = nullptr; + napi_unwrap(env, argv[0], (void **)&(pWantAgent)); + if (pWantAgent == nullptr) { + return NapiGetNull(env); + } + + bool callBackMode = false; + if (argc >= NUMBER_OF_PARAMETERS_TWO) { + napi_valuetype valuetype = napi_valuetype::napi_null; + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT_RETURN_NULL(env, valuetype == napi_function, "Wrong argument type. Function expected."); + callBackMode = true; + } + AsyncGetWantCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncGetWantCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr, + }; + if (asyncCallbackInfo == nullptr) { + return NapiGetNull(env); + } + asyncCallbackInfo->wantAgent = std::make_shared(*pWantAgent); + + if (callBackMode) { + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback[0]); + } + napi_value ret = NAPI_GetWantWrap(env, info, callBackMode, *asyncCallbackInfo); + if (ret == nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + return ((callBackMode) ? (NapiGetNull(env)) : (ret)); +} + +void DeleteRecordByCode(const int32_t code) +{ + std::lock_guard guard(g_mutex); + for (const auto &item : *g_WantAgentMap) { + auto code_ = item.second; + auto record = item.first; + if (code_ == code) { + g_WantAgentMap->erase(record); + if (record != nullptr) { + delete record; + record = nullptr; + } + } + } +} + +auto NAPI_CancelWrapExecuteCallBack = [](napi_env env, void *data) { + HILOG_INFO("Cancel called(CallBack Mode)..."); + AsyncCancelCallbackInfo *asyncCallbackInfo = static_cast(data); + WantAgentHelper::Cancel(asyncCallbackInfo->wantAgent); +}; + +auto NAPI_CancelWrapCompleteCallBack = [](napi_env env, napi_status status, void *data) { + HILOG_INFO("Cancel compeleted(CallBack Mode)..."); + AsyncCancelCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("asyncCallbackInfo is nullptr."); + return; + } + napi_value result[NUMBER_OF_PARAMETERS_TWO] = {nullptr}; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value callResult = nullptr; + + result[0] = GetCallbackErrorResult(asyncCallbackInfo->env, BUSINESS_ERROR_CODE_OK); + napi_get_null(env, &result[1]); + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); + napi_call_function(env, undefined, callback, NUMBER_OF_PARAMETERS_TWO, &result[0], &callResult); + + if (asyncCallbackInfo->callback[0] != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->callback[0]); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; +}; + +auto NAPI_CancelWrapPromiseCompleteCallBack = [](napi_env env, napi_status status, void *data) { + HILOG_INFO("Cancel compeleted(Promise Mode)..."); + AsyncCancelCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("asyncCallbackInfo is nullptr."); + return; + } + napi_value result = nullptr; + napi_get_null(env, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; +}; + +napi_value NAPI_CancelWrap( + napi_env env, napi_callback_info info, bool callBackMode, AsyncCancelCallbackInfo &asyncCallbackInfo) +{ + HILOG_INFO("NAPI_CancelWrap called..."); + if (callBackMode) { + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "NAPI_CancelCallBack", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work(env, + nullptr, + resourceName, + NAPI_CancelWrapExecuteCallBack, + NAPI_CancelWrapCompleteCallBack, + (void *)&asyncCallbackInfo, + &asyncCallbackInfo.asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo.asyncWork)); + // create reutrn + napi_value ret = nullptr; + NAPI_CALL(env, napi_create_int32(env, 0, &ret)); + return ret; + } else { + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "NAPI_CancelPromise", NAPI_AUTO_LENGTH, &resourceName); + + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo.deferred = deferred; + + napi_create_async_work(env, + nullptr, + resourceName, + NAPI_CancelWrapExecuteCallBack, + NAPI_CancelWrapPromiseCompleteCallBack, + (void *)&asyncCallbackInfo, + &asyncCallbackInfo.asyncWork); + napi_queue_async_work(env, asyncCallbackInfo.asyncWork); + return promise; + } +} + +napi_value NAPI_Cancel(napi_env env, napi_callback_info info) +{ + size_t argc = NUMBER_OF_PARAMETERS_TWO; + napi_value argv[NUMBER_OF_PARAMETERS_TWO] = {}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + HILOG_INFO("argc = [%{public}zu]", argc); + + napi_valuetype wantAgentType = napi_valuetype::napi_null; + napi_typeof(env, argv[0], &wantAgentType); + NAPI_ASSERT_RETURN_NULL(env, wantAgentType == napi_object, "Wrong argument type. Object expected."); + + WantAgent *pWantAgent = nullptr; + napi_unwrap(env, argv[0], (void **)&(pWantAgent)); + if (pWantAgent == nullptr) { + return NapiGetNull(env); + } + + bool callBackMode = false; + if (argc >= NUMBER_OF_PARAMETERS_TWO) { + napi_valuetype valuetype = napi_valuetype::napi_null; + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT_RETURN_NULL(env, valuetype == napi_function, "Wrong argument type. Function expected."); + callBackMode = true; + } + AsyncCancelCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncCancelCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr, + }; + if (asyncCallbackInfo == nullptr) { + return NapiGetNull(env); + } + asyncCallbackInfo->wantAgent = std::make_shared(*pWantAgent); + + if (callBackMode) { + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback[0]); + } + napi_value ret = NAPI_CancelWrap(env, info, callBackMode, *asyncCallbackInfo); + if (ret == nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + return ((callBackMode) ? (NapiGetNull(env)) : (ret)); +} + +auto NAPI_TriggerWrapExecuteCallBack = [](napi_env env, void *data) { + HILOG_INFO("Trigger called ..."); + AsyncTriggerCallbackInfo *asyncCallbackInfo = static_cast(data); + asyncCallbackInfo->triggerObj->SetCallbackInfo(env, asyncCallbackInfo->callback[0]); + asyncCallbackInfo->triggerObj->SetWantAgentInstance(asyncCallbackInfo->wantAgent); + WantAgentHelper::TriggerWantAgent(asyncCallbackInfo->wantAgent, + asyncCallbackInfo->triggerObj, + asyncCallbackInfo->triggerInfo); +}; + +auto NAPI_TriggerWrapCompleteCallBack = [](napi_env env, napi_status status, void *data) { + HILOG_INFO("Trigger compeleted ..."); + AsyncTriggerCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("asyncCallbackInfo is nullptr."); + return; + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; +}; + +napi_value NAPI_TriggerWrap(napi_env env, napi_callback_info info, AsyncTriggerCallbackInfo &asyncCallbackInfo) +{ + HILOG_INFO("NAPI_TriggerWrap called..."); + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "NAPI_TriggerWrap", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work(env, + nullptr, + resourceName, + NAPI_TriggerWrapExecuteCallBack, + NAPI_TriggerWrapCompleteCallBack, + (void *)&asyncCallbackInfo, + &asyncCallbackInfo.asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo.asyncWork)); + // create reutrn + napi_value ret = nullptr; + NAPI_CALL(env, napi_create_int32(env, 0, &ret)); + return ret; +} + +napi_value NAPI_GetTriggerInfo(napi_value argv[NUMBER_OF_PARAMETERS_THREE], uint8_t argvLen, napi_env env, + napi_callback_info info, TriggerInfo &triggerInfo) +{ + if (argvLen < 1) { + return nullptr; + } + // Get triggerInfo + napi_value jsTriggerInfo = argv[1]; + napi_valuetype valueType = napi_valuetype::napi_null; + NAPI_CALL(env, napi_typeof(env, jsTriggerInfo, &valueType)); + NAPI_ASSERT_RETURN_NULL(env, valueType == napi_object, "param type mismatch!"); + + // Get triggerInfo code + int32_t code = -1; + if (!UnwrapInt32ByPropertyName(env, jsTriggerInfo, "code", code)) { + return NapiGetNull(env); + } + // Get triggerInfo want + napi_value jsWant = nullptr; + jsWant = GetPropertyValueByPropertyName(env, jsTriggerInfo, "want", napi_object); + std::shared_ptr want = nullptr; + if (jsWant != nullptr) { + want = std::make_shared(); + if (!UnwrapWant(env, jsWant, *want)) { + return NapiGetNull(env); + } + } + // Get triggerInfo permission + std::string permission = {}; + UnwrapStringByPropertyName(env, jsTriggerInfo, "permission", permission); + // Get triggerInfo extraInfo + napi_value jsExtraInfo = nullptr; + jsExtraInfo = GetPropertyValueByPropertyName(env, jsTriggerInfo, "extraInfo", napi_object); + std::shared_ptr extraInfo = nullptr; + if (jsExtraInfo != nullptr) { + extraInfo = std::make_shared(); + if (!UnwrapWantParams(env, jsExtraInfo, *extraInfo)) { + return NapiGetNull(env); + } + } + + TriggerInfo triggerInfoData(permission, extraInfo, want, code); + triggerInfo = triggerInfoData; + return NapiGetNull(env); +} + +napi_value NAPI_Trigger(napi_env env, napi_callback_info info) +{ + size_t argc = NUMBER_OF_PARAMETERS_THREE; + napi_value argv[NUMBER_OF_PARAMETERS_THREE] = {}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + HILOG_INFO("argc = [%{public}zu]", argc); + + napi_valuetype wantAgentType = napi_valuetype::napi_null; + napi_typeof(env, argv[0], &wantAgentType); + NAPI_ASSERT_RETURN_NULL(env, wantAgentType == napi_object, "Wrong argument type. Object expected."); + + WantAgent *pWantAgent = nullptr; + napi_unwrap(env, argv[0], (void **)&(pWantAgent)); + if (pWantAgent == nullptr) { + return NapiGetNull(env); + } + + bool callBackMode = false; + if (argc >= NUMBER_OF_PARAMETERS_THREE) { + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, argv[NUMBER_OF_PARAMETERS_TWO], &valuetype)); + NAPI_ASSERT_RETURN_NULL(env, valuetype == napi_function, "Wrong argument type. Function expected."); + callBackMode = true; + } + + TriggerInfo triggerInfo; + napi_value ret = NAPI_GetTriggerInfo(argv, NUMBER_OF_PARAMETERS_THREE, env, info, triggerInfo); + if (ret == nullptr) { + return NapiGetNull(env); + } + + AsyncTriggerCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncTriggerCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr, + }; + if (asyncCallbackInfo == nullptr) { + return NapiGetNull(env); + } + asyncCallbackInfo->wantAgent = std::make_shared(*pWantAgent); + asyncCallbackInfo->triggerInfo = triggerInfo; + asyncCallbackInfo->triggerObj = nullptr; + if (callBackMode) { + asyncCallbackInfo->callBackMode = callBackMode; + asyncCallbackInfo->triggerObj = std::make_shared(); + napi_create_reference(env, argv[NUMBER_OF_PARAMETERS_TWO], 1, &asyncCallbackInfo->callback[0]); + } + + ret = NAPI_TriggerWrap(env, info, *asyncCallbackInfo); + if (ret == nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + return NapiGetNull(env); +} + +auto NAPI_EqualWrapExecuteCallBack = [](napi_env env, void *data) { + HILOG_INFO("Equal called(CallBack Mode)..."); + AsyncEqualCallbackInfo *asyncCallbackInfo = static_cast(data); + asyncCallbackInfo->result = + WantAgentHelper::JudgeEquality(asyncCallbackInfo->wantAgentFirst, asyncCallbackInfo->wantAgentSecond); +}; + +auto NAPI_EqualWrapCompleteCallBack = [](napi_env env, napi_status status, void *data) { + HILOG_INFO("Equal compeleted(CallBack Mode)..."); + AsyncEqualCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("asyncCallbackInfo is nullptr."); + return; + } + napi_value result[NUMBER_OF_PARAMETERS_TWO] = {}; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value callResult = nullptr; + + result[0] = GetCallbackErrorResult(asyncCallbackInfo->env, BUSINESS_ERROR_CODE_OK); + napi_get_boolean(env, asyncCallbackInfo->result, &result[1]); + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); + napi_call_function(env, undefined, callback, NUMBER_OF_PARAMETERS_TWO, &result[0], &callResult); + + if (asyncCallbackInfo->callback[0] != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->callback[0]); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; +}; + +auto NAPI_EqualWrapPromiseCompleteCallBack = [](napi_env env, napi_status status, void *data) { + HILOG_INFO("Equal compeleted(Promise Mode)..."); + AsyncEqualCallbackInfo *asyncCallbackInfo = static_cast(data); + napi_value result = nullptr; + napi_get_boolean(env, asyncCallbackInfo->result, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; +}; + +napi_value NAPI_EqualWrap( + napi_env env, napi_callback_info info, bool callBackMode, AsyncEqualCallbackInfo &asyncCallbackInfo) +{ + HILOG_INFO("NAPI_EqualWrap called..."); + if (callBackMode) { + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "NAPI_EqualWrapCallBack", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work(env, + nullptr, + resourceName, + NAPI_EqualWrapExecuteCallBack, + NAPI_EqualWrapCompleteCallBack, + (void *)&asyncCallbackInfo, + &asyncCallbackInfo.asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo.asyncWork)); + // create reutrn + napi_value ret = nullptr; + NAPI_CALL(env, napi_create_int32(env, 0, &ret)); + return ret; + } else { + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "NAPI_EqualPromise", NAPI_AUTO_LENGTH, &resourceName); + + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo.deferred = deferred; + + napi_create_async_work(env, + nullptr, + resourceName, + NAPI_EqualWrapExecuteCallBack, + NAPI_EqualWrapPromiseCompleteCallBack, + (void *)&asyncCallbackInfo, + &asyncCallbackInfo.asyncWork); + napi_queue_async_work(env, asyncCallbackInfo.asyncWork); + return promise; + } +} + +napi_value NAPI_Equal(napi_env env, napi_callback_info info) +{ + size_t argc = NUMBER_OF_PARAMETERS_THREE; + napi_value argv[NUMBER_OF_PARAMETERS_THREE] = {}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + HILOG_INFO("argc = [%{public}zu]", argc); + + napi_valuetype wantAgentFirstType = napi_valuetype::napi_null; + napi_typeof(env, argv[0], &wantAgentFirstType); + NAPI_ASSERT_RETURN_NULL(env, wantAgentFirstType == napi_object, "Wrong argument type. Object expected."); + + WantAgent *pWantAgentFirst = nullptr; + napi_unwrap(env, argv[0], (void **)&(pWantAgentFirst)); + if (pWantAgentFirst == nullptr) { + return NapiGetNull(env); + } + + napi_valuetype wantAgentSecondType = napi_valuetype::napi_null; + napi_typeof(env, argv[1], &wantAgentSecondType); + NAPI_ASSERT_RETURN_NULL(env, wantAgentSecondType == napi_object, "Wrong argument type. Object expected."); + + WantAgent *pWantAgentSecond = nullptr; + napi_unwrap(env, argv[1], (void **)&(pWantAgentSecond)); + if (pWantAgentSecond == nullptr) { + return NapiGetNull(env); + } + + bool callBackMode = false; + if (argc >= NUMBER_OF_PARAMETERS_THREE) { + napi_valuetype valuetype = napi_valuetype::napi_null; + NAPI_CALL(env, napi_typeof(env, argv[NUMBER_OF_PARAMETERS_TWO], &valuetype)); + NAPI_ASSERT_RETURN_NULL(env, valuetype == napi_function, "Wrong argument type. Function expected."); + callBackMode = true; + } + AsyncEqualCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncEqualCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr, + }; + if (asyncCallbackInfo == nullptr) { + return NapiGetNull(env); + } + asyncCallbackInfo->wantAgentFirst = std::make_shared(*pWantAgentFirst); + asyncCallbackInfo->wantAgentSecond = std::make_shared(*pWantAgentSecond); + + if (callBackMode) { + napi_create_reference(env, argv[NUMBER_OF_PARAMETERS_TWO], 1, &asyncCallbackInfo->callback[0]); + } + napi_value ret = NAPI_EqualWrap(env, info, callBackMode, *asyncCallbackInfo); + if (ret == nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + return ((callBackMode) ? (NapiGetNull(env)) : (ret)); +} + +auto NAPI_GetWantAgentWrapExecuteCallBack = [](napi_env env, void *data) { + HILOG_INFO("GetWantAgent called(CallBack Mode)..."); + AsyncGetWantAgentCallbackInfo *asyncCallbackInfo = static_cast(data); + WantAgentInfo wantAgentInfo(asyncCallbackInfo->requestCode, + asyncCallbackInfo->operationType, + asyncCallbackInfo->wantAgentFlags, + asyncCallbackInfo->wants, + asyncCallbackInfo->extraInfo); + asyncCallbackInfo->wantAgent = + WantAgentHelper::GetWantAgent(asyncCallbackInfo->context, wantAgentInfo); + if (asyncCallbackInfo->wantAgent == nullptr) { + HILOG_INFO("GetWantAgent instance is nullptr..."); + } + int32_t code = WantAgentHelper::GetHashCode(asyncCallbackInfo->wantAgent); + std::lock_guard guard(g_mutex); + g_WantAgentMap->emplace(asyncCallbackInfo, code); +}; + +auto NAPI_GetWantAgentWrapCompleteCallBack = [](napi_env env, napi_status status, void *data) { + HILOG_INFO("GetWantAgent compeleted(CallBack Mode)..."); + AsyncGetWantAgentCallbackInfo *asyncCallbackInfo = static_cast(data); + napi_value result[NUMBER_OF_PARAMETERS_TWO] = {0}; + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value callResult = nullptr; + + result[0] = GetCallbackErrorResult(asyncCallbackInfo->env, BUSINESS_ERROR_CODE_OK); + + napi_value wantAgentClass = nullptr; + napi_define_class(env, + "WantAgentClass", + NAPI_AUTO_LENGTH, + [](napi_env env, napi_callback_info info) -> napi_value { + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + return thisVar; + }, + nullptr, + 0, + nullptr, + &wantAgentClass); + napi_new_instance(env, wantAgentClass, 0, nullptr, &result[1]); + napi_wrap(env, + result[1], + (void *)asyncCallbackInfo->wantAgent.get(), + [](napi_env env, void *data, void *hint) {}, + nullptr, + nullptr); + napi_get_undefined(env, &undefined); + napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); + napi_call_function(env, undefined, callback, NUMBER_OF_PARAMETERS_TWO, &result[0], &callResult); + + if (asyncCallbackInfo->callback[0] != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->callback[0]); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); +}; + +auto NAPI_GetWantAgentWrapPromiseCompleteCallBack = [](napi_env env, napi_status status, void *data) { + HILOG_INFO("GetWantAgent compeleted(Promise Mode)..."); + AsyncGetWantAgentCallbackInfo *asyncCallbackInfo = static_cast(data); + napi_value wantAgentClass = nullptr; + napi_define_class(env, + "WantAgentClass", + NAPI_AUTO_LENGTH, + [](napi_env env, napi_callback_info info) -> napi_value { + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + return thisVar; + }, + nullptr, + 0, + nullptr, + &wantAgentClass); + napi_value result = nullptr; + napi_new_instance(env, wantAgentClass, 0, nullptr, &result); + napi_wrap(env, + result, + (void *)asyncCallbackInfo->wantAgent.get(), + [](napi_env env, void *data, void *hint) {}, + nullptr, + nullptr); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); +}; + +napi_value NAPI_GetWantAgentWrap( + napi_env env, napi_callback_info info, bool callBackMode, AsyncGetWantAgentCallbackInfo &asyncCallbackInfo) +{ + HILOG_INFO("NAPI_GetWantAgentWrap called..."); + if (callBackMode) { + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "NAPI_GetWantAgentCallBack", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work(env, + nullptr, + resourceName, + NAPI_GetWantAgentWrapExecuteCallBack, + NAPI_GetWantAgentWrapCompleteCallBack, + (void *)&asyncCallbackInfo, + &asyncCallbackInfo.asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo.asyncWork)); + // create reutrn + napi_value ret = nullptr; + NAPI_CALL(env, napi_create_int32(env, 0, &ret)); + return ret; + } else { + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "NAPI_GetWantAgentPromise", NAPI_AUTO_LENGTH, &resourceName); + + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo.deferred = deferred; + + napi_create_async_work(env, + nullptr, + resourceName, + NAPI_GetWantAgentWrapExecuteCallBack, + NAPI_GetWantAgentWrapPromiseCompleteCallBack, + (void *)&asyncCallbackInfo, + &asyncCallbackInfo.asyncWork); + napi_queue_async_work(env, asyncCallbackInfo.asyncWork); + return promise; + } +} + +napi_value NAPI_GetWantAgentWants(napi_env env, napi_value jsWantAgentInfo, const WantAgentWantsParas ¶s) +{ + napi_valuetype jsWantAgentInfoType = napi_valuetype::napi_null; + NAPI_CALL(env, napi_typeof(env, jsWantAgentInfo, &jsWantAgentInfoType)); + NAPI_ASSERT_RETURN_NULL(env, jsWantAgentInfoType == napi_object, "param type mismatch!"); + + napi_value jsWants = GetPropertyValueByPropertyName(env, jsWantAgentInfo, "wants", napi_object); + bool isArray = false; + if (jsWants == nullptr || napi_is_array(env, jsWants, &isArray) != napi_ok || !isArray) { + return NapiGetNull(env); + } + + uint32_t wantsLen = 0; + napi_get_array_length(env, jsWants, &wantsLen); + for (uint32_t i = 0; i < wantsLen; i++) { + std::shared_ptr want = std::make_shared(); + napi_value jsWant = nullptr; + napi_get_element(env, jsWants, i, &jsWant); + if (!UnwrapWant(env, jsWant, *want)) { + return NapiGetNull(env); + } + paras.wants.emplace_back(want); + } + + // Get operationType + if (!UnwrapInt32ByPropertyName(env, jsWantAgentInfo, "operationType", paras.operationType)) { + return NapiGetNull(env); + } + // Get requestCode + if (!UnwrapInt32ByPropertyName(env, jsWantAgentInfo, "requestCode", paras.requestCode)) { + return NapiGetNull(env); + } + // Get wantAgentFlags + napi_value JsWantAgentFlags = GetPropertyValueByPropertyName(env, jsWantAgentInfo, "wantAgentFlags", napi_object); + if (JsWantAgentFlags != nullptr) { + uint32_t arrayLength = 0; + NAPI_CALL(env, napi_get_array_length(env, JsWantAgentFlags, &arrayLength)); + HILOG_INFO("property is array, length=%{public}d", arrayLength); + for (uint32_t i = 0; i < arrayLength; i++) { + napi_value napiWantAgentFlags = nullptr; + napi_get_element(env, JsWantAgentFlags, i, &napiWantAgentFlags); + napi_valuetype valuetype0 = napi_valuetype::napi_null; + NAPI_CALL(env, napi_typeof(env, napiWantAgentFlags, &valuetype0)); + NAPI_ASSERT_RETURN_NULL(env, valuetype0 == napi_number, "Wrong argument type. Numbers expected."); + int32_t value0 = 0; + NAPI_CALL(env, napi_get_value_int32(env, napiWantAgentFlags, &value0)); + paras.wantAgentFlags.emplace_back(static_cast(value0)); + } + } + // Get extraInfo + napi_value JsExtraInfo = GetPropertyValueByPropertyName(env, jsWantAgentInfo, "extraInfo", napi_object); + if (JsExtraInfo != nullptr) { + if (!UnwrapWantParams(env, JsExtraInfo, paras.extraInfo)) { + return NapiGetNull(env); + } + } + return NapiGetNull(env); +} + +napi_value NAPI_GetWantAgent(napi_env env, napi_callback_info info) +{ + size_t argc = NUMBER_OF_PARAMETERS_TWO; + napi_value argv[NUMBER_OF_PARAMETERS_TWO] = {}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + HILOG_INFO("argc = [%{public}zu]", argc); + napi_value jsWantAgentInfo = argv[0]; + + // Get wants + std::vector> wants = {}; + int32_t operationType = -1; + int32_t requestCode = -1; + std::vector wantAgentFlags = {}; + AAFwk::WantParams extraInfo = {}; + WantAgentWantsParas paras = { + .wants = wants, + .operationType = operationType, + .requestCode = requestCode, + .wantAgentFlags = wantAgentFlags, + .extraInfo = extraInfo, + }; + napi_value ret = NAPI_GetWantAgentWants(env, jsWantAgentInfo, paras); + if (ret == nullptr) { + return NapiGetNull(env); + } + + bool callBackMode = false; + if (argc >= NUMBER_OF_PARAMETERS_TWO) { + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT_RETURN_NULL(env, valuetype == napi_function, "Wrong argument type. Function expected."); + callBackMode = true; + } + + AsyncGetWantAgentCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncGetWantAgentCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr, + }; + if (asyncCallbackInfo == nullptr) { + return NapiGetNull(env); + } + asyncCallbackInfo->wants = wants; + asyncCallbackInfo->operationType = + static_cast(operationType); + asyncCallbackInfo->requestCode = requestCode; + asyncCallbackInfo->wantAgentFlags = wantAgentFlags; + asyncCallbackInfo->extraInfo.reset(new (std::nothrow) AAFwk::WantParams(extraInfo)); + asyncCallbackInfo->context = OHOS::AbilityRuntime::Context::GetApplicationContext(); + + if (callBackMode) { + napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback[0]); + } + ret = NAPI_GetWantAgentWrap(env, info, callBackMode, *asyncCallbackInfo); + if (ret == nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + + return ((callBackMode) ? (NapiGetNull(env)) : (ret)); +} + +napi_value GetCallbackErrorResult(napi_env env, int errCode) +{ + napi_value result = nullptr; + napi_value eCode = nullptr; + NAPI_CALL(env, napi_create_int32(env, errCode, &eCode)); + NAPI_CALL(env, napi_create_object(env, &result)); + NAPI_CALL(env, napi_set_named_property(env, result, "code", eCode)); + return result; +} + +napi_value NapiGetNull(napi_env env) +{ + napi_value result = nullptr; + napi_get_null(env, &result); + return result; +} +} // namespace OHOS diff --git a/interfaces/kits/napi/aafwk/wantagent/napi_want_agent.h b/interfaces/kits/napi/aafwk/wantagent/napi_want_agent.h new file mode 100644 index 0000000000000000000000000000000000000000..8c64823d72eb1658b672477c1872937718bc4cd8 --- /dev/null +++ b/interfaces/kits/napi/aafwk/wantagent/napi_want_agent.h @@ -0,0 +1,197 @@ +/* + * 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 NAPI_WANT_AGENT_H +#define NAPI_WANT_AGENT_H + +#include +#include +#include +#include + +#include "ability.h" +#include "completed_callback.h" +#include "context/context.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" +#include "trigger_info.h" +#include "want.h" +#include "want_agent.h" +#include "want_agent_constant.h" +#include "want_params.h" + +namespace OHOS { +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime::WantAgent; + +const uint8_t NUMBER_OF_PARAMETERS_ZERO = 0; +const uint8_t NUMBER_OF_PARAMETERS_ONE = 1; +const uint8_t NUMBER_OF_PARAMETERS_TWO = 2; +const uint8_t NUMBER_OF_PARAMETERS_THREE = 3; +const uint8_t NUMBER_OF_PARAMETERS_FOUR = 4; +const uint8_t NUMBER_OF_PARAMETERS_FIVE = 5; +const uint8_t NUMBER_OF_PARAMETERS_SIX = 6; +const uint8_t NUMBER_OF_PARAMETERS_SEVEN = 7; +const uint8_t NUMBER_OF_PARAMETERS_EIGHT = 8; +const uint8_t NUMBER_OF_PARAMETERS_NINE = 9; + +class TriggerCompleteCallBack; + +struct AsyncGetWantAgentCallbackInfo { + napi_env env; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback[2] = {0}; + std::vector> wants; + WantAgentConstant::OperationType operationType; + int32_t requestCode = -1; + std::vector wantAgentFlags; + std::shared_ptr extraInfo; + std::shared_ptr context; + std::shared_ptr wantAgent; +}; + +struct AsyncGetBundleNameCallbackInfo { + napi_env env; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback[2] = {0}; + std::shared_ptr wantAgent; + std::string bundleName; +}; + +struct AsyncGetUidCallbackInfo { + napi_env env; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback[2] = {0}; + std::shared_ptr wantAgent; + int32_t uid; +}; + +struct AsyncGetWantCallbackInfo { + napi_env env; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback[2] = {0}; + std::shared_ptr wantAgent; + std::shared_ptr want; +}; + +struct AsyncEqualCallbackInfo { + napi_env env; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback[2] = {0}; + std::shared_ptr wantAgentFirst; + std::shared_ptr wantAgentSecond; + bool result; +}; + +struct AsyncCancelCallbackInfo { + napi_env env; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback[2] = {0}; + std::shared_ptr wantAgent; +}; + +struct AsyncTriggerCallbackInfo { + napi_env env; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback[2] = {0}; + bool callBackMode = false; + std::shared_ptr triggerObj; + std::shared_ptr wantAgent; + TriggerInfo triggerInfo; +}; + +struct CallbackInfo { + std::shared_ptr wantAgent; + napi_env env; + napi_ref ref; +}; + +struct TriggerReceiveDataWorker { + napi_env env; + napi_ref ref = 0; + std::shared_ptr wantAgent; + AAFwk::Want want; + int resultCode; + std::string resultData; + AAFwk::WantParams resultExtras; +}; + +struct WantAgentWantsParas { + std::vector> &wants; + int32_t &operationType; + int32_t &requestCode; + std::vector &wantAgentFlags; + AAFwk::WantParams &extraInfo; +}; + +class TriggerCompleteCallBack : public CompletedCallback { +public: + TriggerCompleteCallBack(); + virtual ~TriggerCompleteCallBack(); + +public: + virtual void OnSendFinished(const AAFwk::Want &want, int resultCode, const std::string &resultData, + const AAFwk::WantParams &resultExtras) override; + void SetCallbackInfo(const napi_env &env, const napi_ref &ref); + void SetWantAgentInstance(const std::shared_ptr &wantAgent); + +private: + CallbackInfo triggerCompleteInfo_; +}; + +napi_value WantAgentInit(napi_env env, napi_value exports); + +void SetNamedPropertyByInteger(napi_env env, napi_value dstObj, int32_t objName, const std::string &propName); +napi_value WantAgentFlagsInit(napi_env env, napi_value exports); +napi_value WantAgentOperationTypeInit(napi_env env, napi_value exports); + +napi_value NAPI_GetBundleName(napi_env env, napi_callback_info info); +napi_value NAPI_GetUid(napi_env env, napi_callback_info info); +napi_value NAPI_GetWant(napi_env env, napi_callback_info info); +napi_value NAPI_Cancel(napi_env env, napi_callback_info info); +napi_value NAPI_Trigger(napi_env env, napi_callback_info info); +napi_value NAPI_Equal(napi_env env, napi_callback_info info); +napi_value NAPI_GetWantAgent(napi_env env, napi_callback_info info); + +napi_value GetCallbackErrorResult(napi_env env, int errCode); +napi_value NapiGetNull(napi_env env); + +void DeleteRecordByCode(const int32_t code); +static std::unique_ptr, + std::function *)>> + g_WantAgentMap(new std::map, + [](std::map *map) { + if (map == nullptr) { + return; + } + for (auto &item : *map) { + if (item.first != nullptr) { + delete item.first; + } + } + map->clear(); + delete map; + }); +static std::recursive_mutex g_mutex; +} // namespace OHOS +#endif // NAPI_WANT_AGENT_H diff --git a/interfaces/kits/js/app/activeServiceAbilityInfo.d.ts b/interfaces/kits/napi/aafwk/wantagent/native_module.cpp old mode 100755 new mode 100644 similarity index 40% rename from interfaces/kits/js/app/activeServiceAbilityInfo.d.ts rename to interfaces/kits/napi/aafwk/wantagent/native_module.cpp index 8e9c14e1142a63f083d341922f94f8cb73ac1b72..a2958047cf5e3e01f847689f822c9afa52c7c15b --- a/interfaces/kits/js/app/activeServiceAbilityInfo.d.ts +++ b/interfaces/kits/napi/aafwk/wantagent/native_module.cpp @@ -13,43 +13,51 @@ * limitations under the License. */ -import { ElementName } from '../bundle/elementName'; +#include +#include +#include +#include -/** - * @name information corresponding to active service ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - * @import import AbilityMissionInfo from 'app/activeServiceAbilityInfo' - * @permission N/A - * @devices phone, tablet, tv, wearable, car - */ -export interface ActiveServiceAbilityInfo { - /** - * @default process id - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - pid: number; +#include "napi_want_agent.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" - /** - * @default user id - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - uid: number; +#include "hilog_wrapper.h" - /** - * @default the name of the process - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - processName: string; +using namespace OHOS::AbilityRuntime::WantAgent; - /** - * @default The element name of the service ability - * @since 7 - * @SysCap SystemCapability.Appexecfwk - */ - serviceAbility: ElementName; +namespace OHOS { +EXTERN_C_START +/* + * function for module exports + */ +static napi_value Init(napi_env env, napi_value exports) +{ + WantAgentInit(env, exports); + WantAgentFlagsInit(env, exports); + WantAgentOperationTypeInit(env, exports); + return exports; } +EXTERN_C_END +/* + * Module define + */ +static napi_module _module = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "wantagent", + .nm_priv = ((void *)0), + .reserved = {0}, +}; + +/* + * Module register function + */ +extern "C" __attribute__((constructor)) void RegisterModule(void) +{ + napi_module_register(&_module); +} +} // namespace OHOS \ No newline at end of file diff --git a/ohos.build b/ohos.build index 3aee6a65440edb0762aef1a67ac6cd09df6121d3..210459f71cf8321a2138e613b7a54586556da773 100644 --- a/ohos.build +++ b/ohos.build @@ -10,49 +10,15 @@ "//foundation/aafwk/standard/sa_profile:aafwk_sa_profile", "//foundation/aafwk/standard/interfaces/kits/napi:napi_packages", "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native", + "//foundation/aafwk/standard/common:common_target", "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/frameworks/kits/wantagent:native_wantagent", "//foundation/aafwk/standard/frameworks/kits/appkit:appexec", "//foundation/aafwk/standard/test/resource/amssystemtestability/abilitySrc:ams_system_test_app" + ], "inner_kits": [ - { - "header": { - "header_base": "//foundation/aafwk/standard/interfaces/innerkits/base/include/", - "header_files": [ - "ohos/aafwk/base/array_wrapper.h", - "ohos/aafwk/base/base_def.h", - "ohos/aafwk/base/base_interfaces.h", - "ohos/aafwk/base/base_object.h", - "ohos/aafwk/base/base_types.h", - "ohos/aafwk/base/bool_wrapper.h", - "ohos/aafwk/base/byte_wrapper.h", - "ohos/aafwk/base/double_wrapper.h", - "ohos/aafwk/base/float_wrapper.h", - "ohos/aafwk/base/int_wrapper.h", - "ohos/aafwk/base/light_refbase.h", - "ohos/aafwk/base/long_wrapper.h", - "ohos/aafwk/base/short_wrapper.h", - "ohos/aafwk/base/string_wrapper.h" - ] - }, - "name": "//foundation/aafwk/standard/interfaces/innerkits/base:base" - }, - { - "header": { - "header_base": "//foundation/aafwk/standard/interfaces/innerkits/want/include/", - "header_files": [ - "ohos/aafwk/content/want.h", - "ohos/aafwk/content/skills.h", - "ohos/aafwk/content/want_params.h", - "ohos/aafwk/content/match_type.h", - "ohos/aafwk/content/operation.h", - "ohos/aafwk/content/patterns_matcher.h", - "ohos/aafwk/content/pac_map.h" - ] - }, - "name": "//foundation/aafwk/standard/interfaces/innerkits/want:want" - }, { "header": { "header_base": "//foundation/aafwk/standard/interfaces/innerkits/intent/include/", @@ -116,7 +82,9 @@ "appmgr/iapp_state_callback.h", "appmgr/app_state_callback_host.h", "appmgr/app_mgr_constants.h", - "appmgr/app_process_data.h" + "appmgr/app_process_data.h", + "appmgr/irender_scheduler.h", + "appmgr/render_scheduler_host.h" ] }, "name": "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager" @@ -221,6 +189,62 @@ "//foundation/aafwk/standard/services/formmgr/test:unittest", "//foundation/aafwk/standard/test/systemtest:systemtest" ] + }, + "ability_base": { + "module_list": [ + "//foundation/aafwk/standard/interfaces/innerkits:base_innerkits_target" + ], + "inner_kits": [ + { + "header": { + "header_base": "//foundation/aafwk/standard/interfaces/innerkits/base/include/", + "header_files": [ + "ohos/aafwk/base/array_wrapper.h", + "ohos/aafwk/base/base_def.h", + "ohos/aafwk/base/base_interfaces.h", + "ohos/aafwk/base/base_object.h", + "ohos/aafwk/base/base_types.h", + "ohos/aafwk/base/bool_wrapper.h", + "ohos/aafwk/base/byte_wrapper.h", + "ohos/aafwk/base/double_wrapper.h", + "ohos/aafwk/base/float_wrapper.h", + "ohos/aafwk/base/int_wrapper.h", + "ohos/aafwk/base/light_refbase.h", + "ohos/aafwk/base/long_wrapper.h", + "ohos/aafwk/base/short_wrapper.h", + "ohos/aafwk/base/string_wrapper.h" + ] + }, + "name": "//foundation/aafwk/standard/interfaces/innerkits/base:base" + }, + { + "header": { + "header_base": "//foundation/aafwk/standard/interfaces/innerkits/want/include/", + "header_files": [ + "ohos/aafwk/content/want.h", + "ohos/aafwk/content/skills.h", + "ohos/aafwk/content/want_params.h", + "ohos/aafwk/content/match_type.h", + "ohos/aafwk/content/operation.h", + "ohos/aafwk/content/patterns_matcher.h", + "ohos/aafwk/content/pac_map.h" + ] + }, + "name": "//foundation/aafwk/standard/interfaces/innerkits/want:want" + }, + { + "header": { + "header_base": "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "header_files": [ + "configuration.h", + "global_configuration_key.h" + ] + }, + "name": "//foundation/aafwk/standard/interfaces/innerkits/app_manager:configuration" + } + ], + "test_list": [ + ] } }, "subsystem": "aafwk" diff --git a/sa_profile/183.xml b/sa_profile/183.xml new file mode 100644 index 0000000000000000000000000000000000000000..8c13b2dc261445dac6d961752ff3c5519fd44bbe --- /dev/null +++ b/sa_profile/183.xml @@ -0,0 +1,27 @@ + + + + upms + + 183 + /system/lib64/libupms.z.so + + + true + false + 1 + + diff --git a/sa_profile/BUILD.gn b/sa_profile/BUILD.gn index 60bcceccf9796baa2d5faac3810c04871199dc14..1fb0d0e29a8d9d73f0674e6a2ed1ad6d4d90fae6 100644 --- a/sa_profile/BUILD.gn +++ b/sa_profile/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -17,6 +17,7 @@ ohos_sa_profile("aafwk_sa_profile") { sources = [ "180.xml", "182.xml", + "183.xml", "501.xml", ] diff --git a/services/BUILD.gn b/services/BUILD.gn index 8721ed8539aa6091687309428172df79b41db386..c11ef1cb046b90849cfd5fe7ab504e9cdfe3290b 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -16,6 +16,7 @@ group("services_target") { "abilitymgr:abilityms_target", "appmgr:ams_target", "dataobsmgr:dataobsms", + "uripermmgr:upms_target", ] } diff --git a/services/abilitymgr/BUILD.gn b/services/abilitymgr/BUILD.gn index a849059eb89b3dbef725bd6ee829e6ea2a2a6163..abeb67abb710710ff88f2f696ea380d2515689a5 100644 --- a/services/abilitymgr/BUILD.gn +++ b/services/abilitymgr/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -78,6 +78,7 @@ ohos_shared_library("abilityms") { configs = [ ":abilityms_config" ] deps = [ "${innerkits_path}/base:base", + "${innerkits_path}/uri_permission:uri_permission_mgr", "${innerkits_path}/want:want", "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//base/global/i18n_standard/frameworks/intl:intl_util", @@ -102,6 +103,7 @@ ohos_shared_library("abilityms") { external_deps = [ "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", "bytrace_standard:bytrace_core", "ces_standard:cesfwk_core", "ces_standard:cesfwk_innerkits", @@ -110,6 +112,7 @@ ohos_shared_library("abilityms") { "hicollie_native:libhicollie", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "os_account_standard:os_account_innerkits", "resmgr_standard:global_resmgr", ] diff --git a/services/abilitymgr/abilitymgr.gni b/services/abilitymgr/abilitymgr.gni index 7813a63a59d19af354d3064a07a1c57bc66b5025..c23b483029c2ffc4719f08573c950ba254cde607 100644 --- a/services/abilitymgr/abilitymgr.gni +++ b/services/abilitymgr/abilitymgr.gni @@ -89,7 +89,6 @@ abilityms_files = [ "${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/kernal_ability_manager.cpp", "${services_path}/abilitymgr/src/call_container.cpp", "${services_path}/abilitymgr/src/call_record.cpp", diff --git a/services/abilitymgr/include/ability_config.h b/services/abilitymgr/include/ability_config.h index 8cbb024fa1c9e239af1a956fb6beea38ee1bbc8b..cbe2ce30a35dbeb1dc844172f3e910110a518b36 100644 --- a/services/abilitymgr/include/ability_config.h +++ b/services/abilitymgr/include/ability_config.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -25,8 +25,8 @@ const std::string NAME_ABILITY_MGR_SERVICE = "AbilityManagerService"; const std::string NAME_BUNDLE_MGR_SERVICE = "BundleMgrService"; const std::string SCHEME_DATA_ABILITY = "dataability"; const std::string SYSTEM_UI_BUNDLE_NAME = "com.ohos.systemui"; -const std::string SYSTEM_UI_STATUS_BAR = "com.ohos.systemui.statusbar.MainAbility"; -const std::string SYSTEM_UI_NAVIGATION_BAR = "com.ohos.systemui.navigationbar.MainAbility"; +const std::string SYSTEM_UI_STATUS_BAR = "com.ohos.systemui.statusbar.ServiceExtAbility"; +const std::string SYSTEM_UI_NAVIGATION_BAR = "com.ohos.systemui.navigationbar.ServiceExtAbility"; const std::string SYSTEM_DIALOG_NAME = "com.ohos.systemui.systemdialog.MainAbility"; const std::string SYSTEM_UI_ABILITY_NAME = "com.ohos.systemui.ServiceExtAbility"; @@ -60,6 +60,11 @@ const std::string CONTACTS_BUNDLE_NAME = "com.ohos.contacts"; const std::string MMS_ABILITY_NAME = "com.ohos.mms.ServiceAbility"; const std::string MMS_BUNDLE_NAME = "com.ohos.mms"; + +const std::string SCREEN_LOCK_ABILITY_NAME = "com.ohos.screenlock.ServiceExtAbility"; +const std::string SCREEN_LOCK_BUNDLE_NAME = "com.ohos.screenlock"; + +const std::string PARAMS_STREAM = "ability.params.stream"; } // namespace AbilityConfig } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/ability_manager_proxy.h b/services/abilitymgr/include/ability_manager_proxy.h index 18ad4c0f89afc025f3d444129d31fc0048c16477..4e38abe4b5509a84d251fddc5b465ac26ad8735f 100644 --- a/services/abilitymgr/include/ability_manager_proxy.h +++ b/services/abilitymgr/include/ability_manager_proxy.h @@ -115,6 +115,17 @@ public: */ virtual int TerminateAbilityByCaller(const sptr &callerToken, int requestCode) override; + /** + * CloseAbility, close the special ability. + * + * @param token, the token of the ability to terminate. + * @param resultCode, the resultCode of the ability to terminate. + * @param resultWant, the Want of the ability to return. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int CloseAbility( + const sptr &token, int resultCode, const Want *resultWant = nullptr) override; + /** * MinimizeAbility, minimize the special ability. * @@ -519,7 +530,7 @@ public: virtual void NotifyCompleteContinuation(const std::string &deviceId, int32_t sessionId, bool isSuccess) override; - virtual int NotifyContinuationResult(int32_t missionId, const int32_t result) override; + virtual int NotifyContinuationResult(int32_t missionId, int32_t result) override; virtual int StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag) override; @@ -544,7 +555,9 @@ public: virtual int CleanAllMissions() override; virtual int MoveMissionToFront(int32_t missionId) override; - + + virtual int MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) override; + /** * Start Ability, connect session with common ability. * @@ -652,14 +665,18 @@ public: /** * Send not response process ID to ability manager service. + * * @param pid The not response process ID. + * @return Returns ERR_OK on success, others on failure. */ - virtual bool SendANRProcessID(int pid) override; - + virtual int SendANRProcessID(int pid) override; + private: template int GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos); bool WriteInterfaceToken(MessageParcel &data); + // flag = true : terminate; flag = false : close + int TerminateAbility(const sptr &token, int resultCode, const Want *resultWant, bool flag); private: static inline BrokerDelegator delegator_; diff --git a/services/abilitymgr/include/ability_manager_service.h b/services/abilitymgr/include/ability_manager_service.h index 112ded812c75f82338fdc9dc015c72be0b8eb79a..9ac904e035ef16843b33503e1d9686b68ddaccc6 100644 --- a/services/abilitymgr/include/ability_manager_service.h +++ b/services/abilitymgr/include/ability_manager_service.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -31,7 +31,6 @@ #include "data_ability_manager.h" #include "hilog_wrapper.h" #include "iremote_object.h" -#include "kernal_ability_manager.h" #include "kernal_system_app_manager.h" #include "mission_list_manager.h" #include "system_ability.h" @@ -143,6 +142,17 @@ public: */ virtual int TerminateAbilityByCaller(const sptr &callerToken, int requestCode) override; + /** + * CloseAbility, close the special ability. + * + * @param token, the token of the ability to terminate. + * @param resultCode, the resultCode of the ability to terminate. + * @param resultWant, the Want of the ability to return. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int CloseAbility(const sptr &token, int resultCode = DEFAULT_INVAL_VALUE, + const Want *resultWant = nullptr) override; + /** * MinimizeAbility, minimize the special ability. * @@ -215,7 +225,7 @@ public: * @param result, continuation result. * @return Returns ERR_OK on success, others on failure. */ - virtual int NotifyContinuationResult(int32_t missionId, const int32_t result) override; + virtual int NotifyContinuationResult(int32_t missionId, int32_t result) override; /** * RegisterMissionListener, register remote device mission listener. @@ -298,6 +308,12 @@ public: virtual int ScheduleConnectAbilityDone( const sptr &token, const sptr &remoteObject) override; + /** + * starting system ui ServiceExt abilites. + * + */ + void StartingSystemUiAbility(); + /** * ScheduleDisconnectAbilityDone, service ability call this interface while session was disconnected. * @@ -659,6 +675,8 @@ public: virtual int MoveMissionToFront(int32_t missionId) override; + virtual int MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) override; + virtual int StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag) override; virtual int StopSyncRemoteMissions(const std::string& devId) override; @@ -700,13 +718,6 @@ public: void OnCallConnectDied(std::shared_ptr callRecord); void GetMaxRestartNum(int &max); bool IsUseNewMission(); - - /** - * wait for starting system ui. - * - */ - void StartSystemUi(const std::string name); - void HandleLoadTimeOut(int64_t eventId); void HandleActiveTimeOut(int64_t eventId); void HandleInactiveTimeOut(int64_t eventId); @@ -844,11 +855,14 @@ public: bool IsAbilityControllerForeground(const std::string &bundleName); + void GrantUriPermission(const Want &want, int32_t validUserId, uint32_t targetTokenId); + /** * Send not response process ID to ability manager service. * @param pid The not response process ID. + * @return Returns ERR_OK on success, others on failure. */ - virtual bool SendANRProcessID(int pid) override; + virtual int SendANRProcessID(int pid) override; // MSG 0 - 20 represents timeout message static constexpr uint32_t LOAD_TIMEOUT_MSG = 0; @@ -900,6 +914,8 @@ public: KEY_DUMPSYS_SERVICE, KEY_DUMPSYS_PENDING, KEY_DUMPSYS_PROCESS, + KEY_DUMPSYS_DATA, + KEY_DUMPSYS_SYSTEM_UI, }; friend class AbilityStackManager; @@ -912,6 +928,8 @@ protected: void OnAppStateChanged(const AppInfo &info) override; private: + int TerminateAbilityWithFlag(const sptr &token, int resultCode = DEFAULT_INVAL_VALUE, + const Want *resultWant = nullptr, bool flag = true); /** * initialization of ability manager service. * @@ -932,6 +950,11 @@ private: * */ void StartingSettingsDataAbility(); + /** + * starting screen lock ability. + * + */ + void StartingScreenLockAbility(); /** * starting phone service ability. * @@ -950,12 +973,6 @@ private: */ void StartingContactsAbility(); - /** - * starting system ui ServiceExt abilites. - * - */ - void StartingSystemUiAbility(); - /** * starting mms ability. * @@ -967,11 +984,13 @@ private: * */ void ConnectBmsService(); + /** * get the user id. * */ int GetUserId(); + /** * Determine whether it is a system APP * @@ -1014,6 +1033,8 @@ private: MissionInfo &missionInfo); int32_t GetRemoteMissionSnapshotInfo(const std::string& deviceId, int32_t missionId, MissionSnapshot& missionSnapshot); + int StartRemoteAbilityByCall(const Want &want, const sptr &connect); + int ReleaseRemoteAbility(const sptr &connect, const AppExecFwk::ElementName &element); void DumpInner(const std::string &args, std::vector &info); void DumpStackListInner(const std::string &args, std::vector &info); @@ -1042,30 +1063,34 @@ private: const sptr &callerToken, int32_t &userId); - int CheckMultiOsAccount(const int32_t userId); + bool JudgeMultiUserConcurrency(const AppExecFwk::AbilityInfo &info, const int32_t userId); /** * dumpsys info * */ void DumpSysFuncInit(); void DumpSysInner( - const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId); + const std::string &args, std::vector &info, bool isClient, bool isUserID, int userId); void DumpSysMissionListInner( - const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId); + const std::string &args, std::vector &info, bool isClient, bool isUserID, int userId); void DumpSysAbilityInner( - const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId); + const std::string &args, std::vector &info, bool isClient, bool isUserID, int userId); void DumpSysStateInner( - const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId); + const std::string &args, std::vector &info, bool isClient, bool isUserID, int userId); void DumpSysPendingInner( - const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId); + const std::string &args, std::vector &info, bool isClient, bool isUserID, int userId); void DumpSysProcess( - const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId); + const std::string &args, std::vector &info, bool isClient, bool isUserID, int userId); + void DataDumpSysStateInner( + const std::string &args, std::vector &info, bool isClient, bool isUserID, int userId); + void SystemDumpSysStateInner( + const std::string &args, std::vector &info, bool isClient, bool isUserID, int userId); void InitConnectManager(int32_t userId, bool switchUser); void InitDataAbilityManager(int32_t userId, bool switchUser); void InitPendWantManager(int32_t userId, bool switchUser); - int32_t GetAbilityInfoFromExtension(const Want &want, AppExecFwk::AbilityInfo& abilityInfo); + int32_t GetAbilityInfoFromExtension(const Want &want, AppExecFwk::AbilityInfo& abilityInfo, const int32_t userId); int32_t InitAbilityInfoFromExtension(AppExecFwk::ExtensionAbilityInfo &extensionInfo, AppExecFwk::AbilityInfo &abilityInfo); int32_t ShowPickerDialog(const Want& want, int32_t userId); @@ -1077,7 +1102,7 @@ private: void SwitchToUser(int32_t userId); void StartLauncherAbility(int32_t userId); void SwitchToUser(int32_t oldUserId, int32_t userId); - void SwitchManagers(int32_t userId); + void SwitchManagers(int32_t userId, bool switchUser = true); void StartUserApps(int32_t userId); void StartSystemAbilityByUser(int32_t userId); void PauseOldUser(int32_t userId); @@ -1086,6 +1111,7 @@ private: bool IsSystemUI(const std::string &bundleName) const; bool VerificationAllToken(const sptr &token); + const std::shared_ptr &GetDataAbilityManager(const sptr &scheduler); bool CheckDataAbilityRequest(AbilityRequest &abilityRequest); std::shared_ptr GetStackManagerByUserId(int32_t userId); std::shared_ptr GetListManagerByUserId(int32_t userId); @@ -1096,10 +1122,12 @@ private: std::shared_ptr GetConnectManagerByToken(const sptr &token); std::shared_ptr GetDataAbilityManagerByToken(const sptr &token); - int32_t GetValidUserId(const Want &want, const int32_t userId); + int32_t GetValidUserId(const int32_t userId); int DelegatorMoveMissionToFront(int32_t missionId); + void StartupResidentProcess(); + using DumpFuncType = void (AbilityManagerService::*)(const std::string &args, std::vector &info); std::map dumpFuncMap_; @@ -1107,6 +1135,12 @@ private: const std::string& args, std::vector& state, bool isClient, bool isUserID, int UserID); std::map dumpsysFuncMap_; + int CheckStaticCfgPermission(AppExecFwk::AbilityInfo &abilityInfo); + void GrantUriPermission(const Want &want, int32_t validUserId); + bool VerifyUriPermisson(const AbilityRequest &abilityRequest, const Want &want); + + bool SetANRMissionByProcessID(int pid); + constexpr static int REPOLL_TIME_MICRO_SECONDS = 1000000; constexpr static int WAITING_BOOT_ANIMATION_TIMER = 5; @@ -1133,7 +1167,6 @@ private: bool useNewMission_ {false}; std::unordered_map> missionListManagers_; std::shared_ptr currentMissionListManager_; - std::shared_ptr kernalAbilityManager_; std::shared_ptr userController_; sptr abilityController_ = nullptr; bool controllerIsAStabilityTest_ = false; diff --git a/services/abilitymgr/include/ability_manager_stub.h b/services/abilitymgr/include/ability_manager_stub.h index 08bacb824caa2785704e9e4b3c9a011d17086494..448a262cf098f14e2968ecb5bf23bd584b459dfc 100644 --- a/services/abilitymgr/include/ability_manager_stub.h +++ b/services/abilitymgr/include/ability_manager_stub.h @@ -142,7 +142,7 @@ private: int CleanMissionInner(MessageParcel &data, MessageParcel &reply); int CleanAllMissionsInner(MessageParcel &data, MessageParcel &reply); int MoveMissionToFrontInner(MessageParcel &data, MessageParcel &reply); - + // for new version ability (call ability) int StartAbilityByCallInner(MessageParcel &data, MessageParcel &reply); int ReleaseInner(MessageParcel &data, MessageParcel &reply); @@ -170,6 +170,7 @@ private: int DoAbilityBackgroundInner(MessageParcel &data, MessageParcel &reply); int IsRunningInStabilityTestInner(MessageParcel &data, MessageParcel &reply); + int MoveMissionToFrontByOptionsInner(MessageParcel &data, MessageParcel &reply); using RequestFuncType = int (AbilityManagerStub::*)(MessageParcel &data, MessageParcel &reply); std::map requestFuncMap_; diff --git a/services/abilitymgr/include/ability_record.h b/services/abilitymgr/include/ability_record.h index 1753d77f382755f88166fd82da4dd5f61f2f8f47..e5e73f0345df1cd8b9d893009c8df9c39c44aa8a 100644 --- a/services/abilitymgr/include/ability_record.h +++ b/services/abilitymgr/include/ability_record.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -30,6 +30,7 @@ #include "app_scheduler.h" #include "application_info.h" #include "ability_record_info.h" +#include "bundlemgr/bundle_mgr_interface.h" #include "call_container.h" #include "lifecycle_deal.h" #include "lifecycle_state_info.h" @@ -666,11 +667,15 @@ public: */ void Dump(std::vector &info); + void DumpSys(std::vector &info, bool isClient = false); + + void DumpClientInfo(std::vector &info, bool isClient = false); + /** * dump ability state info. * */ - void DumpAbilityState(std::vector &info, bool isClient); + void DumpAbilityState(std::vector &info, bool isClient, const std::vector ¶ms); void SetStartTime(); @@ -755,7 +760,7 @@ public: void SetLaunchReason(const LaunchReason &reason); void SetLastExitReason(const LastExitReason &reason); void ContinueAbility(const std::string& deviceId); - void NotifyContinuationResult(const int32_t result); + void NotifyContinuationResult(int32_t result); std::shared_ptr GetOwnedMissionList() const; void SetUseNewMission(); @@ -802,6 +807,8 @@ private: */ void GetAbilityTypeString(std::string &typeStr); void OnSchedulerDied(const wptr &remote); + void GrantUriPermission(const Want &want); + int GetCurrentAccountId(); static int64_t abilityRecordId; int recordId_ = 0; // record id @@ -824,6 +831,7 @@ private: int requestCode_ = -1; // requestCode_: >= 0 for-result start mode; <0 for normal start mode in default. sptr schedulerDeathRecipient_ = {}; // scheduler binderDied Recipient + sptr iBundleManager_; /** * result_: ability starts with for-result mode will send result before being terminated. @@ -866,7 +874,7 @@ private: std::weak_ptr mission_; int32_t missionId_ = -1; bool isSwitchingPause_ = false; - + // new version std::shared_ptr callContainer_ = nullptr; bool isStartedByCall_ = false; diff --git a/services/abilitymgr/include/ability_scheduler_proxy.h b/services/abilitymgr/include/ability_scheduler_proxy.h index 7b505783d67ffed965163aa966fca4e500350af7..26e93b3e80d8bea367c0d788c8c6e65735eed9da 100644 --- a/services/abilitymgr/include/ability_scheduler_proxy.h +++ b/services/abilitymgr/include/ability_scheduler_proxy.h @@ -297,7 +297,7 @@ public: * @param The continuation result. * @return */ - void NotifyContinuationResult(const int32_t result) override; + void NotifyContinuationResult(int32_t result) override; /** * Dump Ability Runner info. @@ -305,7 +305,7 @@ public: * @param * @return Ability Runner info. */ - void DumpAbilityInfo(std::vector &info) override; + void DumpAbilityInfo(const std::vector ¶ms, std::vector &info) override; sptr CallRequest() override; private: diff --git a/services/abilitymgr/include/ability_util.h b/services/abilitymgr/include/ability_util.h index 3b6ab7c4066706a85e3acb0a714d644b06a06b58..ac3500dff9c84a3ae8a30f374994453c80746613 100755 --- a/services/abilitymgr/include/ability_util.h +++ b/services/abilitymgr/include/ability_util.h @@ -179,14 +179,6 @@ static sptr GetBundleManager() HILOG_DEBUG("%{public}s end", __func__); return ERR_OK; } - -inline bool IsSystemUiApp(const AppExecFwk::AbilityInfo &info) -{ - if (info.bundleName != AbilityConfig::SYSTEM_UI_BUNDLE_NAME) { - return false; - } - return (info.name == AbilityConfig::SYSTEM_UI_NAVIGATION_BAR || info.name == AbilityConfig::SYSTEM_UI_STATUS_BAR); -} } // namespace AbilityUtil } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/ams_configuration_parameter.h b/services/abilitymgr/include/ams_configuration_parameter.h index c2226e0748c06ab421d7cda2a137413f0f801fd3..a479e6cc4b5ccc390ed0dd4e3872a1f00f2b8aa6 100644 --- a/services/abilitymgr/include/ams_configuration_parameter.h +++ b/services/abilitymgr/include/ams_configuration_parameter.h @@ -29,6 +29,7 @@ const std::string AMS_CONFIG_FILE_PATH {"/system/etc/ams_service_config.json"}; const std::string SERVICE_ITEM_AMS {"service_startup_config"}; const std::string STARTUP_LAUNCHER {"startup_launcher"}; const std::string STARTUP_SETTINGS_DATA {"startup_settings_data"}; +const std::string STARTUP_SCREEN_LOCK {"startup_screen_lock"}; const std::string STARTUP_STATUS_BAR {"startup_system_ui_status_bar"}; const std::string STARTUP_NAVIGATION_BAR {"startup_system_ui_navigation_bar"}; const std::string STARTUP_PHONE_SERVICE {"startup_phone_service"}; @@ -64,6 +65,11 @@ public: * return false : ams do not start settings data */ bool GetStartSettingsDataState() const; + /** + * return true : ams can start screen lock + * return false : ams do not start screen lock + */ + bool GetStartScreenLockState() const; /** * return true : ams can start system ui status bar * return false : ams do not start system ui status bar @@ -140,6 +146,7 @@ private: bool nonConfigFile_ {false}; bool canStartLauncher_ {false}; bool canStartSettingsData_ {false}; + bool canStartScreenLock_ {false}; bool canStartUiStatusBar_ {false}; bool canStartUiNavigationBar_ {false}; bool canStartPhoneService_ {false}; diff --git a/services/abilitymgr/include/app_scheduler.h b/services/abilitymgr/include/app_scheduler.h index 1a4382adbc0b412bdf4f5a16b000bbce8bc2ac7b..9f3b1acde5871b6451eca2d04754f313d892e221 100644 --- a/services/abilitymgr/include/app_scheduler.h +++ b/services/abilitymgr/include/app_scheduler.h @@ -115,10 +115,12 @@ public: * @param preToken, the token of ability's caller. * @param abilityinfo, ability info. * @param application, application info. + * @param want ability want * @return true on success ,false on failure. */ int LoadAbility(const sptr &token, const sptr &preToken, - const AppExecFwk::AbilityInfo &abilityinfo, const AppExecFwk::ApplicationInfo &application); + const AppExecFwk::AbilityInfo &abilityinfo, const AppExecFwk::ApplicationInfo &application, + const Want &want); /** * terminate ability with token. @@ -265,6 +267,15 @@ public: int GetConfiguration(AppExecFwk::Configuration &config); + /** + * Get the token of ability records by process ID. + * + * @param pid The process id. + * @param tokens The token of ability records. + * @return Returns true on success, others on failure. + */ + int GetAbilityRecordsByProcessID(const int pid, std::vector> &tokens); + protected: /** * OnAbilityRequestDone, app manager service call this interface after ability request done. diff --git a/services/abilitymgr/include/call_container.h b/services/abilitymgr/include/call_container.h index 725d6552e09341054de5101ab9904d0bf54090c8..84313aa196769c09baafb223fe284a4f4a95cc88 100644 --- a/services/abilitymgr/include/call_container.h +++ b/services/abilitymgr/include/call_container.h @@ -1,65 +1,65 @@ -/* - * 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 OHOS_AAFWK_CALL_CONTAINER_H -#define OHOS_AAFWK_CALL_CONTAINER_H - -#include -#include -#include - -#include "ability_connect_callback_interface.h" -#include "call_record.h" -#include "element_name.h" -#include "iremote_object.h" -#include "nocopyable.h" - -namespace OHOS { -namespace AAFwk { -class CallRecord; -/** - * @class CallContainer - * CallContainer provides a facility for managing the call records of ability. - */ -class CallContainer : public std::enable_shared_from_this { -public: - using CallMapType = std::map, std::shared_ptr>; - using RecipientMapType = std::map, sptr>; - - CallContainer(); - virtual ~CallContainer(); - - void AddCallRecord(const sptr & connect, const std::shared_ptr& callRecord); - std::shared_ptr GetCallRecord(const sptr & connect) const; - bool RemoveCallRecord(const sptr & connect); - bool CallRequestDone(const sptr & callStub); - void Dump(std::vector &info, const std::string &args = "") const; - bool IsNeedToCallRequest() const; - -private: - void RemoveConnectDeathRecipient(const sptr &connect); - void AddConnectDeathRecipient(const sptr &connect); - void OnConnectionDied(const wptr & remote); - -private: - CallMapType callRecordMap_; - RecipientMapType deathRecipientMap_; - - DISALLOW_COPY_AND_MOVE(CallContainer); -}; -} // namespace AAFwk -} // namespace OHOS -#endif // OHOS_AAFWK_CALL_CONTAINER_H - +/* + * 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 OHOS_AAFWK_CALL_CONTAINER_H +#define OHOS_AAFWK_CALL_CONTAINER_H + +#include +#include +#include + +#include "ability_connect_callback_interface.h" +#include "call_record.h" +#include "element_name.h" +#include "iremote_object.h" +#include "nocopyable.h" + +namespace OHOS { +namespace AAFwk { +class CallRecord; +/** + * @class CallContainer + * CallContainer provides a facility for managing the call records of ability. + */ +class CallContainer : public std::enable_shared_from_this { +public: + using CallMapType = std::map, std::shared_ptr>; + using RecipientMapType = std::map, sptr>; + + CallContainer(); + virtual ~CallContainer(); + + void AddCallRecord(const sptr & connect, const std::shared_ptr& callRecord); + std::shared_ptr GetCallRecord(const sptr & connect) const; + bool RemoveCallRecord(const sptr & connect); + bool CallRequestDone(const sptr & callStub); + void Dump(std::vector &info) const; + bool IsNeedToCallRequest() const; + +private: + void RemoveConnectDeathRecipient(const sptr &connect); + void AddConnectDeathRecipient(const sptr &connect); + void OnConnectionDied(const wptr & remote); + +private: + CallMapType callRecordMap_; + RecipientMapType deathRecipientMap_; + + DISALLOW_COPY_AND_MOVE(CallContainer); +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_CALL_CONTAINER_H + diff --git a/services/abilitymgr/include/data_ability_manager.h b/services/abilitymgr/include/data_ability_manager.h index 13b5a91517eeeac46a211aa551501b9ec304fcc2..a3561ea6511e479fe93d7a4c387de7af0ab2cbf9 100644 --- a/services/abilitymgr/include/data_ability_manager.h +++ b/services/abilitymgr/include/data_ability_manager.h @@ -47,7 +47,9 @@ public: std::shared_ptr GetAbilityRecordByScheduler(const sptr &scheduler); void Dump(const char *func, int line); void DumpState(std::vector &info, const std::string &args = "") const; + void DumpSysState(std::vector &info, bool isClient = false, const std::string &args = "") const; void GetAbilityRunningInfos(std::vector &info); + bool ContainsDataAbility(const sptr &scheduler); private: using DataAbilityRecordPtr = std::shared_ptr; diff --git a/services/abilitymgr/include/inner_mission_info.h b/services/abilitymgr/include/inner_mission_info.h index 5733c8d50d876ddeb1be3a48098ccd40eaef98d1..faec076413295cd66f39b6c6a45b0f129c191040 100644 --- a/services/abilitymgr/include/inner_mission_info.h +++ b/services/abilitymgr/include/inner_mission_info.h @@ -42,7 +42,7 @@ struct InnerMissionInfo { bool isSingletonMode; std::string ToJsonStr() const; - void FromJsonStr(const std::string &jsonStr); + bool FromJsonStr(const std::string &jsonStr); void Dump(std::vector &info) const; }; } // namespace AAFwk diff --git a/services/abilitymgr/include/kernal_ability_manager.h b/services/abilitymgr/include/kernal_ability_manager.h deleted file mode 100644 index dd1ec48af3479ab646a32644bba386d48f7674fb..0000000000000000000000000000000000000000 --- a/services/abilitymgr/include/kernal_ability_manager.h +++ /dev/null @@ -1,166 +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 OHOS_AAFWK_KERNAL_ABILITY_MANAGER_H -#define OHOS_AAFWK_KERNAL_ABILITY_MANAGER_H - -#include -#include - -#include "ability_record.h" -#include "ability_running_info.h" -#include "want.h" - -namespace OHOS { -namespace AAFwk { -/** - * @class KernalAbilityManager - * KernalAbilityManager provides a facility for managing systerm ability life cycle. - */ -class KernalAbilityManager : public std::enable_shared_from_this { -public: - explicit KernalAbilityManager(int userId); - ~KernalAbilityManager(); - - /** - * init kernal ability manager. - * - */ - void Init(); - /** - * StartAbility with request. - * - * @param abilityRequest, the request of the ability to start. - * @return Returns ERR_OK on success, others on failure. - */ - int StartAbility(const AbilityRequest &abilityRequest); - /** - * attach ability thread ipc object. - * - * @param scheduler, ability thread ipc object. - * @param token, the token of ability. - * @return Returns ERR_OK on success, others on failure. - */ - int AttachAbilityThread(const sptr &scheduler, const sptr &token); - /** - * AbilityTransitionDone, ability call this interface after lift cycle was changed. - * - * @param token,.ability's token. - * @param state,.the state of ability lift cycle. - * @return Returns ERR_OK on success, others on failure. - */ - int AbilityTransitionDone(const sptr &token, int state); - /** - * OnAbilityRequestDone, app manager service call this interface after ability request done. - * - * @param token,ability's token. - * @param state,the state of ability lift cycle. - */ - void OnAbilityRequestDone(const sptr &token, const int32_t state); - - void OnAppStateChanged(const AppInfo &info); - - /** - * get manager's user id. - */ - int GetManagerUserId() const; - - void DumpState(std::vector &info); - - void OnAbilityDied(std::shared_ptr abilityRecord); - - void OnTimeOut(uint32_t msgId, int64_t eventId); - - /** - * get the ability record by token. - * - * @return abilityRecord, target ability. - */ - std::shared_ptr GetAbilityRecordByToken(const sptr &token); - - void RestartAbility(const std::shared_ptr abilityRecord); - - void GetAbilityRunningInfos(std::vector &info); - -private: - /** - * StartAbilityLocked. - * - * @param abilityRequest the request of the ability to start. - * @return Returns ERR_OK on success, others on failure. - */ - int StartAbilityLocked(const AbilityRequest &abilityRequest); - /** - * push waitting ability to queue. - * - * @param abilityRequest, the request of ability. - */ - void EnqueueWaittingAbility(const AbilityRequest &abilityRequest); - /** - * pop waitting ability. - * - */ - void DequeueWaittingAbility(); - /** - * get current top ability of stack. - * - * @return top ability record. - */ - std::shared_ptr GetCurrentTopAbility() const; - /** - * get or create the target ability record of system app. - * - * @param abilityRequest, the request of ability. - * @param targetAbility, target ability record. - */ - void GetOrCreateAbilityRecord(const AbilityRequest &abilityRequest, std::shared_ptr &targetAbility); - /** - * get the flag of the target ability record. - * - * @param bundleName, target bundleName. - * @param abilityName, target ability name. - */ - static std::string GetFlagOfAbility(const std::string &bundleName, const std::string &abilityName); - /** - * get the ability record by eventId. - * - * @return abilityRecord, target ability. - */ - std::shared_ptr GetAbilityRecordByEventId(const int64_t eventId) const; - /** - * dispatch ability life cycle . - * - * @param abilityRecord. - * @param state. - */ - int DispatchForeground(const std::shared_ptr &abilityRecord, int state); - /** - * complete ability life cycle . - * - * @param abilityRecord. - */ - void CompleteForeground(const std::shared_ptr &abilityRecord); - - bool RemoveAbilityRecord(std::shared_ptr ability); - -private: - std::recursive_mutex stackLock_; - std::list> abilities_; - std::queue waittingAbilityQueue_; - int userId_; -}; -} // namespace AAFwk -} // namespace OHOS -#endif // OHOS_AAFWK_KERNAL_ABILITY_MANAGER_H diff --git a/services/abilitymgr/include/kernal_system_app_manager.h b/services/abilitymgr/include/kernal_system_app_manager.h index 55f2663ad99ead278eaf1e77aa42c6169a437741..eb30240281ad46de6d5411a11099491cfd2ab805 100644 --- a/services/abilitymgr/include/kernal_system_app_manager.h +++ b/services/abilitymgr/include/kernal_system_app_manager.h @@ -79,6 +79,8 @@ public: void DumpState(std::vector &info); + void DumpSysState(std::vector &info, bool isClient = false); + void OnAbilityDied(std::shared_ptr abilityRecord); void OnTimeOut(uint32_t msgId, int64_t eventId); diff --git a/services/abilitymgr/include/lifecycle_deal.h b/services/abilitymgr/include/lifecycle_deal.h index dfca7756eda6849fc118f0ba3d21d6a97f5d7dfe..2d894433ff1c29d420d918b1249f19c81a7f8676 100644 --- a/services/abilitymgr/include/lifecycle_deal.h +++ b/services/abilitymgr/include/lifecycle_deal.h @@ -58,7 +58,7 @@ public: void ForegroundNew(const Want &want, LifeCycleStateInfo &stateInfo); void BackgroundNew(const Want &want, LifeCycleStateInfo &stateInfo); void ContinueAbility(const std::string& deviceId); - void NotifyContinuationResult(const int32_t result); + void NotifyContinuationResult(int32_t result); private: sptr GetScheduler(); diff --git a/services/abilitymgr/include/mission.h b/services/abilitymgr/include/mission.h index 0005acc6f67f420f3382e474b23fd82f9b3817c4..899311b5a2747359fe1bc15df881b7e01bda4da9 100644 --- a/services/abilitymgr/include/mission.h +++ b/services/abilitymgr/include/mission.h @@ -103,6 +103,16 @@ public: */ bool IsMovingState() const; + /** + * @brief Set application not response state true + */ + void SetANRState(); + + /** + * @brief Is application not response state + */ + bool IsANRState() const; + /** * @brief dump mission * @@ -117,6 +127,7 @@ private: std::weak_ptr ownerMissionList_; bool lockedState_ = false; bool isMovingToFront_ = false; + bool isANRState_ = false; }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/mission_data_storage.h b/services/abilitymgr/include/mission_data_storage.h index 5b7098c9b5e11807eac0e18e2506dc8021c3798d..b07f556e528283b156084b1e981e28fd2bd18105 100644 --- a/services/abilitymgr/include/mission_data_storage.h +++ b/services/abilitymgr/include/mission_data_storage.h @@ -63,7 +63,7 @@ public: * @param missionId Indicates this mission id. * @param missionSnapshot the mission snapshot to save */ - void SaveMissionSnapshot(int missionId, const MissionSnapshot& missionSnapshot); + void SaveMissionSnapshot(int32_t missionId, const MissionSnapshot& missionSnapshot); /** * @brief Delete mission snapshot @@ -77,22 +77,32 @@ public: * @param missionSnapshot * @return Returns true if this function is successfully called; returns false otherwise. */ - bool GetMissionSnapshot(int missionId, MissionSnapshot& missionSnapshot); + bool GetMissionSnapshot(int32_t missionId, MissionSnapshot& missionSnapshot); private: std::string GetMissionDataDirPath(); std::string GetMissionDataFilePath(int missionId); - std::string GetMissionSnapshotPath(int missionId); + std::string GetMissionSnapshotPath(int32_t missionId); bool CheckFileNameValid(const std::string &fileName); bool WriteToPng(const char* fileName, uint32_t width, uint32_t height, const uint8_t* data); + bool GetCachedSnapshot(int32_t missionId, MissionSnapshot& missionSnapshot); + + bool SaveCachedSnapshot(int32_t missionId, const MissionSnapshot& missionSnapshot); + + bool DeleteCachedSnapshot(int32_t missionId); + + void SaveSnapshotFile(int32_t missionId, const MissionSnapshot& missionSnapshot); + private: int userId_ = 0; std::shared_ptr handler_; + std::mutex cachedPixelMapMutex_; + std::map> cachedPixelMap_; }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/mission_list.h b/services/abilitymgr/include/mission_list.h index ca093f4dca82080e320e19ea6fc125777d6e788b..30b4140bdccb8cc55bb67d272d8929f197d6595f 100644 --- a/services/abilitymgr/include/mission_list.h +++ b/services/abilitymgr/include/mission_list.h @@ -174,7 +174,9 @@ public: * @param info dump result. */ void DumpList(std::vector &info, bool isClient); - void DumpStateByRecordId(std::vector &info, bool isClient, int32_t abilityRecordId); + + void DumpStateByRecordId( + std::vector &info, bool isClient, int32_t abilityRecordId, const std::vector ¶ms); std::shared_ptr GetMissionBySpecifiedFlag(const std::string &flag) const; private: diff --git a/services/abilitymgr/include/mission_list_manager.h b/services/abilitymgr/include/mission_list_manager.h index 4d10b727bce43506c82cb57ced12cb20ca4c565c..7c6a82afa40e0c98b38da771e8b8711735fe3948 100644 --- a/services/abilitymgr/include/mission_list_manager.h +++ b/services/abilitymgr/include/mission_list_manager.h @@ -27,6 +27,7 @@ #include "mission_info.h" #include "mission_snapshot.h" #include "snapshot.h" +#include "start_options.h" #include "want.h" namespace OHOS { @@ -67,9 +68,10 @@ public: int GetMissionInfo(int32_t missionId, MissionInfo &missionInfo); - int MoveMissionToFront(int32_t missionId); + int MoveMissionToFront(int32_t missionId, std::shared_ptr startOptions = nullptr); - int MoveMissionToFront(int32_t missionId, bool isCallerFromLauncher); + int MoveMissionToFront(int32_t missionId, bool isCallerFromLauncher, + std::shared_ptr startOptions = nullptr); /** * OnAbilityRequestDone, app manager service call this interface after ability request done. @@ -79,6 +81,8 @@ public: */ void OnAbilityRequestDone(const sptr &token, const int32_t state); + void OnAppStateChanged(const AppInfo &info); + /** * attach ability thread ipc object. * @@ -122,10 +126,11 @@ public: * @param abilityRecord the ability to terminate * @param resultCode the terminate data * @param resultWant the terminate data + * @param flag mark terminate flag * @return int error code */ int TerminateAbility(const std::shared_ptr &abilityRecord, - int resultCode, const Want *resultWant); + int resultCode, const Want *resultWant, bool flag); /** * @brief Terminate ability with caller @@ -140,8 +145,9 @@ public: * @brief remove the mission from the mission list * * @param abilityRecord the ability need to remove + * @param flag mark is terminate or close */ - void RemoveTerminatingAbility(const std::shared_ptr &abilityRecord); + void RemoveTerminatingAbility(const std::shared_ptr &abilityRecord, bool flag); /** * @brief remove the mission list from the mission list manager @@ -262,7 +268,14 @@ public: */ void DumpMissionList(std::vector &info, bool isClient, const std::string &args = ""); - void DumpMissionListByRecordId(std::vector &info, bool isClient, int32_t abilityRecordId); + /** + * @brief dump mission list by id with params + * + * @param info dump result. + * @param params dump params. + */ + void DumpMissionListByRecordId( + std::vector& info, bool isClient, int32_t abilityRecordId, const std::vector& params); /** * @brief dump mission by id @@ -294,7 +307,6 @@ public: * @param element, target ability name. */ int ReleaseLocked(const sptr &connect, const AppExecFwk::ElementName &element); - /** * @brief register snapshotHandler * @param handler the snapshotHandler @@ -354,7 +366,7 @@ private: bool RemoveMissionList(const std::list> lists, const std::shared_ptr &list); int ClearMissionLocked(int missionId, std::shared_ptr mission); - int TerminateAbilityLocked(const std::shared_ptr &abilityRecord); + int TerminateAbilityLocked(const std::shared_ptr &abilityRecord, bool flag); std::shared_ptr GetAbilityRecordByEventId(int64_t eventId) const; std::shared_ptr GetAbilityRecordByCaller( const std::shared_ptr &caller, int requestCode); @@ -369,7 +381,6 @@ private: void GetAllForegroundAbilities(std::list>& foregroundList); void GetForegroundAbilities(const std::shared_ptr& missionList, std::list>& foregroundList); - bool IsPC(); std::shared_ptr GetMissionBySpecifiedFlag(const std::string &flag) const; void HandleLoadTimeout(const std::shared_ptr &ability); @@ -379,6 +390,7 @@ private: int ResolveAbility(const std::shared_ptr &targetAbility, const AbilityRequest &abilityRequest); std::shared_ptr GetAbilityRecordByName(const AppExecFwk::ElementName &element); int CallAbilityLocked(const AbilityRequest &abilityRequest); + void UpdateMissionSnapshot(const std::shared_ptr& abilityRecord); private: int userId_; diff --git a/services/abilitymgr/include/pending_want_manager.h b/services/abilitymgr/include/pending_want_manager.h index b12cbef86a8f58bac17a474cd9f3d0940c6794de..55852046f41d0d826e3ed4d9318a7afcf3a8b0e4 100644 --- a/services/abilitymgr/include/pending_want_manager.h +++ b/services/abilitymgr/include/pending_want_manager.h @@ -159,6 +159,7 @@ public: void ClearPendingWantRecord(const std::string &bundleName); void Dump(std::vector &info); + void DumpByRecordId(std::vector &info, const std::string &args); private: sptr GetWantSenderLocked(const int32_t callingUid, const int32_t uid, const int32_t userId, diff --git a/services/abilitymgr/include/user_controller.h b/services/abilitymgr/include/user_controller.h index fa08f4771853657426d5402da3fc2276fca62dfb..de5adfbcd73416d49b7d6c9568c72da77e93c056 100644 --- a/services/abilitymgr/include/user_controller.h +++ b/services/abilitymgr/include/user_controller.h @@ -18,7 +18,6 @@ #include #include -#include #include "user_event_handler.h" @@ -120,10 +119,10 @@ private: private: std::recursive_mutex userLock_; - int32_t currentUserId_ = USER_ID_DEFAULT; + int32_t currentUserId_ = USER_ID_NO_HEAD; std::unordered_map> userItems_; std::shared_ptr eventHandler_; }; } // namespace AAFwk } // namespace OHOS -#endif // OHOS_AAFWK_USER_CONTROLLER_H \ No newline at end of file +#endif // OHOS_AAFWK_USER_CONTROLLER_H diff --git a/services/abilitymgr/resource/ams_service_config.json b/services/abilitymgr/resource/ams_service_config.json index a557159ea950b684fbd1ab70d82f786b7ecfdc7a..dae4d3c5a1cf274175ae31df02557580b212ebed 100644 --- a/services/abilitymgr/resource/ams_service_config.json +++ b/services/abilitymgr/resource/ams_service_config.json @@ -2,6 +2,7 @@ "service_startup_config":{ "startup_launcher":true, "startup_settings_data": true, + "startup_screen_lock" : true, "startup_system_ui_status_bar" : true, "startup_system_ui_navigation_bar" : true, "startup_phone_service" : true, diff --git a/services/abilitymgr/src/ability_connect_manager.cpp b/services/abilitymgr/src/ability_connect_manager.cpp index f56e06fac78b8f7683eaf393e7b2dcddf917f75f..1fe56f890a166d8c1e8d34f645a6f8b9c263fe51 100755 --- a/services/abilitymgr/src/ability_connect_manager.cpp +++ b/services/abilitymgr/src/ability_connect_manager.cpp @@ -403,13 +403,23 @@ int AbilityConnectManager::AbilityTransitionDone(const sptr &toke switch (state) { case AbilityState::INACTIVE: { - DelayedSingleton::GetInstance()->UpdateExtensionState( - token, AppExecFwk::ExtensionState::EXTENSION_STATE_CREATE); + if (abilityRecord->GetAbilityInfo().type == AbilityType::SERVICE) { + DelayedSingleton::GetInstance()->UpdateAbilityState( + token, AppExecFwk::AbilityState::ABILITY_STATE_CREATE); + } else { + DelayedSingleton::GetInstance()->UpdateExtensionState( + token, AppExecFwk::ExtensionState::EXTENSION_STATE_CREATE); + } return DispatchInactive(abilityRecord, state); } case AbilityState::INITIAL: { - DelayedSingleton::GetInstance()->UpdateExtensionState( - token, AppExecFwk::ExtensionState::EXTENSION_STATE_TERMINATED); + if (abilityRecord->GetAbilityInfo().type == AbilityType::SERVICE) { + DelayedSingleton::GetInstance()->UpdateAbilityState( + token, AppExecFwk::AbilityState::ABILITY_STATE_TERMINATED); + } else { + DelayedSingleton::GetInstance()->UpdateExtensionState( + token, AppExecFwk::ExtensionState::EXTENSION_STATE_TERMINATED); + } return DispatchTerminate(abilityRecord); } default: { @@ -438,8 +448,13 @@ int AbilityConnectManager::ScheduleConnectAbilityDoneLocked( return INVALID_CONNECTION_STATE; } - DelayedSingleton::GetInstance()->UpdateExtensionState( - token, AppExecFwk::ExtensionState::EXTENSION_STATE_CONNECTED); + if (abilityRecord->GetAbilityInfo().type == AbilityType::SERVICE) { + DelayedSingleton::GetInstance()->UpdateAbilityState( + token, AppExecFwk::AbilityState::ABILITY_STATE_CONNECTED); + } else { + DelayedSingleton::GetInstance()->UpdateExtensionState( + token, AppExecFwk::ExtensionState::EXTENSION_STATE_CONNECTED); + } abilityRecord->SetConnRemoteObject(remoteObject); // There may be multiple callers waiting for the connection result @@ -466,8 +481,13 @@ int AbilityConnectManager::ScheduleDisconnectAbilityDoneLocked(const sptr::GetInstance()->UpdateExtensionState( - token, AppExecFwk::ExtensionState::EXTENSION_STATE_DISCONNECTED); + if (abilityRecord->GetAbilityInfo().type == AbilityType::SERVICE) { + DelayedSingleton::GetInstance()->UpdateAbilityState( + token, AppExecFwk::AbilityState::ABILITY_STATE_DISCONNECTED); + } else { + DelayedSingleton::GetInstance()->UpdateExtensionState( + token, AppExecFwk::ExtensionState::EXTENSION_STATE_DISCONNECTED); + } std::string element = abilityRecord->GetWant().GetElement().GetURI(); HILOG_INFO("disconnect ability done with service %{public}s", element.c_str()); @@ -586,7 +606,8 @@ void AbilityConnectManager::LoadAbility(const std::shared_ptr &ab } } DelayedSingleton::GetInstance()->LoadAbility( - token, perToken, abilityRecord->GetAbilityInfo(), abilityRecord->GetApplicationInfo()); + token, perToken, abilityRecord->GetAbilityInfo(), abilityRecord->GetApplicationInfo(), + abilityRecord->GetWant()); abilityRecord->SetStartTime(); } diff --git a/services/abilitymgr/src/ability_manager_client.cpp b/services/abilitymgr/src/ability_manager_client.cpp index ec19bb5290a81717b830a017248cf65c3f139963..ea6b4073118feef2e8dfdd678bf9e579f2a1384a 100644 --- a/services/abilitymgr/src/ability_manager_client.cpp +++ b/services/abilitymgr/src/ability_manager_client.cpp @@ -165,6 +165,13 @@ ErrCode AbilityManagerClient::TerminateAbilityResult(const sptr & return abms->TerminateAbilityResult(token, startId); } +ErrCode AbilityManagerClient::CloseAbility(const sptr &token, int resultCode, const Want *resultWant) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + sptr abms = iface_cast(remoteObject_); + return abms->CloseAbility(token, resultCode, resultWant); +} + ErrCode AbilityManagerClient::MinimizeAbility(const sptr &token, bool fromUser) { CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); @@ -273,7 +280,7 @@ ErrCode AbilityManagerClient::GetMissionSnapshot(const int32_t missionId, Missio int ret = abms->GetMissionSnapshot(missionId, missionPixelMap); if (ret == ERR_OK) { HILOG_INFO("missionPixelMap.imageInfo.shmKey: %{public}d", missionPixelMap.imageInfo.shmKey); - if (0 == missionPixelMap.imageInfo.size) { + if (missionPixelMap.imageInfo.size == 0) { HILOG_INFO("size is 0."); return -1; } @@ -287,8 +294,8 @@ ErrCode AbilityManagerClient::GetMissionSnapshot(const int32_t missionId, Missio mediaOption.size.height = missionPixelMap.imageInfo.height; mediaOption.pixelFormat = Media::PixelFormat::BGRA_8888; mediaOption.editable = true; - auto pixel = - Media::PixelMap::Create((const uint32_t *)data, missionPixelMap.imageInfo.size / sizeof(uint32_t), mediaOption); + auto pixel = Media::PixelMap::Create((const uint32_t *)data, + missionPixelMap.imageInfo.size / sizeof(uint32_t), mediaOption); if (!pixel) { HILOG_INFO(" Media::PixelMap::Create return value is nullptr."); return -1; @@ -772,6 +779,14 @@ ErrCode AbilityManagerClient::MoveMissionToFront(int32_t missionId) return abms->MoveMissionToFront(missionId); } +ErrCode AbilityManagerClient::MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + + sptr abms = iface_cast(remoteObject_); + return abms->MoveMissionToFront(missionId, startOptions); +} + ErrCode AbilityManagerClient::StartAbilityByCall( const Want &want, const sptr &connect, const sptr &callToken) { @@ -924,5 +939,22 @@ ErrCode AbilityManagerClient::DoAbilityBackground(const sptr &tok sptr abms = iface_cast(remoteObject_); return abms->DoAbilityBackground(token, flag); } + +ErrCode AbilityManagerClient::SetAbilityController(const sptr &abilityController, + bool imAStabilityTest) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + + sptr abms = iface_cast(remoteObject_); + return abms->SetAbilityController(abilityController, imAStabilityTest); +} + +ErrCode AbilityManagerClient::SendANRProcessID(int pid) +{ + CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); + + sptr abms = iface_cast(remoteObject_); + return abms->SendANRProcessID(pid); +} } // namespace AAFwk } // namespace AAFwk diff --git a/services/abilitymgr/src/ability_manager_proxy.cpp b/services/abilitymgr/src/ability_manager_proxy.cpp index 86db7a562d30993b0ea3aef66f6128bfe7644063..51742b52d3347038e0c1d8c5b74bd7e8598a781a 100644 --- a/services/abilitymgr/src/ability_manager_proxy.cpp +++ b/services/abilitymgr/src/ability_manager_proxy.cpp @@ -15,10 +15,6 @@ #include "ability_manager_proxy.h" -#include -#include -#include - #include "errors.h" #include "string_ex.h" @@ -185,6 +181,12 @@ int AbilityManagerProxy::StartAbility(const Want &want, const StartOptions &star } int AbilityManagerProxy::TerminateAbility(const sptr &token, int resultCode, const Want *resultWant) +{ + return TerminateAbility(token, resultCode, resultWant, true); +} + +int AbilityManagerProxy::TerminateAbility(const sptr &token, + int resultCode, const Want *resultWant, bool flag) { int error; MessageParcel data; @@ -198,6 +200,10 @@ int AbilityManagerProxy::TerminateAbility(const sptr &token, int HILOG_ERROR("data write failed."); return INNER_ERR; } + if (!data.WriteBool(flag)) { + HILOG_ERROR("data write flag failed."); + return INNER_ERR; + } error = Remote()->SendRequest(IAbilityManager::TERMINATE_ABILITY, data, reply, option); if (error != NO_ERROR) { HILOG_ERROR("Send request error: %{public}d", error); @@ -228,6 +234,11 @@ int AbilityManagerProxy::TerminateAbilityByCaller(const sptr &cal return reply.ReadInt32(); } +int AbilityManagerProxy::CloseAbility(const sptr &token, int resultCode, const Want *resultWant) +{ + return TerminateAbility(token, resultCode, resultWant, false); +} + int AbilityManagerProxy::ConnectAbility( const Want &want, const sptr &connect, const sptr &callerToken, int32_t userId) { @@ -1092,7 +1103,7 @@ bool AbilityManagerProxy::IsFirstInMission(const sptr &token) MessageOption option; if (!WriteInterfaceToken(data)) { - return INNER_ERR; + return false; } if (!data.WriteParcelable(token)) { HILOG_ERROR("token write failed."); @@ -1721,7 +1732,7 @@ void AbilityManagerProxy::NotifyCompleteContinuation(const std::string &deviceId } } -int AbilityManagerProxy::NotifyContinuationResult(int32_t missionId, const int32_t result) +int AbilityManagerProxy::NotifyContinuationResult(int32_t missionId, int32_t result) { MessageParcel data; MessageParcel reply; @@ -1996,6 +2007,32 @@ int AbilityManagerProxy::MoveMissionToFront(int32_t missionId) return reply.ReadInt32(); } +int AbilityManagerProxy::MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + if (!data.WriteInt32(missionId)) { + HILOG_ERROR("move mission to front , WriteInt32 fail."); + return ERR_INVALID_VALUE; + } + if (!data.WriteParcelable(&startOptions)) { + HILOG_ERROR("startOptions write failed."); + return INNER_ERR; + } + error = Remote()->SendRequest(IAbilityManager::MOVE_MISSION_TO_FRONT_BY_OPTIONS, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("move mission to front, SendRequest error: %d", error); + return error; + } + return reply.ReadInt32(); +} + int AbilityManagerProxy::StartUser(int userId) { int error; @@ -2555,25 +2592,24 @@ int AbilityManagerProxy::DoAbilityBackground(const sptr &token, u return reply.ReadInt32(); } -bool AbilityManagerProxy::SendANRProcessID(int pid) +int AbilityManagerProxy::SendANRProcessID(int pid) { - int error; MessageParcel data; MessageParcel reply; MessageOption option; if (!WriteInterfaceToken(data)) { - return false; + return INNER_ERR; } if (!data.WriteInt32(pid)) { HILOG_ERROR("pid WriteInt32 fail."); - return false; + return ERR_INVALID_VALUE; } - error = Remote()->SendRequest(IAbilityManager::SEND_APP_NOT_RESPONSE_PROCESS_ID, data, reply, option); + auto error = Remote()->SendRequest(IAbilityManager::SEND_APP_NOT_RESPONSE_PROCESS_ID, data, reply, option); if (error != NO_ERROR) { HILOG_ERROR("SendANRProcessID error: %d", error); - return false; + return error; } - return reply.ReadBool(); + return reply.ReadInt32(); } } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_manager_service.cpp b/services/abilitymgr/src/ability_manager_service.cpp index c5f6b6a3168336b3210c7e8881f9389f423cc7b1..b27d0736ae8da87d42039c7eae7232acfcd670e5 100644 --- a/services/abilitymgr/src/ability_manager_service.cpp +++ b/services/abilitymgr/src/ability_manager_service.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,6 +14,7 @@ */ #include "ability_manager_service.h" +#include "accesstoken_kit.h" #include #include @@ -47,20 +48,23 @@ #include "os_account_manager.h" #include "png.h" #include "ui_service_mgr_client.h" +#include "uri_permission_manager_client.h" #include "xcollie/watchdog.h" using OHOS::AppExecFwk::ElementName; +using OHOS::Security::AccessToken::AccessTokenKit; namespace OHOS { namespace AAFwk { using namespace std::chrono; +const bool CONCURRENCY_MODE_FALSE = false; const int32_t MAIN_USER_ID = 100; const int32_t U0_USER_ID = 0; +constexpr int32_t INVALID_USER_ID = -1; 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 = ""; @@ -109,6 +113,10 @@ const std::map AbilityManagerSer std::map::value_type("-p", KEY_DUMPSYS_PENDING), std::map::value_type("--process", KEY_DUMPSYS_PROCESS), std::map::value_type("-r", KEY_DUMPSYS_PROCESS), + std::map::value_type("--data", KEY_DUMPSYS_DATA), + std::map::value_type("-d", KEY_DUMPSYS_DATA), + std::map::value_type("--ui", KEY_DUMPSYS_SYSTEM_UI), + std::map::value_type("-k", KEY_DUMPSYS_SYSTEM_UI), }; const bool REGISTER_RESULT = @@ -185,10 +193,8 @@ bool AbilityManagerService::Init() CHECK_POINTER_RETURN_BOOL(systemAppManager_); InitMissionListManager(userId, true); - kernalAbilityManager_ = std::make_shared(0); - CHECK_POINTER_RETURN_BOOL(kernalAbilityManager_); - InitU0User(); + SwitchManagers(U0_USER_ID, false); int amsTimeOut = amsConfigResolver_->GetAMSTimeOutTime(); if (HiviewDFX::Watchdog::GetInstance().AddThread("AMSWatchdog", handler_, amsTimeOut) != 0) { HILOG_ERROR("HiviewDFX::Watchdog::GetInstance AddThread Fail"); @@ -216,16 +222,6 @@ bool AbilityManagerService::Init() return true; } -void AbilityManagerService::InitU0User() -{ - InitConnectManager(U0_USER_ID, false); - InitDataAbilityManager(U0_USER_ID, false); - InitPendWantManager(U0_USER_ID, false); - SetStackManager(U0_USER_ID, false); - InitMissionListManager(U0_USER_ID, false); -} - - void AbilityManagerService::OnStop() { HILOG_INFO("Stop service."); @@ -267,25 +263,42 @@ int AbilityManagerService::StartAbilityInner(const Want &want, const sptr(abilityInfo.applicationInfo.singleUser)); + + if (!JudgeMultiUserConcurrency(abilityRequest.abilityInfo, validUserId)) { + HILOG_ERROR("Multi-user non-concurrent mode is not satisfied."); + return ERR_INVALID_VALUE; + } + + result = CheckStaticCfgPermission(abilityInfo); + if (result != AppExecFwk::Constants::PERMISSION_GRANTED) { + return result; + } + GrantUriPermission(want, validUserId); result = AbilityUtil::JudgeAbilityVisibleControl(abilityInfo, callerUid); if (result != ERR_OK) { HILOG_ERROR("%{public}s JudgeAbilityVisibleControl error.", __func__); @@ -299,7 +312,7 @@ int AbilityManagerService::StartAbilityInner(const Want &want, const sptrStartAbility(abilityRequest); - } - - userIdValid = abilityInfo.applicationInfo.singleUser ? DEFAULT_USER_ID : userIdValid; - - auto missionListManager = GetListManagerByUserId(userIdValid); + auto missionListManager = GetListManagerByUserId(validUserId); if (missionListManager == nullptr) { - HILOG_ERROR("missionListManager is nullptr. userId=%{public}d", userIdValid); + HILOG_ERROR("missionListManager is nullptr. userId=%{public}d", validUserId); return ERR_INVALID_VALUE; } HILOG_DEBUG("%{public}s StartAbility by MissionList", __func__); @@ -343,9 +349,9 @@ int AbilityManagerService::StartAbilityInner(const Want &want, const sptrStartAbility(abilityRequest); } - auto stackManager = GetStackManagerByUserId(userIdValid); + auto stackManager = GetStackManagerByUserId(validUserId); if (!stackManager) { - HILOG_ERROR("stackManager is nullptr. userId=%{public}d", userIdValid); + HILOG_ERROR("stackManager is nullptr. userId=%{public}d", validUserId); return ERR_INVALID_VALUE; } HILOG_DEBUG("%{public}s StartAbility by StackManager", __func__); @@ -358,23 +364,34 @@ int AbilityManagerService::StartAbility(const Want &want, const AbilityStartSett { BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); HILOG_DEBUG("Start ability setting."); + + if (userId != INVALID_USER_ID && !CheckCallerIsSystemAppByIpc()) { + HILOG_ERROR("caller is not systemApp"); + return CALLER_ISNOT_SYSTEMAPP; + } + if (callerToken != nullptr && !VerificationAllToken(callerToken)) { return ERR_INVALID_VALUE; } - int32_t userIdValid = GetValidUserId(want, userId); - int result = CheckMultiOsAccount(userIdValid); - if (result != ERR_OK) { - HILOG_ERROR("CheckMultiOsAccount error."); - return result; - } + int32_t validUserId = GetValidUserId(userId); + AbilityRequest abilityRequest; - result = GenerateAbilityRequestLocal(want, requestCode, abilityRequest, callerToken, userIdValid); + auto result = GenerateAbilityRequestLocal(want, requestCode, abilityRequest, callerToken, validUserId); if (result != ERR_OK) { HILOG_ERROR("Generate ability request local error."); return result; } auto abilityInfo = abilityRequest.abilityInfo; + validUserId = abilityInfo.applicationInfo.singleUser ? U0_USER_ID : validUserId; + HILOG_DEBUG("userId : %{public}d, singleUser is : %{public}d", + validUserId, static_cast(abilityInfo.applicationInfo.singleUser)); + + if (!JudgeMultiUserConcurrency(abilityRequest.abilityInfo, validUserId)) { + HILOG_ERROR("Multi-user non-concurrent mode is not satisfied."); + return ERR_INVALID_VALUE; + } + result = AbilityUtil::JudgeAbilityVisibleControl(abilityInfo); if (result != ERR_OK) { HILOG_ERROR("%{public}s JudgeAbilityVisibleControl error.", __func__); @@ -389,7 +406,7 @@ int AbilityManagerService::StartAbility(const Want &want, const AbilityStartSett } if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) { - result = PreLoadAppDataAbilities(abilityInfo.bundleName, userIdValid); + result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId); if (result != ERR_OK) { HILOG_ERROR("StartAbility: App data ability preloading failed, '%{public}s', %{public}d", abilityInfo.bundleName.c_str(), @@ -407,15 +424,9 @@ int AbilityManagerService::StartAbility(const Want &want, const AbilityStartSett return ERR_WOULD_BLOCK; } if (useNewMission_) { - if (IsSystemUiApp(abilityRequest.abilityInfo)) { - return kernalAbilityManager_->StartAbility(abilityRequest); - } - - userIdValid = abilityInfo.applicationInfo.singleUser ? DEFAULT_USER_ID : userIdValid; - - auto missionListManager = GetListManagerByUserId(userIdValid); + auto missionListManager = GetListManagerByUserId(validUserId); if (missionListManager == nullptr) { - HILOG_ERROR("missionListManager is Null. userId=%{public}d", userIdValid); + HILOG_ERROR("missionListManager is Null. userId=%{public}d", validUserId); return ERR_INVALID_VALUE; } return missionListManager->StartAbility(abilityRequest); @@ -424,9 +435,9 @@ int AbilityManagerService::StartAbility(const Want &want, const AbilityStartSett return systemAppManager_->StartAbility(abilityRequest); } - auto stackManager = GetStackManagerByUserId(userIdValid); + auto stackManager = GetStackManagerByUserId(validUserId); if (!stackManager) { - HILOG_ERROR("stackManager is nullptr. userId=%{public}d", userIdValid); + HILOG_ERROR("stackManager is nullptr. userId=%{public}d", validUserId); return ERR_INVALID_VALUE; } return stackManager->StartAbility(abilityRequest); @@ -438,25 +449,35 @@ int AbilityManagerService::StartAbility(const Want &want, const StartOptions &st { BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); HILOG_DEBUG("Start ability options."); + + if (userId != INVALID_USER_ID && !CheckCallerIsSystemAppByIpc()) { + HILOG_ERROR("caller is not systemApp"); + return CALLER_ISNOT_SYSTEMAPP; + } + if (callerToken != nullptr && !VerificationAllToken(callerToken)) { return ERR_INVALID_VALUE; } - int32_t userIdValid = GetValidUserId(want, userId); - int result = CheckMultiOsAccount(userIdValid); - if (result != ERR_OK) { - HILOG_ERROR("CheckMultiOsAccount error."); - return result; - } + int32_t validUserId = GetValidUserId(userId); AbilityRequest abilityRequest; - result = GenerateAbilityRequestLocal(want, requestCode, abilityRequest, callerToken, userIdValid); + auto result = GenerateAbilityRequestLocal(want, requestCode, abilityRequest, callerToken, validUserId); if (result != ERR_OK) { HILOG_ERROR("Generate ability request local error."); return result; } auto abilityInfo = abilityRequest.abilityInfo; + validUserId = abilityInfo.applicationInfo.singleUser ? U0_USER_ID : validUserId; + HILOG_DEBUG("userId : %{public}d, singleUser is : %{public}d", + validUserId, static_cast(abilityInfo.applicationInfo.singleUser)); + + if (!JudgeMultiUserConcurrency(abilityRequest.abilityInfo, validUserId)) { + HILOG_ERROR("Multi-user non-concurrent mode is not satisfied."); + return ERR_INVALID_VALUE; + } + result = AbilityUtil::JudgeAbilityVisibleControl(abilityInfo); if (result != ERR_OK) { HILOG_ERROR("%{public}s JudgeAbilityVisibleControl error.", __func__); @@ -469,7 +490,7 @@ int AbilityManagerService::StartAbility(const Want &want, const StartOptions &st } if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) { - result = PreLoadAppDataAbilities(abilityInfo.bundleName, userIdValid); + result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId); if (result != ERR_OK) { HILOG_ERROR("StartAbility: App data ability preloading failed, '%{public}s', %{public}d", abilityInfo.bundleName.c_str(), @@ -481,39 +502,103 @@ int AbilityManagerService::StartAbility(const Want &want, const StartOptions &st if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) { return ERR_WOULD_BLOCK; } - if (IsSystemUiApp(abilityRequest.abilityInfo)) { - if (useNewMission_) { - return kernalAbilityManager_->StartAbility(abilityRequest); - } else { - return systemAppManager_->StartAbility(abilityRequest); - } - } - abilityRequest.want.SetParam(StartOptions::STRING_DISPLAY_ID, startOptions.GetDisplayID()); + GrantUriPermission(want, validUserId); + abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID, startOptions.GetDisplayID()); abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_MODE, startOptions.GetWindowMode()); if (useNewMission_) { - userIdValid = abilityInfo.applicationInfo.singleUser ? DEFAULT_USER_ID : userIdValid; - - auto missionListManager = GetListManagerByUserId(userIdValid); + auto missionListManager = GetListManagerByUserId(validUserId); if (missionListManager == nullptr) { - HILOG_ERROR("missionListManager is Null. userId=%{public}d", userIdValid); + HILOG_ERROR("missionListManager is Null. userId=%{public}d", validUserId); return ERR_INVALID_VALUE; } return missionListManager->StartAbility(abilityRequest); } else { - auto stackManager = GetStackManagerByUserId(userIdValid); + auto stackManager = GetStackManagerByUserId(validUserId); if (!stackManager) { - HILOG_ERROR("stackManager is nullptr. userId=%{public}d", userIdValid); + HILOG_ERROR("stackManager is nullptr. userId=%{public}d", validUserId); return ERR_INVALID_VALUE; } return stackManager->StartAbility(abilityRequest); } } +void AbilityManagerService::GrantUriPermission(const Want &want, int32_t validUserId) +{ + HILOG_DEBUG("AbilityManagerService::GrantUriPermission is called."); + auto bms = GetBundleManager(); + if (!bms) { + HILOG_ERROR("Get bundle manager service failed."); + return; + } + + auto bundleName = want.GetBundle(); + AppExecFwk::BundleInfo bundleInfo; + auto bundleFlag = AppExecFwk::BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO; + if (!bms->GetBundleInfo(bundleName, bundleFlag, bundleInfo, validUserId)) { + HILOG_ERROR("Not found ExtensionAbilityInfo according to the uri."); + return; + } + + if (want.GetFlags() & (Want::FLAG_AUTH_READ_URI_PERMISSION | Want::FLAG_AUTH_WRITE_URI_PERMISSION)) { + HILOG_INFO("Want to grant r/w permission of the uri"); + auto targetTokenId = bundleInfo.applicationInfo.accessTokenId; + GrantUriPermission(want, validUserId, targetTokenId); + } +} + +void AbilityManagerService::GrantUriPermission(const Want &want, int32_t validUserId, uint32_t targetTokenId) +{ + auto bms = GetBundleManager(); + if (!bms) { + HILOG_ERROR("Get bundle manager service failed."); + return; + } + auto uriStr = want.GetUri().ToString(); + auto uriVec = want.GetStringArrayParam(AbilityConfig::PARAMS_STREAM); + uriVec.emplace_back(uriStr); + auto upmClient = AAFwk::UriPermissionManagerClient::GetInstance(); + auto fromTokenId = IPCSkeleton::GetCallingTokenID(); + AppExecFwk::ExtensionAbilityInfo info; + for (auto str : uriVec) { + if (!bms->QueryExtensionAbilityInfoByUri(str, validUserId, info)) { + HILOG_WARN("Not found ExtensionAbilityInfo according to the uri."); + continue; + } + if (info.type != AppExecFwk::ExtensionAbilityType::FILESHARE) { + HILOG_WARN("The upms only open to FILESHARE."); + continue; + } + if (fromTokenId != info.applicationInfo.accessTokenId) { + HILOG_WARN("Only the uri of this application can be authorized."); + continue; + } + + Uri uri(str); + if (want.GetFlags() & Want::FLAG_AUTH_WRITE_URI_PERMISSION) { + upmClient->GrantUriPermission(uri, Want::FLAG_AUTH_WRITE_URI_PERMISSION, fromTokenId, targetTokenId); + } else { + upmClient->GrantUriPermission(uri, Want::FLAG_AUTH_READ_URI_PERMISSION, fromTokenId, targetTokenId); + } + } +} + int AbilityManagerService::TerminateAbility(const sptr &token, int resultCode, const Want *resultWant) +{ + return TerminateAbilityWithFlag(token, resultCode, resultWant, true); +} + +int AbilityManagerService::CloseAbility(const sptr &token, int resultCode, const Want *resultWant) +{ + return TerminateAbilityWithFlag(token, resultCode, resultWant, false); +} + +int AbilityManagerService::TerminateAbilityWithFlag(const sptr &token, int resultCode, + const Want *resultWant, bool flag) { BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); HILOG_DEBUG("Terminate ability for result: %{public}d", (resultWant != nullptr)); if (!VerificationAllToken(token)) { + HILOG_ERROR("%{public}s VerificationAllToken failed.", __func__); return ERR_INVALID_VALUE; } @@ -565,7 +650,7 @@ int AbilityManagerService::TerminateAbility(const sptr &token, in HILOG_ERROR("missionListManager is Null. userId=%{public}d", userId); return ERR_INVALID_VALUE; } - return missionListManager->TerminateAbility(abilityRecord, resultCode, resultWant); + return missionListManager->TerminateAbility(abilityRecord, resultCode, resultWant, flag); } else { auto stackManager = GetStackManagerByUserId(userId); if (!stackManager) { @@ -581,9 +666,11 @@ int AbilityManagerService::StartRemoteAbility(const Want &want, int requestCode) HILOG_INFO("%{public}s", __func__); want.DumpInfo(0); int32_t callerUid = IPCSkeleton::GetCallingUid(); + uint32_t accessToken = IPCSkeleton::GetCallingTokenID(); DistributedClient dmsClient; HILOG_INFO("AbilityManagerService::Try to StartRemoteAbility, callerUid = %{public}d", callerUid); - int result = dmsClient.StartRemoteAbility(want, callerUid, requestCode); + HILOG_INFO("AbilityManagerService::Try to StartRemoteAbility, AccessTokenID = %{public}d", accessToken); + int result = dmsClient.StartRemoteAbility(want, callerUid, requestCode, accessToken); if (result != ERR_NONE) { HILOG_ERROR("AbilityManagerService::StartRemoteAbility failed, result = %{public}d", result); } @@ -592,35 +679,32 @@ int AbilityManagerService::StartRemoteAbility(const Want &want, int requestCode) bool AbilityManagerService::CheckIsRemote(const std::string& deviceId) { - HILOG_INFO("check is remote, deviceId = %{public}s", AnonymizeDeviceId(deviceId).c_str()); if (deviceId.empty()) { - HILOG_ERROR("CheckIsRemote: device id is empty."); + HILOG_INFO("CheckIsRemote: deviceId is empty."); return false; } - std::string localDeviceId; - if (!GetLocalDeviceId(localDeviceId) || localDeviceId == deviceId) { - HILOG_ERROR("CheckIsRemote: Check DeviceId failed"); + if (!GetLocalDeviceId(localDeviceId)) { + HILOG_ERROR("CheckIsRemote: get local deviceId failed"); + return false; + } + if (localDeviceId == deviceId) { + HILOG_INFO("CheckIsRemote: deviceId is local."); return false; } + HILOG_INFO("CheckIsRemote, deviceId = %{public}s", AnonymizeDeviceId(deviceId).c_str()); return true; } bool AbilityManagerService::CheckIfOperateRemote(const Want &want) { - std::string localDeviceId; std::string deviceId = want.GetElement().GetDeviceID(); - HILOG_INFO("get deviceId, deviceId = %{public}s", AnonymizeDeviceId(deviceId).c_str()); if (deviceId.empty() || want.GetElement().GetBundleName().empty() || want.GetElement().GetAbilityName().empty()) { - HILOG_ERROR("CheckIfOperateRemote: GetDeviceId,or GetBundleName, or GetAbilityName failed"); + HILOG_DEBUG("CheckIfOperateRemote: DeviceId or BundleName or GetAbilityName empty"); return false; } - if (!GetLocalDeviceId(localDeviceId) || localDeviceId == deviceId) { - HILOG_ERROR("CheckIfOperateRemote: Check DeviceId failed"); - return false; - } - return true; + return CheckIsRemote(deviceId); } bool AbilityManagerService::GetLocalDeviceId(std::string& localDeviceId) @@ -889,18 +973,18 @@ int AbilityManagerService::ConnectAbility( CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE); CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE); + if (userId != INVALID_USER_ID && !CheckCallerIsSystemAppByIpc()) { + HILOG_ERROR("caller is not systemApp"); + return CALLER_ISNOT_SYSTEMAPP; + } + if (CheckIfOperateRemote(want)) { HILOG_INFO("AbilityManagerService::ConnectAbility. try to ConnectRemoteAbility"); return ConnectRemoteAbility(want, connect->AsObject()); } - int32_t userIdValid = GetValidUserId(want, userId); - int result = CheckMultiOsAccount(userIdValid); - if (result != ERR_OK) { - HILOG_ERROR("CheckMultiOsAccount error."); - return result; - } - return ConnectLocalAbility(want, userIdValid, connect, callerToken); + int32_t validUserId = GetValidUserId(userId); + return ConnectLocalAbility(want, validUserId, connect, callerToken); } int AbilityManagerService::DisconnectAbility(const sptr &connect) @@ -927,6 +1011,25 @@ int AbilityManagerService::ConnectLocalAbility(const Want &want, const int32_t u return result; } auto abilityInfo = abilityRequest.abilityInfo; + int32_t validUserId = abilityInfo.applicationInfo.singleUser ? U0_USER_ID : userId; + HILOG_DEBUG("validUserId : %{public}d, singleUser is : %{public}d", + validUserId, static_cast(abilityInfo.applicationInfo.singleUser)); + + if (!JudgeMultiUserConcurrency(abilityRequest.abilityInfo, validUserId)) { + HILOG_ERROR("Multi-user non-concurrent mode is not satisfied."); + return ERR_INVALID_VALUE; + } + + result = CheckStaticCfgPermission(abilityInfo); + if (result != AppExecFwk::Constants::PERMISSION_GRANTED) { + return result; + } + + if (!VerifyUriPermisson(abilityRequest, want)) { + HILOG_ERROR("The uri has not granted."); + return ERR_INVALID_OPERATION; + } + result = AbilityUtil::JudgeAbilityVisibleControl(abilityInfo); if (result != ERR_OK) { HILOG_ERROR("%{public}s JudgeAbilityVisibleControl error.", __func__); @@ -937,7 +1040,7 @@ int AbilityManagerService::ConnectLocalAbility(const Want &want, const int32_t u HILOG_ERROR("Connect Ability failed, target Ability is not Service."); return TARGET_ABILITY_NOT_SERVICE; } - result = PreLoadAppDataAbilities(abilityInfo.bundleName, userId); + result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId); if (result != ERR_OK) { HILOG_ERROR("ConnectAbility: App data ability preloading failed, '%{public}s', %{public}d", abilityInfo.bundleName.c_str(), @@ -945,9 +1048,9 @@ int AbilityManagerService::ConnectLocalAbility(const Want &want, const int32_t u return result; } - auto connectManager = GetConnectManagerByUserId(userId); + auto connectManager = GetConnectManagerByUserId(validUserId); if (connectManager == nullptr) { - HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId); + HILOG_ERROR("connectManager is nullptr. userId=%{public}d", validUserId); return ERR_INVALID_VALUE; } return connectManager->ConnectAbilityLocked(abilityRequest, connect, callerToken); @@ -958,8 +1061,10 @@ int AbilityManagerService::ConnectRemoteAbility(const Want &want, const sptr &connect) @@ -1008,13 +1113,15 @@ int AbilityManagerService::StartContinuation(const Want &want, const sptrMoveMissionToFront(missionId); } +int AbilityManagerService::MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) +{ + HILOG_INFO("request MoveMissionToFront, missionId:%{public}d", missionId); + CHECK_POINTER_AND_RETURN(currentMissionListManager_, ERR_NO_INIT); + CHECK_POINTER_AND_RETURN(iBundleManager_, ERR_NO_INIT); + + if (!CheckCallerIsSystemAppByIpc()) { + HILOG_ERROR("caller is not system app"); + return CALLER_ISNOT_SYSTEMAPP; + } + + auto options = std::make_shared(startOptions); + return currentMissionListManager_->MoveMissionToFront(missionId, options); +} + std::shared_ptr AbilityManagerService::GetServiceRecordByElementName(const std::string &element) { return connectManager_->GetServiceRecordByElementName(element); @@ -1466,7 +1588,7 @@ sptr AbilityManagerService::AcquireDataAbility( return nullptr; } - auto userId = GetUserId(); + auto userId = GetValidUserId(INVALID_USER_ID); AbilityRequest abilityRequest; std::string dataAbilityUri = localUri.ToString(); HILOG_INFO("%{public}s, called. userId %{public}d", __func__, userId); @@ -1486,8 +1608,17 @@ sptr AbilityManagerService::AcquireDataAbility( abilityRequest.appInfo.bundleName.c_str(), abilityRequest.abilityInfo.name.c_str()); - CHECK_POINTER_AND_RETURN(dataAbilityManager_, nullptr); - return dataAbilityManager_->Acquire(abilityRequest, tryBind, callerToken, isSystem); + if (CheckStaticCfgPermission(abilityRequest.abilityInfo) != AppExecFwk::Constants::PERMISSION_GRANTED) { + return nullptr; + } + + if (abilityRequest.abilityInfo.applicationInfo.singleUser) { + userId = U0_USER_ID; + } + + std::shared_ptr dataAbilityManager = GetDataAbilityManagerByUserId(userId); + CHECK_POINTER_AND_RETURN(dataAbilityManager, nullptr); + return dataAbilityManager->Acquire(abilityRequest, tryBind, callerToken, isSystem); } bool AbilityManagerService::CheckDataAbilityRequest(AbilityRequest &abilityRequest) @@ -1518,12 +1649,17 @@ int AbilityManagerService::ReleaseDataAbility( if (!isSystem) { HILOG_INFO("callerToken not system %{public}s", __func__); if (!VerificationAllToken(callerToken)) { - HILOG_INFO("VerificationAllToken fail"); + HILOG_ERROR("VerificationAllToken fail"); return ERR_INVALID_STATE; } } - return dataAbilityManager_->Release(dataAbilityScheduler, callerToken, isSystem); + std::shared_ptr dataAbilityManager = GetDataAbilityManager(dataAbilityScheduler); + if (!dataAbilityManager) { + HILOG_ERROR("dataAbilityScheduler is not exists"); + } + + return dataAbilityManager->Release(dataAbilityScheduler, callerToken, isSystem); } int AbilityManagerService::AttachAbilityThread( @@ -1559,12 +1695,6 @@ int AbilityManagerService::AttachAbilityThread( return ERR_INVALID_VALUE; } returnCode = dataAbilityManager->AttachAbilityThread(scheduler, token); - } else if (IsSystemUiApp(abilityInfo)) { - if (useNewMission_) { - returnCode = kernalAbilityManager_->AttachAbilityThread(scheduler, token); - } else { - returnCode = systemAppManager_->AttachAbilityThread(scheduler, token); - } } else { if (useNewMission_) { auto missionListManager = GetListManagerByUserId(userId); @@ -1611,6 +1741,8 @@ void AbilityManagerService::DumpSysFuncInit() dumpsysFuncMap_[KEY_DUMPSYS_SERVICE] = &AbilityManagerService::DumpSysStateInner; dumpsysFuncMap_[KEY_DUMPSYS_PENDING] = &AbilityManagerService::DumpSysPendingInner; dumpsysFuncMap_[KEY_DUMPSYS_PROCESS] = &AbilityManagerService::DumpSysProcess; + dumpsysFuncMap_[KEY_DUMPSYS_DATA] = &AbilityManagerService::DataDumpSysStateInner; + dumpsysFuncMap_[KEY_DUMPSYS_SYSTEM_UI] = &AbilityManagerService::SystemDumpSysStateInner; } void AbilityManagerService::DumpSysInner( @@ -1628,7 +1760,7 @@ void AbilityManagerService::DumpSysInner( } void AbilityManagerService::DumpSysMissionListInner( - const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId) + const std::string &args, std::vector &info, bool isClient, bool isUserID, int userId) { std::shared_ptr targetManager; if (isUserID) { @@ -1659,7 +1791,7 @@ void AbilityManagerService::DumpSysMissionListInner( } } void AbilityManagerService::DumpSysAbilityInner( - const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId) + const std::string &args, std::vector &info, bool isClient, bool isUserID, int userId) { std::shared_ptr targetManager; if (isUserID) { @@ -1680,9 +1812,10 @@ void AbilityManagerService::DumpSysAbilityInner( if (argList.empty()) { return; } - if (argList.size() == MIN_DUMP_ARGUMENT_NUM) { + if (argList.size() >= MIN_DUMP_ARGUMENT_NUM) { HILOG_INFO("argList = %{public}s", argList[1].c_str()); - targetManager->DumpMissionListByRecordId(info, isClient, std::stoi(argList[1])); + std::vector params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end()); + targetManager->DumpMissionListByRecordId(info, isClient, std::stoi(argList[1]), params); } else { info.emplace_back("error: invalid argument, please see 'ability dumpsys -h'."); } @@ -1724,18 +1857,33 @@ void AbilityManagerService::DumpSysStateInner( void AbilityManagerService::DumpSysPendingInner( const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId) { + std::shared_ptr targetManager; if (isUserID) { auto it = pendingWantManagers_.find(userId); - if (it != pendingWantManagers_.end()) { - it->second->Dump(info); + if (it == pendingWantManagers_.end()) { + info.push_back("error: No user found'."); return; } - info.push_back("error: No user found'."); + targetManager = it->second; + } else { + targetManager = pendingWantManager_; + } + + CHECK_POINTER(targetManager); + + std::vector argList; + SplitStr(args, " ", argList); + if (argList.empty()) { return; } - CHECK_POINTER(pendingWantManager_); - pendingWantManager_->Dump(info); + if (argList.size() == MIN_DUMP_ARGUMENT_NUM) { + targetManager->DumpByRecordId(info, argList[1]); + } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) { + targetManager->Dump(info); + } else { + info.emplace_back("error: invalid argument, please see 'ability dumpsys -h'."); + } } void AbilityManagerService::DumpSysProcess( @@ -1783,6 +1931,43 @@ void AbilityManagerService::DumpSysProcess( } } +void AbilityManagerService::DataDumpSysStateInner( + const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId) +{ + std::shared_ptr targetManager; + if (isUserID) { + auto it = dataAbilityManagers_.find(userId); + if (it == dataAbilityManagers_.end()) { + info.push_back("error: No user found'."); + return; + } + targetManager = it->second; + } else { + targetManager = dataAbilityManager_; + } + + CHECK_POINTER(targetManager); + + std::vector argList; + SplitStr(args, " ", argList); + if (argList.empty()) { + return; + } + if (argList.size() == MIN_DUMP_ARGUMENT_NUM) { + targetManager->DumpSysState(info, isClient, argList[1]); + } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) { + targetManager->DumpSysState(info, isClient); + } else { + info.emplace_back("error: invalid argument, please see 'ability dump -h'."); + } +} + +void AbilityManagerService::SystemDumpSysStateInner( + const std::string& args, std::vector& info, bool isClient, bool isUserID, int userId) +{ + systemAppManager_->DumpSysState(info, isClient); +} + void AbilityManagerService::DumpInner(const std::string &args, std::vector &info) { if (useNewMission_) { @@ -2004,9 +2189,6 @@ int AbilityManagerService::AbilityTransitionDone(const sptr &toke return dataAbilityManager->AbilityTransitionDone(token, state); } if (useNewMission_) { - if (IsSystemUiApp(abilityInfo)) { - return kernalAbilityManager_->AbilityTransitionDone(token, state); - } auto missionListManager = GetListManagerByUserId(userId); if (!missionListManager) { HILOG_ERROR("missionListManager is Null. userId=%{public}d", userId); @@ -2150,10 +2332,6 @@ void AbilityManagerService::OnAbilityRequestDone(const sptr &toke } default: { if (useNewMission_) { - if (IsSystemUiApp(abilityRecord->GetAbilityInfo())) { - kernalAbilityManager_->OnAbilityRequestDone(token, state); - break; - } auto missionListManager = GetListManagerByUserId(userId); if (!missionListManager) { HILOG_ERROR("missionListManager is Null. userId=%{public}d", userId); @@ -2180,11 +2358,11 @@ void AbilityManagerService::OnAbilityRequestDone(const sptr &toke void AbilityManagerService::OnAppStateChanged(const AppInfo &info) { HILOG_INFO("On app state changed."); - currentStackManager_->OnAppStateChanged(info); connectManager_->OnAppStateChanged(info); if (useNewMission_) { - kernalAbilityManager_->OnAppStateChanged(info); + currentMissionListManager_->OnAppStateChanged(info); } else { + currentStackManager_->OnAppStateChanged(info); systemAppManager_->OnAppStateChanged(info); } dataAbilityManager_->OnAppStateChanged(info); @@ -2247,7 +2425,7 @@ int AbilityManagerService::GetUserId() if (userController_) { return userController_->GetCurrentUserId(); } - return DEFAULT_USER_ID; + return U0_USER_ID; } void AbilityManagerService::StartingLauncherAbility() @@ -2358,16 +2536,6 @@ void AbilityManagerService::StartingMmsAbility() } } -void AbilityManagerService::StartSystemUi(const std::string abilityName) -{ - HILOG_INFO("Starting system ui app."); - Want want; - want.SetElementName(AbilityConfig::SYSTEM_UI_BUNDLE_NAME, abilityName); - HILOG_INFO("Ability name: %{public}s.", abilityName.c_str()); - (void)StartAbility(want, USER_ID_DEFAULT, DEFAULT_INVAL_VALUE); - return; -} - int AbilityManagerService::GenerateAbilityRequest( const Want &want, int requestCode, AbilityRequest &request, const sptr &callerToken, int32_t userId) { @@ -2387,26 +2555,17 @@ int AbilityManagerService::GenerateAbilityRequest( userId, request.abilityInfo); if (request.abilityInfo.name.empty() || request.abilityInfo.bundleName.empty()) { // try to find extension - int ret = GetAbilityInfoFromExtension(want, request.abilityInfo); + int ret = GetAbilityInfoFromExtension(want, request.abilityInfo, userId); if (!ret) { HILOG_ERROR("Get ability info failed."); return RESOLVE_ABILITY_ERR; } } - HILOG_DEBUG("Query ability name: %{public}s,", request.abilityInfo.name.c_str()); - if (request.abilityInfo.type == AppExecFwk::AbilityType::SERVICE) { - AppExecFwk::BundleInfo bundleInfo; - bool ret = bms->GetBundleInfo(request.abilityInfo.bundleName, - AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, userId); - if (!ret) { - HILOG_ERROR("Failed to get bundle info when GenerateAbilityRequest."); - return RESOLVE_ABILITY_ERR; - } - HILOG_INFO("bundleInfo.compatibleVersion:%{public}d", bundleInfo.compatibleVersion); - if (bundleInfo.compatibleVersion >= EXTENSION_SUPPORT_API_VERSION) { - HILOG_INFO("abilityInfo reset EXTENSION."); - request.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION; - } + HILOG_DEBUG("Query ability name: %{public}s, is stage mode: %{public}d", + request.abilityInfo.name.c_str(), request.abilityInfo.isStageBasedModel); + if (request.abilityInfo.type == AppExecFwk::AbilityType::SERVICE && request.abilityInfo.isStageBasedModel) { + HILOG_INFO("stage mode, abilityInfo SERVICE type reset EXTENSION."); + request.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION; } auto appName = request.abilityInfo.applicationInfo.name; @@ -2473,26 +2632,32 @@ int AbilityManagerService::StopServiceAbility(const Want &want, int32_t userId) BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); HILOG_DEBUG("Stop service ability."); - int32_t userIdValid = GetValidUserId(want, userId); - int result = CheckMultiOsAccount(userIdValid); - if (result != ERR_OK) { - HILOG_ERROR("CheckMultiOsAccount error."); - return result; - } + int32_t validUserId = GetValidUserId(userId); + AbilityRequest abilityRequest; - result = GenerateAbilityRequestLocal(want, DEFAULT_INVAL_VALUE, abilityRequest, nullptr, userIdValid); + auto result = GenerateAbilityRequestLocal(want, DEFAULT_INVAL_VALUE, abilityRequest, nullptr, validUserId); if (result != ERR_OK) { HILOG_ERROR("Generate ability request local error."); return result; } + auto abilityInfo = abilityRequest.abilityInfo; + validUserId = abilityInfo.applicationInfo.singleUser ? U0_USER_ID : validUserId; + HILOG_DEBUG("validUserId : %{public}d, singleUser is : %{public}d", + validUserId, static_cast(abilityInfo.applicationInfo.singleUser)); + + if (!JudgeMultiUserConcurrency(abilityRequest.abilityInfo, validUserId)) { + HILOG_ERROR("Multi-user non-concurrent mode is not satisfied."); + return ERR_INVALID_VALUE; + } + auto type = abilityInfo.type; if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) { HILOG_ERROR("Target ability is not service type."); return TARGET_ABILITY_NOT_SERVICE; } - auto connectManager = GetConnectManagerByUserId(userIdValid); + auto connectManager = GetConnectManagerByUserId(validUserId); if (connectManager == nullptr) { return ERR_INVALID_VALUE; } @@ -2505,11 +2670,6 @@ void AbilityManagerService::OnAbilityDied(std::shared_ptr ability CHECK_POINTER(abilityRecord); if (useNewMission_) { - if (kernalAbilityManager_ && abilityRecord->IsKernalSystemAbility()) { - kernalAbilityManager_->OnAbilityDied(abilityRecord); - return; - } - auto manager = GetListManagerByToken(abilityRecord->GetToken()); if (manager) { manager->OnAbilityDied(abilityRecord, GetUserId()); @@ -2628,7 +2788,6 @@ sptr AbilityManagerService::GetBundleManager() } iBundleManager_ = iface_cast(bundleObj); } - return iBundleManager_; } @@ -2690,7 +2849,9 @@ bool AbilityManagerService::IsSystemUiApp(const AppExecFwk::AbilityInfo &info) c if (info.bundleName != AbilityConfig::SYSTEM_UI_BUNDLE_NAME) { return false; } - return (info.name == AbilityConfig::SYSTEM_UI_NAVIGATION_BAR || info.name == AbilityConfig::SYSTEM_UI_STATUS_BAR); + return (info.name == AbilityConfig::SYSTEM_UI_NAVIGATION_BAR || + info.name == AbilityConfig::SYSTEM_UI_STATUS_BAR || + info.name == AbilityConfig::SYSTEM_UI_ABILITY_NAME); } bool AbilityManagerService::IsSystemUI(const std::string &bundleName) const @@ -2702,9 +2863,6 @@ void AbilityManagerService::HandleLoadTimeOut(int64_t eventId) { HILOG_DEBUG("Handle load timeout."); if (useNewMission_) { - if (kernalAbilityManager_) { - kernalAbilityManager_->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, eventId); - } for (auto& item : missionListManagers_) { if (item.second) { item.second->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, eventId); @@ -2719,7 +2877,7 @@ void AbilityManagerService::HandleLoadTimeOut(int64_t eventId) item.second->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, eventId); } } - } + } } void AbilityManagerService::HandleActiveTimeOut(int64_t eventId) @@ -2727,9 +2885,6 @@ void AbilityManagerService::HandleActiveTimeOut(int64_t eventId) HILOG_DEBUG("Handle active timeout."); if (useNewMission_) { - if (kernalAbilityManager_) { - kernalAbilityManager_->OnTimeOut(AbilityManagerService::ACTIVE_TIMEOUT_MSG, eventId); - } for (auto& item : missionListManagers_) { if (item.second) { item.second->OnTimeOut(AbilityManagerService::ACTIVE_TIMEOUT_MSG, eventId); @@ -2769,9 +2924,6 @@ void AbilityManagerService::HandleForegroundNewTimeOut(int64_t eventId) { HILOG_DEBUG("Handle ForegroundNew timeout."); if (useNewMission_) { - if (kernalAbilityManager_) { - kernalAbilityManager_->OnTimeOut(AbilityManagerService::FOREGROUNDNEW_TIMEOUT_MSG, eventId); - } for (auto& item : missionListManagers_) { if (item.second) { item.second->OnTimeOut(AbilityManagerService::FOREGROUNDNEW_TIMEOUT_MSG, eventId); @@ -2793,9 +2945,6 @@ void AbilityManagerService::HandleBackgroundNewTimeOut(int64_t eventId) { HILOG_DEBUG("Handle BackgroundNew timeout."); if (useNewMission_) { - if (kernalAbilityManager_) { - kernalAbilityManager_->OnTimeOut(AbilityManagerService::BACKGROUNDNEW_TIMEOUT_MSG, eventId); - } for (auto& item : missionListManagers_) { if (item.second) { item.second->OnTimeOut(AbilityManagerService::BACKGROUNDNEW_TIMEOUT_MSG, eventId); @@ -2821,7 +2970,6 @@ bool AbilityManagerService::VerificationToken(const sptr &token) CHECK_POINTER_RETURN_BOOL(currentStackManager_); CHECK_POINTER_RETURN_BOOL(systemAppManager_); CHECK_POINTER_RETURN_BOOL(currentMissionListManager_); - CHECK_POINTER_RETURN_BOOL(kernalAbilityManager_); if (useNewMission_) { if (currentMissionListManager_->GetAbilityRecordByToken(token)) { @@ -2848,11 +2996,7 @@ bool AbilityManagerService::VerificationToken(const sptr &token) return true; } - if (useNewMission_) { - if (kernalAbilityManager_->GetAbilityRecordByToken(token)) { - return true; - } - } else { + if (!useNewMission_) { if (systemAppManager_->GetAbilityRecordByToken(token)) { return true; } @@ -2900,11 +3044,7 @@ bool AbilityManagerService::VerificationAllToken(const sptr &toke } } - if (useNewMission_) { - if (kernalAbilityManager_->GetAbilityRecordByToken(token)) { - return true; - } - } else { + if (!useNewMission_) { if (systemAppManager_->GetAbilityRecordByToken(token)) { return true; } @@ -2914,6 +3054,23 @@ bool AbilityManagerService::VerificationAllToken(const sptr &toke return false; } +const std::shared_ptr &AbilityManagerService::GetDataAbilityManager( + const sptr &scheduler) +{ + if (scheduler == nullptr) { + HILOG_ERROR("the param ability scheduler is nullptr"); + return nullptr; + } + + for (auto item: dataAbilityManagers_) { + if (item.second && item.second->ContainsDataAbility(scheduler)) { + return item.second; + } + } + + return nullptr; +} + std::shared_ptr AbilityManagerService::GetStackManagerByUserId(int32_t userId) { auto it = stackManagers_.find(userId); @@ -3147,7 +3304,6 @@ void AbilityManagerService::RestartAbility(const sptr &token) { HILOG_INFO("%{public}s called", __func__); CHECK_POINTER(currentStackManager_); - CHECK_POINTER(kernalAbilityManager_); CHECK_POINTER(systemAppManager_); if (!VerificationAllToken(token)) { return; @@ -3157,14 +3313,6 @@ void AbilityManagerService::RestartAbility(const sptr &token) auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE; CHECK_POINTER(abilityRecord); - if (IsSystemUiApp(abilityRecord->GetAbilityInfo())) { - if (useNewMission_) { - kernalAbilityManager_->RestartAbility(abilityRecord); - } else { - systemAppManager_->RestartAbility(abilityRecord); - } - return; - } auto stackManager = GetStackManagerByUserId(userId); if (!stackManager) { HILOG_ERROR("stackManager is nullptr. userId=%{public}d", userId); @@ -3190,14 +3338,14 @@ void AbilityManagerService::StartSystemApplication() if (!amsConfigResolver_ || amsConfigResolver_->NonConfigFile()) { HILOG_INFO("start all"); + StartingSettingsDataAbility(); StartingSystemUiAbility(); return; } + StartingSettingsDataAbility(); StartingSystemUiAbility(); - - // Location may change - DelayedSingleton::GetInstance()->StartupResidentProcess(); + StartupResidentProcess(); } void AbilityManagerService::StartingSystemUiAbility() @@ -3310,13 +3458,16 @@ int AbilityManagerService::GetMissionSaveTime() const int32_t AbilityManagerService::GetMissionIdByAbilityToken(const sptr &token) { auto abilityRecord = Token::GetAbilityRecordByToken(token); + if (!abilityRecord) { + HILOG_ERROR("abilityRecord is Null."); + return -1; + } auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE; auto missionListManager = GetListManagerByUserId(userId); if (!missionListManager) { HILOG_ERROR("missionListManager is Null. userId=%{public}d", userId); return -1; } - return missionListManager->GetMissionIdByAbilityToken(token); } @@ -3340,10 +3491,8 @@ void AbilityManagerService::StartingSettingsDataAbility() Want want; want.SetElementName(AbilityConfig::SETTINGS_DATA_BUNDLE_NAME, AbilityConfig::SETTINGS_DATA_ABILITY_NAME); uint32_t waitCnt = 0; - // Wait 5 minutes for the installation to complete. - auto userId = GetUserId(); while (!iBundleManager_->QueryAbilityInfo(want, OHOS::AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_DEFAULT, - userId, abilityInfo) && waitCnt < MAX_WAIT_SETTINGS_DATA_NUM) { + U0_USER_ID, abilityInfo) && waitCnt < MAX_WAIT_SETTINGS_DATA_NUM) { HILOG_INFO("Waiting query settings data info completed."); usleep(REPOLL_TIME_MICRO_SECONDS); waitCnt++; @@ -3375,6 +3524,22 @@ void AbilityManagerService::StartingSettingsDataAbility() (void)AcquireDataAbility(uri, true, nullptr); } +int AbilityManagerService::StartRemoteAbilityByCall(const Want &want, const sptr &connect) +{ + int32_t callerUid = IPCSkeleton::GetCallingUid(); + int32_t callerPid = IPCSkeleton::GetCallingPid(); + uint32_t tokenCaller = IPCSkeleton::GetCallingTokenID(); + DistributedClient dmsClient; + return dmsClient.StartRemoteAbilityByCall(want, connect, callerUid, callerPid, tokenCaller); +} + +int AbilityManagerService::ReleaseRemoteAbility(const sptr &connect, + const AppExecFwk::ElementName &element) +{ + DistributedClient dmsClient; + return dmsClient.ReleaseRemoteAbility(connect, element); +} + int AbilityManagerService::StartAbilityByCall( const Want &want, const sptr &connect, const sptr &callerToken) { @@ -3382,6 +3547,11 @@ int AbilityManagerService::StartAbilityByCall( CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE); CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE); + if (CheckIfOperateRemote(want)) { + HILOG_INFO("start remote ability by call"); + return StartRemoteAbilityByCall(want, connect->AsObject()); + } + AbilityRequest abilityRequest; abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; abilityRequest.callerUid = IPCSkeleton::GetCallingUid(); @@ -3420,6 +3590,11 @@ int AbilityManagerService::ReleaseAbility( std::string elementName = element.GetURI(); HILOG_DEBUG("try to release called ability, name: %{public}s.", elementName.c_str()); + if (CheckIsRemote(element.GetDeviceID())) { + HILOG_INFO("release remote ability"); + return ReleaseRemoteAbility(connect->AsObject(), element); + } + return currentMissionListManager_->ReleaseLocked(connect, element); } @@ -3539,7 +3714,6 @@ int AbilityManagerService::GetAbilityRunningInfos(std::vectorGetAbilityRunningInfos(info); - kernalAbilityManager_->GetAbilityRunningInfos(info); connectManager_->GetAbilityRunningInfos(info); dataAbilityManager_->GetAbilityRunningInfos(info); @@ -3662,14 +3836,14 @@ void AbilityManagerService::SwitchToUser(int32_t oldUserId, int32_t userId) StartUserApps(userId); } -void AbilityManagerService::SwitchManagers(int32_t userId) +void AbilityManagerService::SwitchManagers(int32_t userId, bool switchUser) { HILOG_INFO("%{public}s, SwitchManagers:%{public}d-----begin", __func__, userId); - InitConnectManager(userId, true); - SetStackManager(userId, true); - InitMissionListManager(userId, true); - InitDataAbilityManager(userId, true); - InitPendWantManager(userId, true); + InitConnectManager(userId, switchUser); + SetStackManager(userId, switchUser); + InitMissionListManager(userId, switchUser); + InitDataAbilityManager(userId, switchUser); + InitPendWantManager(userId, switchUser); HILOG_INFO("%{public}s, SwitchManagers:%{public}d-----end", __func__, userId); } @@ -3741,7 +3915,7 @@ void AbilityManagerService::StartSystemAbilityByUser(int32_t userId) if (!amsConfigResolver_ || amsConfigResolver_->NonConfigFile()) { HILOG_INFO("start all"); StartingLauncherAbility(); - StartingSettingsDataAbility(); + StartingScreenLockAbility(); return; } @@ -3750,9 +3924,8 @@ void AbilityManagerService::StartSystemAbilityByUser(int32_t userId) StartingLauncherAbility(); } - if (amsConfigResolver_->GetStartSettingsDataState()) { - HILOG_INFO("start settingsdata"); - StartingSettingsDataAbility(); + if (amsConfigResolver_->GetStartScreenLockState()) { + StartingScreenLockAbility(); } if (amsConfigResolver_->GetPhoneServiceState()) { @@ -3820,20 +3993,24 @@ void AbilityManagerService::InitPendWantManager(int32_t userId, bool switchUser) } } -int32_t AbilityManagerService::GetValidUserId(const Want &want, const int32_t userId) +int32_t AbilityManagerService::GetValidUserId(const int32_t userId) { HILOG_DEBUG("%{public}s userId = %{public}d", __func__, userId); - int32_t userIdValid = DEFAULT_INVAL_VALUE; + int32_t validUserId = DEFAULT_INVAL_VALUE; if (DEFAULT_INVAL_VALUE == userId) { - userIdValid = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE; - HILOG_DEBUG("%{public}s userIdValid = %{public}d, CallingUid = %{public}d", __func__, userIdValid, + validUserId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE; + HILOG_DEBUG("%{public}s validUserId = %{public}d, CallingUid = %{public}d", __func__, validUserId, IPCSkeleton::GetCallingUid()); + if (validUserId == U0_USER_ID) { + validUserId = GetUserId(); + } } else { - userIdValid = userId; + validUserId = userId; } - return userIdValid; + return validUserId; } + int AbilityManagerService::SetAbilityController(const sptr &abilityController, bool imAStabilityTest) { @@ -3858,7 +4035,7 @@ int AbilityManagerService::SetAbilityController(const sptr & return ERR_OK; } -bool AbilityManagerService::SendANRProcessID(int pid) +int AbilityManagerService::SendANRProcessID(int pid) { int anrTimeOut = amsConfigResolver_->GetANRTimeOutTime(); auto timeoutTask = [pid]() { @@ -3866,11 +4043,15 @@ bool AbilityManagerService::SendANRProcessID(int pid) HILOG_ERROR("Kill app not response process failed"); } }; + if (!SetANRMissionByProcessID(pid)) { + HILOG_ERROR("Set app not response mission record failed"); + } + handler_->PostTask(timeoutTask, "TIME_OUT_TASK", anrTimeOut); if (kill(pid, SIGUSR1) != ERR_OK) { HILOG_ERROR("Send sig to app not response process failed"); + return SEND_USR1_SIG_FAIL; } - handler_->PostTask(timeoutTask, "TIME_OUT_TASK", anrTimeOut); - return true; + return ERR_OK; } bool AbilityManagerService::IsRunningInStabilityTest() @@ -3883,7 +4064,7 @@ bool AbilityManagerService::IsRunningInStabilityTest() bool AbilityManagerService::IsAbilityControllerStart(const Want &want, const std::string &bundleName) { - if (abilityController_ != nullptr) { + if (abilityController_ != nullptr && controllerIsAStabilityTest_) { HILOG_DEBUG("%{public}s, controllerIsAStabilityTest_: %{public}d", __func__, controllerIsAStabilityTest_); bool isStart = abilityController_->AllowAbilityStart(want, bundleName); if (!isStart) { @@ -3896,9 +4077,9 @@ bool AbilityManagerService::IsAbilityControllerStart(const Want &want, const std bool AbilityManagerService::IsAbilityControllerForeground(const std::string &bundleName) { - if (abilityController_ != nullptr) { + if (abilityController_ != nullptr && controllerIsAStabilityTest_) { HILOG_DEBUG("%{public}s, controllerIsAStabilityTest_: %{public}d", __func__, controllerIsAStabilityTest_); - bool isResume = abilityController_->AllowAbilityForeground(bundleName); + bool isResume = abilityController_->AllowAbilityBackground(bundleName); if (!isResume) { HILOG_INFO("Not finishing terminate ability because controller resuming: %{public}s", bundleName.c_str()); return false; @@ -3936,20 +4117,26 @@ int32_t AbilityManagerService::InitAbilityInfoFromExtension(AppExecFwk::Extensio return 0; } -int32_t AbilityManagerService::GetAbilityInfoFromExtension(const Want &want, AppExecFwk::AbilityInfo &abilityInfo) +int32_t AbilityManagerService::GetAbilityInfoFromExtension( + const Want &want, AppExecFwk::AbilityInfo &abilityInfo, const int32_t userId) { + HILOG_DEBUG("%{public}s, userId : %{public}d", __func__, userId); ElementName elementName = want.GetElement(); std::string bundleName = elementName.GetBundleName(); std::string abilityName = elementName.GetAbilityName(); - AppExecFwk::BundleMgrClient bundleClient; AppExecFwk::BundleInfo 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; + AppExecFwk::BundleMgrClient bundleClient; + auto bundleFlag = AppExecFwk::BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO; + + if (!bundleClient.GetBundleInfo(bundleName, bundleFlag, bundleInfo, userId)) { + auto bms = GetBundleManager(); + CHECK_POINTER_AND_RETURN(bms, RESOLVE_APP_ERR); + if (!bms->GetBundleInfo(bundleName, bundleFlag, bundleInfo, userId)) { + HILOG_ERROR("Failed to get bundle info when generate ability request."); + return RESOLVE_APP_ERR; + } } bool found = false; - for (auto &extensionInfo: bundleInfo.extensionInfos) { if (extensionInfo.name != abilityName) { continue; @@ -3961,7 +4148,6 @@ int32_t AbilityManagerService::GetAbilityInfoFromExtension(const Want &want, App InitAbilityInfoFromExtension(extensionInfo, abilityInfo); break; } - return found; } @@ -4041,6 +4227,13 @@ int AbilityManagerService::GetCurrentTopAbility(sptr &token) } token = abilityRecord->GetToken(); + if (!token) { + HILOG_ERROR("Failed to get token"); + return ERR_INVALID_VALUE; + } + + HILOG_INFO("bundleName : %{public}s, abilityName : %{public}s", + bundleName.data(), abilityRecord->GetAbilityInfo().name.data()); return ERR_OK; } @@ -4050,6 +4243,11 @@ int AbilityManagerService::DelegatorDoAbilityForeground(const sptr &token, { HILOG_DEBUG("DoAbilityForeground, sceneFlag:%{public}d", flag); CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE); + if (!VerificationToken(token) && !VerificationAllToken(token)) { + HILOG_ERROR("%{public}s token error.", __func__); + return ERR_INVALID_VALUE; + } std::lock_guard guard(globalLock_); auto abilityRecord = Token::GetAbilityRecordByToken(token); CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); + int result = AbilityUtil::JudgeAbilityVisibleControl(abilityRecord->GetAbilityInfo()); + if (result != ERR_OK) { + HILOG_ERROR("%{public}s JudgeAbilityVisibleControl error.", __func__); + return result; + } + + auto type = abilityRecord->GetAbilityInfo().type; + if (type != AppExecFwk::AbilityType::PAGE) { + HILOG_ERROR("Cannot minimize except page ability."); + return ERR_INVALID_VALUE; + } + + if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) { + HILOG_ERROR("IsAbilityControllerForeground false."); + return ERR_WOULD_BLOCK; + } abilityRecord->lifeCycleStateInfo_.sceneFlag = flag; - abilityRecord->ProcessForegroundAbility(); + abilityRecord->ForegroundAbility(); abilityRecord->lifeCycleStateInfo_.sceneFlag = SCENE_FLAG_NORMAL; return ERR_OK; } @@ -4116,20 +4334,24 @@ void AbilityManagerService::UpdateCallerInfo(Want& want) want.SetParam(Want::PARAM_RESV_CALLER_PID, callerPid); } -int AbilityManagerService::CheckMultiOsAccount(const int32_t userId) +bool AbilityManagerService::JudgeMultiUserConcurrency(const AppExecFwk::AbilityInfo &info, const int32_t userId) { BYTRACE_NAME(BYTRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - bool isMultiOsAccountEnable = false; - AccountSA::OsAccountManager::IsMultiOsAccountEnable(isMultiOsAccountEnable); - HILOG_DEBUG("%{public}s isMultiOsAccountEnable = %{public}d", __func__, isMultiOsAccountEnable); - if (!isMultiOsAccountEnable) { - if (userId != GetUserId()) { - HILOG_ERROR("%{public}s userId(%{public}d) Unequal CurrentUserId(%{public}d).", __func__, - userId, GetUserId()); - return INVALID_USERID_VALUE; - } + + if (userId == U0_USER_ID) { + HILOG_DEBUG("%{public}s, userId is 0.", __func__); + return true; } - return ERR_OK; + + HILOG_DEBUG("userId : %{public}d, current userId : %{public}d", userId, GetUserId()); + + // Only non-concurrent mode is supported + bool concurrencyMode = CONCURRENCY_MODE_FALSE; + if (!concurrencyMode) { + return (userId == GetUserId()); + } + + return true; } int AbilityManagerService::GenerateAbilityRequestLocal( @@ -4148,5 +4370,145 @@ int AbilityManagerService::GenerateAbilityRequestLocal( } return result; } + +void AbilityManagerService::StartingScreenLockAbility() +{ + HILOG_DEBUG("%{public}s", __func__); + if (!iBundleManager_) { + HILOG_INFO("bms service is null"); + return; + } + + constexpr int maxAttemptNums = 5; + auto userId = GetUserId(); + int attemptNums = 1; + AppExecFwk::AbilityInfo screenLockInfo; + Want screenLockWant; + screenLockWant.SetElementName(AbilityConfig::SCREEN_LOCK_BUNDLE_NAME, AbilityConfig::SCREEN_LOCK_ABILITY_NAME); + while (!(iBundleManager_->QueryAbilityInfo(screenLockWant, + OHOS::AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_DEFAULT, userId, screenLockInfo)) && + attemptNums <= maxAttemptNums) { + HILOG_INFO("Waiting query mms service completed."); + usleep(REPOLL_TIME_MICRO_SECONDS); + attemptNums++; + } + + HILOG_INFO("attemptNums : %{public}d", attemptNums); + if (attemptNums <= maxAttemptNums) { + (void)StartAbility(screenLockWant, userId, DEFAULT_INVAL_VALUE); + } +} + +int AbilityManagerService::CheckStaticCfgPermission(AppExecFwk::AbilityInfo &abilityInfo) +{ + auto tokenId = IPCSkeleton::GetCallingTokenID(); + + if ((abilityInfo.type == AppExecFwk::AbilityType::EXTENSION && + abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::DATASHARE) || + (abilityInfo.type == AppExecFwk::AbilityType::DATA)) { + // just need check the read permission and write permission of extension ability or data ability + if (!abilityInfo.readPermission.empty()) { + int checkReadPermission = AccessTokenKit::VerifyAccessToken(tokenId, abilityInfo.readPermission); + if (checkReadPermission == ERR_OK) { + return AppExecFwk::Constants::PERMISSION_GRANTED; + } + HILOG_WARN("verify access token fail, read permission: %{public}s", abilityInfo.readPermission.c_str()); + } + if (!abilityInfo.writePermission.empty()) { + int checkWritePermission = AccessTokenKit::VerifyAccessToken(tokenId, abilityInfo.writePermission); + if (checkWritePermission == ERR_OK) { + return AppExecFwk::Constants::PERMISSION_GRANTED; + } + HILOG_WARN("verify access token fail, write permission: %{public}s", abilityInfo.writePermission.c_str()); + } + + if (!abilityInfo.readPermission.empty() || !abilityInfo.writePermission.empty()) { + // 'readPermission' and 'writePermission' take precedence over 'permission' + // when 'readPermission' or 'writePermission' is not empty, no need check 'permission' + return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; + } + } + + // verify permission if 'permission' is not empty + if (abilityInfo.permissions.empty()) { + return AppExecFwk::Constants::PERMISSION_GRANTED; + } + + for (auto permission : abilityInfo.permissions) { + if (AccessTokenKit::VerifyAccessToken(tokenId, permission) + != AppExecFwk::Constants::PERMISSION_GRANTED) { + HILOG_ERROR("verify access token fail, permission: %{public}s", permission.c_str()); + return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; + } + } + + return AppExecFwk::Constants::PERMISSION_GRANTED; +} + +bool AbilityManagerService::VerifyUriPermisson(const AbilityRequest &abilityRequest, const Want &want) +{ + if (abilityRequest.abilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::FILESHARE) { + HILOG_DEBUG("Only FILESHARE need to Verify uri permission."); + return true; + } + auto uriStr = want.GetUri().ToString(); + auto uriVec = want.GetStringArrayParam(AbilityConfig::PARAMS_STREAM); + uriVec.emplace_back(uriStr); + auto targetTokenId = IPCSkeleton::GetCallingTokenID(); + auto uriPermMgrClient = AAFwk::UriPermissionManagerClient::GetInstance(); + for (auto str : uriVec) { + Uri uri(str); + if (uriPermMgrClient->VerifyUriPermission(uri, Want::FLAG_AUTH_WRITE_URI_PERMISSION, targetTokenId)) { + return true; + } + if (uriPermMgrClient->VerifyUriPermission(uri, Want::FLAG_AUTH_READ_URI_PERMISSION, targetTokenId)) { + return true; + } + } + return false; +} + +bool AbilityManagerService::SetANRMissionByProcessID(int pid) +{ + std::vector> tokens; + if (appScheduler_->GetAbilityRecordsByProcessID(pid, tokens) != ERR_OK) { + HILOG_ERROR("Get ability record failed."); + return false; + } + if (appScheduler_) { + for (auto &item : tokens) { + auto abilityRecord = currentMissionListManager_->GetAbilityRecordByToken(item); + auto mission = abilityRecord->GetMission(); + mission->SetANRState(); + } + return true; + } + return false; +} + +void AbilityManagerService::StartupResidentProcess() +{ + // Location may change + auto bms = GetBundleManager(); + if (bms == nullptr) { + HILOG_INFO("StartupResidentProcess bms is nullptr"); + return; + } + + std::vector bundleInfos; + (void)iBundleManager_->QueryKeepAliveBundleInfos(bundleInfos); + for (auto bundleInfo : bundleInfos) { + for (auto hapModuleInfo : bundleInfo.hapModuleInfos) { + if (!hapModuleInfo.mainElementName.empty()) { + AppExecFwk::AbilityInfo abilityInfo; + Want want; + want.SetElementName(hapModuleInfo.bundleName, hapModuleInfo.mainElementName); + (void)StartAbility(want, USER_ID_NO_HEAD, DEFAULT_INVAL_VALUE); // user 0 + } + } + } + + DelayedSingleton::GetInstance()->StartupResidentProcess(); +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_manager_stub.cpp b/services/abilitymgr/src/ability_manager_stub.cpp index d9088839c36d2b4c77dced73dbe1bf51d5cf4559..c3377113091186686ac8894990618a93a965e677 100644 --- a/services/abilitymgr/src/ability_manager_stub.cpp +++ b/services/abilitymgr/src/ability_manager_stub.cpp @@ -125,6 +125,7 @@ void AbilityManagerStub::SecondStepInit() requestFuncMap_[CLEAN_MISSION] = &AbilityManagerStub::CleanMissionInner; requestFuncMap_[CLEAN_ALL_MISSIONS] = &AbilityManagerStub::CleanAllMissionsInner; requestFuncMap_[MOVE_MISSION_TO_FRONT] = &AbilityManagerStub::MoveMissionToFrontInner; + requestFuncMap_[MOVE_MISSION_TO_FRONT_BY_OPTIONS] = &AbilityManagerStub::MoveMissionToFrontByOptionsInner; requestFuncMap_[START_CALL_ABILITY] = &AbilityManagerStub::StartAbilityByCallInner; requestFuncMap_[RELEASE_CALL_ABILITY] = &AbilityManagerStub::ReleaseInner; requestFuncMap_[SET_MISSION_LABEL] = &AbilityManagerStub::SetMissionLabelInner; @@ -176,7 +177,13 @@ int AbilityManagerStub::TerminateAbilityInner(MessageParcel &data, MessageParcel sptr token = data.ReadParcelable(); int resultCode = data.ReadInt32(); Want *resultWant = data.ReadParcelable(); - int32_t result = TerminateAbility(token, resultCode, resultWant); + bool flag = data.ReadBool(); + int32_t result; + if (flag) { + result = TerminateAbility(token, resultCode, resultWant); + } else { + result = CloseAbility(token, resultCode, resultWant); + } reply.WriteInt32(result); if (resultWant != nullptr) { delete resultWant; @@ -1148,9 +1155,25 @@ int AbilityManagerStub::MoveMissionToFrontInner(MessageParcel &data, MessageParc return NO_ERROR; } +int AbilityManagerStub::MoveMissionToFrontByOptionsInner(MessageParcel &data, MessageParcel &reply) +{ + int32_t missionId = data.ReadInt32(); + StartOptions *startOptions = data.ReadParcelable(); + if (startOptions == nullptr) { + HILOG_ERROR("startOptions is nullptr"); + return ERR_INVALID_VALUE; + } + int result = MoveMissionToFront(missionId, *startOptions); + if (!reply.WriteInt32(result)) { + HILOG_ERROR("MoveMissionToFront failed."); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + int AbilityManagerStub::StartAbilityByCallInner(MessageParcel &data, MessageParcel &reply) { - + HILOG_DEBUG("AbilityManagerStub::StartAbilityByCallInner begin."); Want *want = data.ReadParcelable(); if (want == nullptr) { @@ -1166,7 +1189,7 @@ int AbilityManagerStub::StartAbilityByCallInner(MessageParcel &data, MessageParc reply.WriteInt32(result); delete want; - + HILOG_DEBUG("AbilityManagerStub::StartAbilityByCallInner end."); return NO_ERROR; @@ -1482,8 +1505,8 @@ int AbilityManagerStub::DoAbilityBackgroundInner(MessageParcel &data, MessagePar int AbilityManagerStub::SendANRProcessIDInner(MessageParcel &data, MessageParcel &reply) { int32_t pid = data.ReadInt32(); - bool result = SendANRProcessID(pid); - if (!reply.WriteBool(result)) { + int32_t result = SendANRProcessID(pid); + if (!reply.WriteInt32(result)) { HILOG_ERROR("reply write failed."); return ERR_INVALID_VALUE; } diff --git a/services/abilitymgr/src/ability_record.cpp b/services/abilitymgr/src/ability_record.cpp index 90c73efb5bda9d2bf5b4be75508c4a9429c2603b..b6c7368fab11c9440ac8deeeb2ecc54aa412a0f8 100644 --- a/services/abilitymgr/src/ability_record.cpp +++ b/services/abilitymgr/src/ability_record.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -22,9 +22,12 @@ #include "ability_manager_service.h" #include "ability_scheduler_stub.h" #include "ability_util.h" +#include "bundle_mgr_client.h" #include "bytrace.h" #include "errors.h" #include "hilog_wrapper.h" +#include "os_account_manager.h" +#include "uri_permission_manager_client.h" namespace OHOS { namespace AAFwk { @@ -187,7 +190,7 @@ int AbilityRecord::LoadAbility() } } return DelayedSingleton::GetInstance()->LoadAbility( - token_, callerToken_, abilityInfo_, applicationInfo_); + token_, callerToken_, abilityInfo_, applicationInfo_, want_); } void AbilityRecord::ForegroundAbility() @@ -688,6 +691,7 @@ void AbilityRecord::SendResult() CHECK_POINTER(scheduler_); CHECK_POINTER(result_); scheduler_->SendResult(result_->requestCode_, result_->resultCode_, result_->resultWant_); + GrantUriPermission(result_->resultWant_); // reset result to avoid send result next time result_.reset(); } @@ -922,7 +926,8 @@ void AbilityRecord::Dump(std::vector &info) } } -void AbilityRecord::DumpAbilityState(std::vector &info, bool isClient) +void AbilityRecord::DumpAbilityState( + std::vector &info, bool isClient, const std::vector ¶ms) { HILOG_INFO("%{public}s begin.", __func__); std::string dumpInfo = " AbilityRecord ID #" + std::to_string(recordId_); @@ -946,6 +951,11 @@ void AbilityRecord::DumpAbilityState(std::vector &info, bool isClie dumpInfo = " ready #" + std::to_string(isReady_) + " window attached #" + std::to_string(isWindowAttached_) + " launcher #" + std::to_string(isLauncherAbility_); info.push_back(dumpInfo); + dumpInfo = " callee connections: "; + info.push_back(dumpInfo); + if (callContainer_) { + callContainer_->Dump(info); + } if (isLauncherRoot_ && IsNewVersion()) { dumpInfo = " can restart num #" + std::to_string(restartCount_); @@ -954,7 +964,10 @@ void AbilityRecord::DumpAbilityState(std::vector &info, bool isClie // add dump client info if (isClient && scheduler_ && isReady_) { - scheduler_->DumpAbilityInfo(info); + scheduler_->DumpAbilityInfo(params, info); + if (!params.empty()) { + return; + } AppExecFwk::Configuration config; if (DelayedSingleton::GetInstance()->GetConfiguration(config) == ERR_OK) { info.emplace_back(" configuration: " + config.GetName()); @@ -992,7 +1005,8 @@ void AbilityRecord::DumpService(std::vector &info, bool isClient) c } // add dump client info if (isClient && scheduler_ && isReady_) { - scheduler_->DumpAbilityInfo(info); + std::vector params; + scheduler_->DumpAbilityInfo(params, info); AppExecFwk::Configuration config; if (DelayedSingleton::GetInstance()->GetConfiguration(config) == ERR_OK) { info.emplace_back(" configuration: " + config.GetName()); @@ -1029,7 +1043,11 @@ void AbilityRecord::GetAbilityRecordInfo(AbilityRecordInfo &recordInfo) void AbilityRecord::OnSchedulerDied(const wptr &remote) { - HILOG_DEBUG("On scheduler died."); + HILOG_WARN("On scheduler died."); + auto mission = GetMission(); + if (mission) { + HILOG_WARN("On scheduler died. Is app not response Reason:%{public}d", mission->IsANRState()); + } CHECK_POINTER(scheduler_); auto object = remote.promote(); @@ -1292,7 +1310,7 @@ void AbilityRecord::SetLastExitReason(const LastExitReason &reason) lifeCycleStateInfo_.launchParam.lastExitReason = reason; } -void AbilityRecord::NotifyContinuationResult(const int32_t result) +void AbilityRecord::NotifyContinuationResult(int32_t result) { HILOG_INFO("NotifyContinuationResult."); CHECK_POINTER(lifecycleDeal_); @@ -1557,5 +1575,98 @@ bool AbilityRecord::IsSwitchingPause() { return isSwitchingPause_; } + +void AbilityRecord::DumpSys(std::vector &info, bool isClient) +{ + std::string dumpInfo = " AbilityRecord ID #" + std::to_string(recordId_); + info.push_back(dumpInfo); + dumpInfo = " app name [" + GetAbilityInfo().applicationName + "]"; + info.push_back(dumpInfo); + dumpInfo = " main name [" + GetAbilityInfo().name + "]"; + info.push_back(dumpInfo); + dumpInfo = " bundle name [" + GetAbilityInfo().bundleName + "]"; + info.push_back(dumpInfo); + std::string typeStr; + GetAbilityTypeString(typeStr); + dumpInfo = " ability type [" + typeStr + "]"; + info.push_back(dumpInfo); + std::shared_ptr preAbility = GetPreAbilityRecord(); + if (preAbility == nullptr) { + dumpInfo = " previous ability app name [NULL]" + LINE_SEPARATOR; + dumpInfo += " previous ability file name [NULL]"; + } else { + dumpInfo = + " previous ability app name [" + preAbility->GetAbilityInfo().applicationName + "]" + LINE_SEPARATOR; + dumpInfo += " previous ability file name [" + preAbility->GetAbilityInfo().name + "]"; + } + info.push_back(dumpInfo); + std::shared_ptr nextAbility = GetNextAbilityRecord(); + if (nextAbility == nullptr) { + dumpInfo = " next ability app name [NULL]" + LINE_SEPARATOR; + dumpInfo += " next ability file name [NULL]"; + } else { + dumpInfo = + " next ability app name [" + nextAbility->GetAbilityInfo().applicationName + "]" + LINE_SEPARATOR; + dumpInfo += " next ability main name [" + nextAbility->GetAbilityInfo().name + "]"; + } + info.push_back(dumpInfo); + dumpInfo = " state #" + AbilityRecord::ConvertAbilityState(GetAbilityState()) + " start time [" + + std::to_string(startTime_) + "]"; + info.push_back(dumpInfo); + dumpInfo = " app state #" + AbilityRecord::ConvertAppState(appState_); + info.push_back(dumpInfo); + dumpInfo = " ready #" + std::to_string(isReady_) + " window attached #" + + std::to_string(isWindowAttached_) + " launcher #" + std::to_string(isLauncherAbility_); + info.push_back(dumpInfo); + + if (isLauncherRoot_ && IsNewVersion()) { + dumpInfo = " can restart num #" + std::to_string(restartCount_); + info.push_back(dumpInfo); + } + DumpClientInfo(info, isClient); +} + +void AbilityRecord::DumpClientInfo(std::vector &info, bool isClient) +{ + if (isClient && scheduler_ && isReady_) { + std::vector params; + scheduler_->DumpAbilityInfo(params, info); + AppExecFwk::Configuration config; + if (DelayedSingleton::GetInstance()->GetConfiguration(config) == ERR_OK) { + info.emplace_back(" configuration: " + config.GetName()); + } + } +} + +void AbilityRecord::GrantUriPermission(const Want &want) +{ + HILOG_DEBUG("AbilityRecord::GrantUriPermission is called."); + auto flags = want.GetFlags(); + if (flags & (Want::FLAG_AUTH_READ_URI_PERMISSION | Want::FLAG_AUTH_WRITE_URI_PERMISSION)) { + HILOG_INFO("Want to grant r/w permission of the uri"); + auto targetTokenId = abilityInfo_.applicationInfo.accessTokenId; + auto abilityMgr = DelayedSingleton::GetInstance(); + if (abilityMgr) { + abilityMgr->GrantUriPermission(want, GetCurrentAccountId(), targetTokenId); + } + } +} + +int AbilityRecord::GetCurrentAccountId() +{ + std::vector osActiveAccountIds; + ErrCode ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(osActiveAccountIds); + if (ret != ERR_OK) { + HILOG_ERROR("QueryActiveOsAccountIds failed."); + return DEFAULT_USER_ID; + } + + if (osActiveAccountIds.empty()) { + HILOG_ERROR("QueryActiveOsAccountIds is empty, no accounts."); + return DEFAULT_USER_ID; + } + + return osActiveAccountIds.front(); +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_scheduler_proxy.cpp b/services/abilitymgr/src/ability_scheduler_proxy.cpp index c95d108a3ee91392b4f3d27a6d0277e701f60079..557d9c42a522b16d0c59541443ef2f3fd02792c3 100755 --- a/services/abilitymgr/src/ability_scheduler_proxy.cpp +++ b/services/abilitymgr/src/ability_scheduler_proxy.cpp @@ -41,7 +41,7 @@ void AbilitySchedulerProxy::ScheduleAbilityTransaction(const Want &want, const L { MessageParcel data; MessageParcel reply; - MessageOption option; + MessageOption option(MessageOption::TF_ASYNC); if (!WriteInterfaceToken(data)) { return; } @@ -49,7 +49,7 @@ void AbilitySchedulerProxy::ScheduleAbilityTransaction(const Want &want, const L data.WriteParcelable(&stateInfo); int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_ABILITY_TRANSACTION, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("ScheduleAbilityTransaction fail to SendRequest. err: %d", err); + HILOG_ERROR("ScheduleAbilityTransaction fail to SendRequest. err: %{public}d", err); } } @@ -69,7 +69,7 @@ void AbilitySchedulerProxy::SendResult(int requestCode, int resultCode, const Wa } int32_t err = Remote()->SendRequest(IAbilityScheduler::SEND_RESULT, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("SendResult fail to SendRequest. err: %d", err); + HILOG_ERROR("SendResult fail to SendRequest. err: %{public}d", err); } } @@ -87,7 +87,7 @@ void AbilitySchedulerProxy::ScheduleConnectAbility(const Want &want) } int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_ABILITY_CONNECT, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("ScheduleConnectAbility fail to SendRequest. err: %d", err); + HILOG_ERROR("ScheduleConnectAbility fail to SendRequest. err: %{public}d", err); } } @@ -106,7 +106,7 @@ void AbilitySchedulerProxy::ScheduleDisconnectAbility(const Want &want) int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_ABILITY_DISCONNECT, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("ScheduleDisconnectAbility fail to SendRequest. err: %d", err); + HILOG_ERROR("ScheduleDisconnectAbility fail to SendRequest. err: %{public}d", err); } } @@ -134,7 +134,7 @@ void AbilitySchedulerProxy::ScheduleCommandAbility(const Want &want, bool restar int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_ABILITY_COMMAND, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("ScheduleCommandAbility fail to SendRequest. err: %d", err); + HILOG_ERROR("ScheduleCommandAbility fail to SendRequest. err: %{public}d", err); } } @@ -148,7 +148,7 @@ void AbilitySchedulerProxy::ScheduleSaveAbilityState() } int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_SAVE_ABILITY_STATE, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("ScheduleSaveAbilityState fail to SendRequest. err: %d", err); + HILOG_ERROR("ScheduleSaveAbilityState fail to SendRequest. err: %{public}d", err); } } @@ -166,7 +166,7 @@ void AbilitySchedulerProxy::ScheduleRestoreAbilityState(const PacMap &inState) } int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_RESTORE_ABILITY_STATE, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("ScheduleRestoreAbilityState fail to SendRequest. err: %d", err); + HILOG_ERROR("ScheduleRestoreAbilityState fail to SendRequest. err: %{public}d", err); } } @@ -184,7 +184,7 @@ void AbilitySchedulerProxy::ScheduleUpdateConfiguration(const AppExecFwk::Config } int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_UPDATE_CONFIGURATION, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("ScheduleRestoreAbilityState fail to SendRequest. err: %d", err); + HILOG_ERROR("ScheduleRestoreAbilityState fail to SendRequest. err: %{public}d", err); } } @@ -220,7 +220,7 @@ std::vector AbilitySchedulerProxy::GetFileTypes(const Uri &uri, con int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_GETFILETYPES, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("GetFileTypes fail to SendRequest. err: %d", err); + HILOG_ERROR("GetFileTypes fail to SendRequest. err: %{public}d", err); } if (!reply.ReadStringVector(&types)) { @@ -265,7 +265,7 @@ int AbilitySchedulerProxy::OpenFile(const Uri &uri, const std::string &mode) int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_OPENFILE, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("OpenFile fail to SendRequest. err: %d", err); + HILOG_ERROR("OpenFile fail to SendRequest. err: %{public}d", err); return fd; } @@ -314,7 +314,7 @@ int AbilitySchedulerProxy::OpenRawFile(const Uri &uri, const std::string &mode) int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_OPENRAWFILE, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("OpenFile fail to SendRequest. err: %d", err); + HILOG_ERROR("OpenFile fail to SendRequest. err: %{public}d", err); return fd; } @@ -358,7 +358,7 @@ int AbilitySchedulerProxy::Insert(const Uri &uri, const NativeRdb::ValuesBucket int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_INSERT, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("Insert fail to SendRequest. err: %d", err); + HILOG_ERROR("Insert fail to SendRequest. err: %{public}d", err); return index; } @@ -379,7 +379,8 @@ int AbilitySchedulerProxy::Insert(const Uri &uri, const NativeRdb::ValuesBucket * * @return Returns the number of data records updated. */ -int AbilitySchedulerProxy::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) +int AbilitySchedulerProxy::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, + const NativeRdb::DataAbilityPredicates &predicates) { int index = -1; @@ -408,7 +409,7 @@ int AbilitySchedulerProxy::Update(const Uri &uri, const NativeRdb::ValuesBucket int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_UPDATE, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("Update fail to SendRequest. err: %d", err); + HILOG_ERROR("Update fail to SendRequest. err: %{public}d", err); return index; } @@ -452,7 +453,7 @@ int AbilitySchedulerProxy::Delete(const Uri &uri, const NativeRdb::DataAbilityPr int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_DELETE, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("Delete fail to SendRequest. err: %d", err); + HILOG_ERROR("Delete fail to SendRequest. err: %{public}d", err); return index; } @@ -501,7 +502,7 @@ std::shared_ptr AbilitySchedulerProxy::Query( int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_QUERY, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("Query fail to SendRequest. err: %d", err); + HILOG_ERROR("Query fail to SendRequest. err: %{public}d", err); return nullptr; } return OHOS::NativeRdb::ISharedResultSet::ReadFromParcel(reply); @@ -534,7 +535,7 @@ std::string AbilitySchedulerProxy::GetType(const Uri &uri) int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_GETTYPE, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("GetFileTypes fail to SendRequest. err: %d", err); + HILOG_ERROR("GetFileTypes fail to SendRequest. err: %{public}d", err); return type; } @@ -581,7 +582,7 @@ bool AbilitySchedulerProxy::Reload(const Uri &uri, const PacMap &extras) int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_RELOAD, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("GetFileTypes fail to SendRequest. err: %d", err); + HILOG_ERROR("GetFileTypes fail to SendRequest. err: %{public}d", err); return ret; } @@ -634,7 +635,7 @@ int AbilitySchedulerProxy::BatchInsert(const Uri &uri, const std::vectorSendRequest(IAbilityScheduler::SCHEDULE_BATCHINSERT, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("GetFileTypes fail to SendRequest. err: %d", err); + HILOG_ERROR("GetFileTypes fail to SendRequest. err: %{public}d", err); return ret; } @@ -670,7 +671,7 @@ void AbilitySchedulerProxy::NotifyMultiWinModeChanged(int32_t winModeKey, bool f } int32_t err = Remote()->SendRequest(IAbilityScheduler::MULTI_WIN_CHANGED, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("NotifyMultiWinModeChanged fail to SendRequest. err: %d", err); + HILOG_ERROR("NotifyMultiWinModeChanged fail to SendRequest. err: %{public}d", err); } } @@ -798,7 +799,7 @@ void AbilitySchedulerProxy::NotifyTopActiveAbilityChanged(bool flag) } int32_t err = Remote()->SendRequest(IAbilityScheduler::TOP_ACTIVE_ABILITY_CHANGED, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("NotifyTopActiveAbilityChanged fail to SendRequest. err: %d", err); + HILOG_ERROR("NotifyTopActiveAbilityChanged fail to SendRequest. err: %{public}d", err); } } @@ -834,7 +835,7 @@ Uri AbilitySchedulerProxy::NormalizeUri(const Uri &uri) int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_NORMALIZEURI, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("NormalizeUri fail to SendRequest. err: %d", err); + HILOG_ERROR("NormalizeUri fail to SendRequest. err: %{public}d", err); return Uri(""); } @@ -875,7 +876,7 @@ Uri AbilitySchedulerProxy::DenormalizeUri(const Uri &uri) int32_t err = Remote()->SendRequest(IAbilityScheduler::SCHEDULE_DENORMALIZEURI, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("DenormalizeUri fail to SendRequest. err: %d", err); + HILOG_ERROR("DenormalizeUri fail to SendRequest. err: %{public}d", err); return Uri(""); } @@ -957,7 +958,7 @@ void AbilitySchedulerProxy::ContinueAbility(const std::string& deviceId) int32_t err = Remote()->SendRequest(IAbilityScheduler::CONTINUE_ABILITY, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("ContinueAbility fail to SendRequest. err: %d", err); + HILOG_ERROR("ContinueAbility fail to SendRequest. err: %{public}d", err); } } @@ -977,11 +978,11 @@ void AbilitySchedulerProxy::NotifyContinuationResult(int32_t result) int32_t err = Remote()->SendRequest(IAbilityScheduler::NOTIFY_CONTINUATION_RESULT, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("NotifyContinuationResult fail to SendRequest. err: %d", err); + HILOG_ERROR("NotifyContinuationResult fail to SendRequest. err: %{public}d", err); } } -void AbilitySchedulerProxy::DumpAbilityInfo(std::vector &info) +void AbilitySchedulerProxy::DumpAbilityInfo(const std::vector ¶ms, std::vector &info) { MessageParcel data; MessageParcel reply; @@ -991,9 +992,14 @@ void AbilitySchedulerProxy::DumpAbilityInfo(std::vector &info) return; } + if (!data.WriteStringVector(params)) { + HILOG_ERROR("DumpAbilityRunner fail to write params"); + return; + } + int32_t err = Remote()->SendRequest(IAbilityScheduler::DUMP_ABILITY_RUNNER_INNER, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("DumpAbilityRunner fail to SendRequest. err: %d", err); + HILOG_ERROR("DumpAbilityRunner fail to SendRequest. err: %{public}d", err); } int32_t stackNum = reply.ReadInt32(); @@ -1017,7 +1023,7 @@ sptr AbilitySchedulerProxy::CallRequest() int32_t err = Remote()->SendRequest(IAbilityScheduler::REQUEST_CALL_REMOTE, data, reply, option); if (err != NO_ERROR) { - HILOG_ERROR("CallRequest fail to SendRequest. err: %d", err); + HILOG_ERROR("CallRequest fail to SendRequest. err: %{public}d", err); return nullptr; } diff --git a/services/abilitymgr/src/ability_scheduler_stub.cpp b/services/abilitymgr/src/ability_scheduler_stub.cpp index e72008a219afa220a12a33610a3d42095d322274..89e19940414d40019d3d127e4c5bf403428909a0 100644 --- a/services/abilitymgr/src/ability_scheduler_stub.cpp +++ b/services/abilitymgr/src/ability_scheduler_stub.cpp @@ -580,10 +580,13 @@ int AbilitySchedulerStub::NotifyContinuationResultInner(MessageParcel &data, Mes int AbilitySchedulerStub::DumpAbilityInfoInner(MessageParcel &data, MessageParcel &reply) { - std::vector infos; - - DumpAbilityInfo(infos); + std::vector params; + if (!data.ReadStringVector(¶ms)) { + HILOG_INFO("DumpAbilityInfoInner read params error"); + return NO_ERROR; + } + DumpAbilityInfo(params, infos); for (const auto & infostep:infos) { HILOG_INFO("DumpAbilityInfoInner infos = %{public}s", infostep.c_str()); diff --git a/services/abilitymgr/src/ability_stack_manager.cpp b/services/abilitymgr/src/ability_stack_manager.cpp index 2ffbcc83a8946f7f10bba1d7a41f24667eafd4e4..05e8121db5ce6386e91c19f9470957d640998e0e 100644 --- a/services/abilitymgr/src/ability_stack_manager.cpp +++ b/services/abilitymgr/src/ability_stack_manager.cpp @@ -97,8 +97,8 @@ int AbilityStackManager::StartAbility(const AbilityRequest &abilityRequest) auto abilityInfo = abilityRequest.abilityInfo; auto type = abilityInfo.type; if (abilityInfo.applicationInfo.isLauncherApp && type == AppExecFwk::AbilityType::PAGE && currentTopAbilityRecord && - AbilityUtil::IsSystemDialogAbility( - currentTopAbilityRecord->GetAbilityInfo().bundleName, currentTopAbilityRecord->GetAbilityInfo().name)) { + AbilityUtil::IsSystemDialogAbility(currentTopAbilityRecord->GetAbilityInfo().bundleName, + currentTopAbilityRecord->GetAbilityInfo().name)) { HILOG_ERROR("Page ability is dialog type, cannot return to luncher."); return ERR_INVALID_VALUE; } @@ -1480,6 +1480,10 @@ void AbilityStackManager::CompleteActive(const std::shared_ptr &a auto self(shared_from_this()); auto startWaittingAbilityTask = [self]() { self->StartWaittingAbility(); }; auto handler = DelayedSingleton::GetInstance()->GetEventHandler(); + if (handler == nullptr) { + HILOG_ERROR("handler is nullptr."); + return; + } // multi window moving, complete state. if (abilityRecord->GetInMovingState()) { @@ -2735,20 +2739,26 @@ void AbilityStackManager::HandleAbilityDied(std::shared_ptr abili auto stack = mission->GetMissionStack(); if (IsSplitScreenStack(stack->GetMissionStackId())) { auto friendMission = GetFriendMissionBySplitScreen(stack, mission->GetMissionRecordId()); + if (friendMission == nullptr) { + HILOG_ERROR("friendMission is null."); + return; + } auto friendStack = friendMission->GetMissionStack(); - if (friendMission && friendStack) { - UpdateMissionOption(friendMission, defaultMissionStack_, - AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FULLSCREEN); - - friendStack->RemoveMissionRecord(friendMission->GetMissionRecordId()); - defaultMissionStack_->AddMissionRecordToEnd(friendMission); - - auto friendTopAbility = friendMission->GetTopAbilityRecord(); - if (friendTopAbility && - (friendTopAbility->IsAbilityState(ACTIVE) || friendTopAbility->IsAbilityState(ACTIVATING))) { - friendTopAbility->SetMovingBackgroundFlag(true); - friendTopAbility->Inactivate(); - } + if (friendStack == nullptr) { + HILOG_ERROR("friendStack is null."); + return; + } + UpdateMissionOption(friendMission, defaultMissionStack_, + AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FULLSCREEN); + + friendStack->RemoveMissionRecord(friendMission->GetMissionRecordId()); + defaultMissionStack_->AddMissionRecordToEnd(friendMission); + + auto friendTopAbility = friendMission->GetTopAbilityRecord(); + if (friendTopAbility && + (friendTopAbility->IsAbilityState(ACTIVE) || friendTopAbility->IsAbilityState(ACTIVATING))) { + friendTopAbility->SetMovingBackgroundFlag(true); + friendTopAbility->Inactivate(); } } RemoveMissionRecordById(mission->GetMissionRecordId()); diff --git a/services/abilitymgr/src/ams_configuration_parameter.cpp b/services/abilitymgr/src/ams_configuration_parameter.cpp index 49d1ef168c43031354791c275e77ca5aeb68b655..889dbc03af8d478d1d441c5a5505e75777346234 100644 --- a/services/abilitymgr/src/ams_configuration_parameter.cpp +++ b/services/abilitymgr/src/ams_configuration_parameter.cpp @@ -37,6 +37,11 @@ bool AmsConfigurationParameter::GetStartSettingsDataState() const return canStartSettingsData_; } +bool AmsConfigurationParameter::GetStartScreenLockState() const +{ + return canStartScreenLock_; +} + bool AmsConfigurationParameter::GetStatusBarState() const { return canStartUiStatusBar_; @@ -149,6 +154,7 @@ int AmsConfigurationParameter::LoadAppConfigurationForStartUpService(nlohmann::j if (Object.contains(AmsConfig::SERVICE_ITEM_AMS)) { canStartLauncher_ = Object.at(AmsConfig::SERVICE_ITEM_AMS).at(AmsConfig::STARTUP_LAUNCHER).get(); canStartSettingsData_ = Object.at(AmsConfig::SERVICE_ITEM_AMS).at(AmsConfig::STARTUP_SETTINGS_DATA).get(); + canStartScreenLock_ = Object.at(AmsConfig::SERVICE_ITEM_AMS).at(AmsConfig::STARTUP_SCREEN_LOCK).get(); canStartUiStatusBar_ = Object.at(AmsConfig::SERVICE_ITEM_AMS).at(AmsConfig::STARTUP_STATUS_BAR).get(); canStartUiNavigationBar_ = Object.at(AmsConfig::SERVICE_ITEM_AMS).at(AmsConfig::STARTUP_NAVIGATION_BAR).get(); diff --git a/services/abilitymgr/src/app_scheduler.cpp b/services/abilitymgr/src/app_scheduler.cpp index e047ef049f228babb666226ec7fbb06a74221c94..e75536398bb0a3aac3f0b2f4f0222bfca2c2b053 100644 --- a/services/abilitymgr/src/app_scheduler.cpp +++ b/services/abilitymgr/src/app_scheduler.cpp @@ -74,13 +74,13 @@ bool AppScheduler::Init(const std::weak_ptr &callback) } int AppScheduler::LoadAbility(const sptr &token, const sptr &preToken, - const AppExecFwk::AbilityInfo &abilityInfo, const AppExecFwk::ApplicationInfo &applicationInfo) + const AppExecFwk::AbilityInfo &abilityInfo, const AppExecFwk::ApplicationInfo &applicationInfo, const Want &want) { HILOG_DEBUG("Load ability."); CHECK_POINTER_AND_RETURN(appMgrClient_, INNER_ERR); /* because the errcode type of AppMgr Client API will be changed to int, * so must to covert the return result */ - int ret = static_cast(appMgrClient_->LoadAbility(token, preToken, abilityInfo, applicationInfo)); + int ret = static_cast(appMgrClient_->LoadAbility(token, preToken, abilityInfo, applicationInfo, want)); if (ret != ERR_OK) { HILOG_ERROR("AppScheduler fail to LoadAbility. ret %d", ret); return INNER_ERR; @@ -340,5 +340,17 @@ int AppScheduler::GetConfiguration(AppExecFwk::Configuration &config) return ERR_OK; } + +int AppScheduler::GetAbilityRecordsByProcessID(const int pid, std::vector> &tokens) +{ + CHECK_POINTER_AND_RETURN(appMgrClient_, INNER_ERR); + auto ret = static_cast(appMgrClient_->GetAbilityRecordsByProcessID(pid, tokens)); + if (ret != ERR_OK) { + HILOG_ERROR("GetAbilityRecordsByProcessID failed."); + return INNER_ERR; + } + + return ERR_OK; +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/call_container.cpp b/services/abilitymgr/src/call_container.cpp index 5782444019f58ba715e1cc91b7ac57984e0120ad..4657a6051f277f7de6a49d5310c433de7baa2102 100644 --- a/services/abilitymgr/src/call_container.cpp +++ b/services/abilitymgr/src/call_container.cpp @@ -1,189 +1,195 @@ -/* - * 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 "call_container.h" - -#include "hilog_wrapper.h" -#include "ability_manager_errors.h" -#include "ability_connect_callback_stub.h" -#include "ability_util.h" -#include "ability_event_handler.h" -#include "ability_manager_service.h" - -namespace OHOS { -namespace AAFwk { -CallContainer::CallContainer() -{} - -CallContainer::~CallContainer() -{ - std::for_each(deathRecipientMap_.begin(), - deathRecipientMap_.end(), - [&](RecipientMapType::reference recipient) { - recipient.first->RemoveDeathRecipient(recipient.second); - }); - - deathRecipientMap_.clear(); - callRecordMap_.clear(); -} - -void CallContainer::AddCallRecord(const sptr & connect, - const std::shared_ptr& callRecord) -{ - CHECK_POINTER(callRecord); - CHECK_POINTER(connect); - CHECK_POINTER(connect->AsObject()); - - auto iter = callRecordMap_.find(connect->AsObject()); - if (iter != callRecordMap_.end()) { - RemoveConnectDeathRecipient(connect); - callRecordMap_.erase(callRecordMap_.find(connect->AsObject())); - } - - AddConnectDeathRecipient(connect); - callRecord->SetConCallBack(connect); - callRecordMap_.emplace(connect->AsObject(), callRecord); - - HILOG_DEBUG("Add call record to callcontainer, target: %{public}s", - callRecord->GetTargetServiceName().GetURI().c_str()); -} - -std::shared_ptr CallContainer::GetCallRecord(const sptr & connect) const -{ - CHECK_POINTER_AND_RETURN(connect, nullptr); - CHECK_POINTER_AND_RETURN(connect->AsObject(), nullptr); - - auto mapIter = callRecordMap_.find(connect->AsObject()); - if (mapIter != callRecordMap_.end()) { - return mapIter->second; - } - - return nullptr; -} - -bool CallContainer::RemoveCallRecord(const sptr & connect) -{ - HILOG_DEBUG("call container release call record by callback."); - CHECK_POINTER_AND_RETURN(connect, nullptr); - CHECK_POINTER_AND_RETURN(connect->AsObject(), nullptr); - - auto iter = callRecordMap_.find(connect->AsObject()); - if (iter != callRecordMap_.end()) { - auto callrecord = iter->second; - if (callrecord) { - callrecord->SchedulerDisConnectDone(); - } - RemoveConnectDeathRecipient(connect); - callRecordMap_.erase(callRecordMap_.find(connect->AsObject())); - HILOG_DEBUG("remove call record is success."); - return true; - } - - if (callRecordMap_.empty()) { - // notify soft resouce service. - HILOG_DEBUG("this ability has no callrecord."); - } - - HILOG_WARN("remove call record is not exist."); - return false; -} - -void CallContainer::OnConnectionDied(const wptr & remote) -{ - HILOG_WARN("Call back is died."); - auto object = remote.promote(); - CHECK_POINTER(object); - - std::shared_ptr callRecord = nullptr; - auto mapIter = callRecordMap_.find(object); - if (mapIter != callRecordMap_.end()) { - callRecord = mapIter->second; - } - - auto abilityManagerService = DelayedSingleton::GetInstance(); - CHECK_POINTER(abilityManagerService); - auto handler = abilityManagerService->GetEventHandler(); - CHECK_POINTER(handler); - auto task = [abilityManagerService, callRecord]() { - abilityManagerService->OnCallConnectDied(callRecord); - }; - handler->PostTask(task); -} - -bool CallContainer::CallRequestDone(const sptr & callStub) -{ - HILOG_INFO("Call Request Done start."); - - CHECK_POINTER_AND_RETURN(callStub, false); - - std::for_each(callRecordMap_.begin(), - callRecordMap_.end(), - [&callStub](CallMapType::reference service) { - std::shared_ptr callRecord = service.second; - if (callRecord && callRecord->IsCallState(CallState::REQUESTING)) { - callRecord->SetCallStub(callStub); - callRecord->SchedulerConnectDone(); - } - }); - - HILOG_INFO("Call Request Done end."); - return true; -} - -void CallContainer::Dump(std::vector &info, const std::string &args) const -{ - HILOG_INFO("Dump call records."); -} - -bool CallContainer::IsNeedToCallRequest() const -{ - for (auto &iter : callRecordMap_) { - auto callRecord = iter.second; - if (callRecord && !callRecord->IsCallState(CallState::REQUESTED)) { - return true; - } - } - return false; -} - -void CallContainer::AddConnectDeathRecipient(const sptr &connect) -{ - CHECK_POINTER(connect); - CHECK_POINTER(connect->AsObject()); - auto it = deathRecipientMap_.find(connect->AsObject()); - if (it != deathRecipientMap_.end()) { - HILOG_ERROR("This death recipient has been added."); - return; - } else { - sptr deathRecipient = new AbilityConnectCallbackRecipient( - std::bind(&CallContainer::OnConnectionDied, this, std::placeholders::_1)); - connect->AsObject()->AddDeathRecipient(deathRecipient); - deathRecipientMap_.emplace(connect->AsObject(), deathRecipient); - } -} - -void CallContainer::RemoveConnectDeathRecipient(const sptr &connect) -{ - CHECK_POINTER(connect); - CHECK_POINTER(connect->AsObject()); - auto it = deathRecipientMap_.find(connect->AsObject()); - if (it != deathRecipientMap_.end()) { - it->first->RemoveDeathRecipient(it->second); - deathRecipientMap_.erase(it); - return; - } -} -} // namespace AAFwk -} // namesspace OHOS +/* + * 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 "call_container.h" + +#include "hilog_wrapper.h" +#include "ability_manager_errors.h" +#include "ability_connect_callback_stub.h" +#include "ability_util.h" +#include "ability_event_handler.h" +#include "ability_manager_service.h" + +namespace OHOS { +namespace AAFwk { +CallContainer::CallContainer() +{} + +CallContainer::~CallContainer() +{ + std::for_each(deathRecipientMap_.begin(), + deathRecipientMap_.end(), + [&](RecipientMapType::reference recipient) { + recipient.first->RemoveDeathRecipient(recipient.second); + }); + + deathRecipientMap_.clear(); + callRecordMap_.clear(); +} + +void CallContainer::AddCallRecord(const sptr & connect, + const std::shared_ptr& callRecord) +{ + CHECK_POINTER(callRecord); + CHECK_POINTER(connect); + CHECK_POINTER(connect->AsObject()); + + auto iter = callRecordMap_.find(connect->AsObject()); + if (iter != callRecordMap_.end()) { + RemoveConnectDeathRecipient(connect); + callRecordMap_.erase(callRecordMap_.find(connect->AsObject())); + } + + AddConnectDeathRecipient(connect); + callRecord->SetConCallBack(connect); + callRecordMap_.emplace(connect->AsObject(), callRecord); + + HILOG_DEBUG("Add call record to callcontainer, target: %{public}s", + callRecord->GetTargetServiceName().GetURI().c_str()); +} + +std::shared_ptr CallContainer::GetCallRecord(const sptr & connect) const +{ + CHECK_POINTER_AND_RETURN(connect, nullptr); + CHECK_POINTER_AND_RETURN(connect->AsObject(), nullptr); + + auto mapIter = callRecordMap_.find(connect->AsObject()); + if (mapIter != callRecordMap_.end()) { + return mapIter->second; + } + + return nullptr; +} + +bool CallContainer::RemoveCallRecord(const sptr & connect) +{ + HILOG_DEBUG("call container release call record by callback."); + CHECK_POINTER_AND_RETURN(connect, nullptr); + CHECK_POINTER_AND_RETURN(connect->AsObject(), nullptr); + + auto iter = callRecordMap_.find(connect->AsObject()); + if (iter != callRecordMap_.end()) { + auto callrecord = iter->second; + if (callrecord) { + callrecord->SchedulerDisConnectDone(); + } + RemoveConnectDeathRecipient(connect); + callRecordMap_.erase(callRecordMap_.find(connect->AsObject())); + HILOG_DEBUG("remove call record is success."); + return true; + } + + if (callRecordMap_.empty()) { + // notify soft resouce service. + HILOG_DEBUG("this ability has no callrecord."); + } + + HILOG_WARN("remove call record is not exist."); + return false; +} + +void CallContainer::OnConnectionDied(const wptr & remote) +{ + HILOG_WARN("Call back is died."); + auto object = remote.promote(); + CHECK_POINTER(object); + + std::shared_ptr callRecord = nullptr; + auto mapIter = callRecordMap_.find(object); + if (mapIter != callRecordMap_.end()) { + callRecord = mapIter->second; + } + + auto abilityManagerService = DelayedSingleton::GetInstance(); + CHECK_POINTER(abilityManagerService); + auto handler = abilityManagerService->GetEventHandler(); + CHECK_POINTER(handler); + auto task = [abilityManagerService, callRecord]() { + abilityManagerService->OnCallConnectDied(callRecord); + }; + handler->PostTask(task); +} + +bool CallContainer::CallRequestDone(const sptr & callStub) +{ + HILOG_INFO("Call Request Done start."); + + CHECK_POINTER_AND_RETURN(callStub, false); + + std::for_each(callRecordMap_.begin(), + callRecordMap_.end(), + [&callStub](CallMapType::reference service) { + std::shared_ptr callRecord = service.second; + if (callRecord && callRecord->IsCallState(CallState::REQUESTING)) { + callRecord->SetCallStub(callStub); + callRecord->SchedulerConnectDone(); + } + }); + + HILOG_INFO("Call Request Done end."); + return true; +} + +void CallContainer::Dump(std::vector &info) const +{ + HILOG_INFO("Dump call records."); + for (auto &iter : callRecordMap_) { + auto callRecord = iter.second; + if (callRecord) { + callRecord->Dump(info); + } + } +} + +bool CallContainer::IsNeedToCallRequest() const +{ + for (auto &iter : callRecordMap_) { + auto callRecord = iter.second; + if (callRecord && !callRecord->IsCallState(CallState::REQUESTED)) { + return true; + } + } + return false; +} + +void CallContainer::AddConnectDeathRecipient(const sptr &connect) +{ + CHECK_POINTER(connect); + CHECK_POINTER(connect->AsObject()); + auto it = deathRecipientMap_.find(connect->AsObject()); + if (it != deathRecipientMap_.end()) { + HILOG_ERROR("This death recipient has been added."); + return; + } else { + sptr deathRecipient = new AbilityConnectCallbackRecipient( + std::bind(&CallContainer::OnConnectionDied, this, std::placeholders::_1)); + connect->AsObject()->AddDeathRecipient(deathRecipient); + deathRecipientMap_.emplace(connect->AsObject(), deathRecipient); + } +} + +void CallContainer::RemoveConnectDeathRecipient(const sptr &connect) +{ + CHECK_POINTER(connect); + CHECK_POINTER(connect->AsObject()); + auto it = deathRecipientMap_.find(connect->AsObject()); + if (it != deathRecipientMap_.end()) { + it->first->RemoveDeathRecipient(it->second); + deathRecipientMap_.erase(it); + return; + } +} +} // namespace AAFwk +} // namesspace OHOS diff --git a/services/abilitymgr/src/call_record.cpp b/services/abilitymgr/src/call_record.cpp index 59098ac815b03a8e4a2348935a3426370faea306..c4f7ca30979b8d42eb3b681569b1469f7274be91 100644 --- a/services/abilitymgr/src/call_record.cpp +++ b/services/abilitymgr/src/call_record.cpp @@ -1,181 +1,199 @@ -/* - * 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 "call_record.h" - -#include "hilog_wrapper.h" -#include "ability_util.h" -#include "ability_event_handler.h" -#include "ability_manager_service.h" -#include "ability_record.h" -#include "element_name.h" - -namespace OHOS { -namespace AAFwk { -int64_t CallRecord::callRecordId = 0; - -CallRecord::CallRecord(const int32_t callerUid, const std::shared_ptr &targetService, - const sptr &connCallback, const sptr &callToken) - : callerUid_(callerUid), - state_(CallState::INIT), - service_(targetService), - connCallback_(connCallback), - callerToken_(callToken) -{ - recordId_ = callRecordId++; - startTime_ = AbilityUtil::SystemTimeMillis(); -} - -CallRecord::~CallRecord() -{ - if (callRemoteObject_ && callDeathRecipient_) { - callRemoteObject_->RemoveDeathRecipient(callDeathRecipient_); - } -} - -std::shared_ptr CallRecord::CreateCallRecord(const int32_t callerUid, - const std::shared_ptr &targetService, const sptr &connCallback, - const sptr &callToken) -{ - auto callRecord = std::make_shared(callerUid, targetService, connCallback, callToken); - CHECK_POINTER_AND_RETURN(callRecord, nullptr); - callRecord->SetCallState(CallState::INIT); - return callRecord; -} - -void CallRecord::SetCallStub(const sptr & call) -{ - CHECK_POINTER(call); - - callRemoteObject_ = call; - - HILOG_DEBUG("SetCallStub complete."); - - if (callDeathRecipient_ == nullptr) { - callDeathRecipient_ = - new AbilityCallRecipient(std::bind(&CallRecord::OnCallStubDied, this, std::placeholders::_1)); - } - - callRemoteObject_->AddDeathRecipient(callDeathRecipient_); -} - -sptr CallRecord::GetCallStub() -{ - return callRemoteObject_; -} - -void CallRecord::SetConCallBack(const sptr &connCallback) -{ - connCallback_ = connCallback; -} - -sptr CallRecord::GetConCallBack() const -{ - return connCallback_; -} - -AppExecFwk::ElementName CallRecord::GetTargetServiceName() const -{ - std::shared_ptr tmpService = service_.lock(); - if (tmpService) { - const AppExecFwk::AbilityInfo &abilityInfo = tmpService->GetAbilityInfo(); - AppExecFwk::ElementName element(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name); - return element; - } - return AppExecFwk::ElementName(); -} - -sptr CallRecord::GetCallerToken() const -{ - return callerToken_; -} - -bool CallRecord::SchedulerConnectDone() -{ - HILOG_DEBUG("Scheduler Connect Done by callback. id:%{public}d", recordId_); - std::shared_ptr tmpService = service_.lock(); - if (!callRemoteObject_ || !connCallback_ || !tmpService) { - HILOG_ERROR("callstub or connCallback is nullptr, can't scheduler connect done."); - return false; - } - - const AppExecFwk::AbilityInfo &abilityInfo = tmpService->GetAbilityInfo(); - AppExecFwk::ElementName element(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name); - connCallback_->OnAbilityConnectDone(element, callRemoteObject_, ERR_OK); - state_ = CallState::REQUESTED; - - HILOG_DEBUG("element: %{public}s, result: %{public}d. connectstate:%{public}d.", element.GetURI().c_str(), - ERR_OK, state_); - return true; -} - -bool CallRecord::SchedulerDisConnectDone() -{ - HILOG_DEBUG("Scheduler disconnect Done by callback. id:%{public}d", recordId_); - std::shared_ptr tmpService = service_.lock(); - if (!connCallback_ || !tmpService) { - HILOG_ERROR("callstub or connCallback is nullptr, can't scheduler connect done."); - return false; - } - - const AppExecFwk::AbilityInfo &abilityInfo = tmpService->GetAbilityInfo(); - AppExecFwk::ElementName element(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name); - connCallback_->OnAbilityDisconnectDone(element, ERR_OK); - - return true; -} - -void CallRecord::OnCallStubDied(const wptr & remote) -{ - HILOG_WARN("callstub is died. id:%{public}d", recordId_); - auto object = remote.promote(); - CHECK_POINTER(object); - - auto abilityManagerService = DelayedSingleton::GetInstance(); - CHECK_POINTER(abilityManagerService); - auto handler = abilityManagerService->GetEventHandler(); - CHECK_POINTER(handler); - auto task = [abilityManagerService, callRecord = shared_from_this()]() { - abilityManagerService->OnCallConnectDied(callRecord); - }; - handler->PostTask(task); -} - -void CallRecord::Dump(std::vector &info) const -{ - HILOG_DEBUG("CallRecord::Dump is called"); -} - -int32_t CallRecord::GetCallerUid() const -{ - return callerUid_; -} - -bool CallRecord::IsCallState(const CallState& state) const -{ - return (state_ == state); -} - -void CallRecord::SetCallState(const CallState& state) -{ - state_ = state; -} - -int CallRecord::GetCallRecordId() const -{ - return recordId_; -} -} // namespace AAFwk +/* + * 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 "call_record.h" + +#include "hilog_wrapper.h" +#include "ability_util.h" +#include "ability_event_handler.h" +#include "ability_manager_service.h" +#include "ability_record.h" +#include "element_name.h" + +namespace OHOS { +namespace AAFwk { +int64_t CallRecord::callRecordId = 0; + +CallRecord::CallRecord(const int32_t callerUid, const std::shared_ptr &targetService, + const sptr &connCallback, const sptr &callToken) + : callerUid_(callerUid), + state_(CallState::INIT), + service_(targetService), + connCallback_(connCallback), + callerToken_(callToken) +{ + recordId_ = callRecordId++; + startTime_ = AbilityUtil::SystemTimeMillis(); +} + +CallRecord::~CallRecord() +{ + if (callRemoteObject_ && callDeathRecipient_) { + callRemoteObject_->RemoveDeathRecipient(callDeathRecipient_); + } +} + +std::shared_ptr CallRecord::CreateCallRecord(const int32_t callerUid, + const std::shared_ptr &targetService, const sptr &connCallback, + const sptr &callToken) +{ + auto callRecord = std::make_shared(callerUid, targetService, connCallback, callToken); + CHECK_POINTER_AND_RETURN(callRecord, nullptr); + callRecord->SetCallState(CallState::INIT); + return callRecord; +} + +void CallRecord::SetCallStub(const sptr & call) +{ + CHECK_POINTER(call); + + callRemoteObject_ = call; + + HILOG_DEBUG("SetCallStub complete."); + + if (callDeathRecipient_ == nullptr) { + callDeathRecipient_ = + new AbilityCallRecipient(std::bind(&CallRecord::OnCallStubDied, this, std::placeholders::_1)); + } + + callRemoteObject_->AddDeathRecipient(callDeathRecipient_); +} + +sptr CallRecord::GetCallStub() +{ + return callRemoteObject_; +} + +void CallRecord::SetConCallBack(const sptr &connCallback) +{ + connCallback_ = connCallback; +} + +sptr CallRecord::GetConCallBack() const +{ + return connCallback_; +} + +AppExecFwk::ElementName CallRecord::GetTargetServiceName() const +{ + std::shared_ptr tmpService = service_.lock(); + if (tmpService) { + const AppExecFwk::AbilityInfo &abilityInfo = tmpService->GetAbilityInfo(); + AppExecFwk::ElementName element(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name); + return element; + } + return AppExecFwk::ElementName(); +} + +sptr CallRecord::GetCallerToken() const +{ + return callerToken_; +} + +bool CallRecord::SchedulerConnectDone() +{ + HILOG_DEBUG("Scheduler Connect Done by callback. id:%{public}d", recordId_); + std::shared_ptr tmpService = service_.lock(); + if (!callRemoteObject_ || !connCallback_ || !tmpService) { + HILOG_ERROR("callstub or connCallback is nullptr, can't scheduler connect done."); + return false; + } + + const AppExecFwk::AbilityInfo &abilityInfo = tmpService->GetAbilityInfo(); + AppExecFwk::ElementName element(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name); + connCallback_->OnAbilityConnectDone(element, callRemoteObject_, ERR_OK); + state_ = CallState::REQUESTED; + + HILOG_DEBUG("element: %{public}s, result: %{public}d. connectstate:%{public}d.", element.GetURI().c_str(), + ERR_OK, state_); + return true; +} + +bool CallRecord::SchedulerDisConnectDone() +{ + HILOG_DEBUG("Scheduler disconnect Done by callback. id:%{public}d", recordId_); + std::shared_ptr tmpService = service_.lock(); + if (!connCallback_ || !tmpService) { + HILOG_ERROR("callstub or connCallback is nullptr, can't scheduler connect done."); + return false; + } + + const AppExecFwk::AbilityInfo &abilityInfo = tmpService->GetAbilityInfo(); + AppExecFwk::ElementName element(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name); + connCallback_->OnAbilityDisconnectDone(element, ERR_OK); + + return true; +} + +void CallRecord::OnCallStubDied(const wptr & remote) +{ + HILOG_WARN("callstub is died. id:%{public}d", recordId_); + auto object = remote.promote(); + CHECK_POINTER(object); + + auto abilityManagerService = DelayedSingleton::GetInstance(); + CHECK_POINTER(abilityManagerService); + auto handler = abilityManagerService->GetEventHandler(); + CHECK_POINTER(handler); + auto task = [abilityManagerService, callRecord = shared_from_this()]() { + abilityManagerService->OnCallConnectDied(callRecord); + }; + handler->PostTask(task); +} + +void CallRecord::Dump(std::vector &info) const +{ + HILOG_DEBUG("CallRecord::Dump is called"); + + std::string tempstr = " CallRecord"; + tempstr += " ID #" + std::to_string (recordId_) + "\n"; + tempstr += " caller"; + auto abilityRecord = Token::GetAbilityRecordByToken(callerToken_); + if (abilityRecord) { + AppExecFwk::ElementName element( + abilityRecord->GetAbilityInfo().deviceId, abilityRecord->GetAbilityInfo().bundleName, + abilityRecord->GetAbilityInfo().name); + tempstr += " uri [" + element.GetURI() + "]" + "\n"; + } + + std::string state = (state_ == CallState::INIT ? "INIT" : + state_ == CallState::REQUESTING ? "REQUESTING" : "REQUESTED"); + tempstr += " state #" + state; + tempstr += " start time [" + std::to_string (startTime_) + "]"; + info.emplace_back(tempstr); + HILOG_DEBUG("CallRecord::Dump is called1"); +} + +int32_t CallRecord::GetCallerUid() const +{ + return callerUid_; +} + +bool CallRecord::IsCallState(const CallState& state) const +{ + return (state_ == state); +} + +void CallRecord::SetCallState(const CallState& state) +{ + state_ = state; +} + +int CallRecord::GetCallRecordId() const +{ + return recordId_; +} +} // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/data_ability_manager.cpp b/services/abilitymgr/src/data_ability_manager.cpp index 898e3847432908a4e92934b7cc2df321dd19082e..898ecdb426994eccaff43df0bc1d719f9fd10e74 100644 --- a/services/abilitymgr/src/data_ability_manager.cpp +++ b/services/abilitymgr/src/data_ability_manager.cpp @@ -168,6 +168,24 @@ int DataAbilityManager::Release( return ERR_OK; } +bool DataAbilityManager::ContainsDataAbility(const sptr &scheduler) +{ + HILOG_DEBUG("%{public}s(%{public}d)", __PRETTY_FUNCTION__, __LINE__); + + CHECK_POINTER_AND_RETURN(scheduler, ERR_NULL_OBJECT); + + std::lock_guard locker(mutex_); + + DataAbilityRecordPtrMap::iterator it; + for (it = dataAbilityRecordsLoaded_.begin(); it != dataAbilityRecordsLoaded_.end(); ++it) { + if (it->second->GetScheduler() != nullptr && it->second->GetScheduler()->AsObject() == scheduler->AsObject()) { + return true; + } + } + + return false; +} + int DataAbilityManager::AttachAbilityThread(const sptr &scheduler, const sptr &token) { HILOG_DEBUG("%{public}s(%{public}d)", __PRETTY_FUNCTION__, __LINE__); @@ -495,6 +513,48 @@ void DataAbilityManager::DumpState(std::vector &info, const std::st return; } +void DataAbilityManager::DumpSysState(std::vector &info, bool isClient, const std::string &args) const +{ + if (!args.empty()) { + auto it = std::find_if(dataAbilityRecordsLoaded_.begin(), + dataAbilityRecordsLoaded_.end(), + [&args](const auto &dataAbilityRecord) { return dataAbilityRecord.first.compare(args) == 0; }); + if (it != dataAbilityRecordsLoaded_.end()) { + info.emplace_back("AbilityName [ " + it->first + " ]"); + it->second->Dump(info); + // add dump client info + if (isClient && it->second->GetScheduler() && it->second->GetAbilityRecord()->IsReady()) { + std::vector params; + it->second->GetScheduler()->DumpAbilityInfo(params, info); + AppExecFwk::Configuration config; + if (DelayedSingleton::GetInstance()->GetConfiguration(config) == ERR_OK) { + info.emplace_back(" configuration: " + config.GetName()); + } + } + } else { + info.emplace_back(args + ": Nothing to dump."); + } + } else { + info.emplace_back(" dataAbilityRecords:"); + for (auto &&dataAbilityRecord : dataAbilityRecordsLoaded_) { + info.emplace_back(" uri [" + dataAbilityRecord.first + "]"); + dataAbilityRecord.second->Dump(info); + dataAbilityRecord.second->GetScheduler(); + // add dump client info + if (isClient && dataAbilityRecord.second->GetScheduler() + && dataAbilityRecord.second->GetAbilityRecord()->IsReady()) { + std::vector params; + dataAbilityRecord.second->GetScheduler()->DumpAbilityInfo(params, info); + AppExecFwk::Configuration config; + if (DelayedSingleton::GetInstance()->GetConfiguration(config) == ERR_OK) { + info.emplace_back(" configuration: " + config.GetName()); + } + } + } + } + return; +} + void DataAbilityManager::GetAbilityRunningInfos(std::vector &info) { HILOG_INFO("Get ability running infos"); diff --git a/services/abilitymgr/src/inner_mission_info.cpp b/services/abilitymgr/src/inner_mission_info.cpp index 42275a6a11d1e281bb3f1d2963fe1aebe4502729..6231b346fce388e389a010501dfaa0ac76402157 100644 --- a/services/abilitymgr/src/inner_mission_info.cpp +++ b/services/abilitymgr/src/inner_mission_info.cpp @@ -37,19 +37,16 @@ std::string InnerMissionInfo::ToJsonStr() const return value.dump(); } -void InnerMissionInfo::FromJsonStr(const std::string &jsonStr) +bool InnerMissionInfo::FromJsonStr(const std::string &jsonStr) { - if (jsonStr.empty()) { - HILOG_ERROR("json str is empty."); - return; - } - nlohmann::json value = nlohmann::json::parse(jsonStr); + // Do not throw exceptions in nlohmann::json::parse + nlohmann::json value = nlohmann::json::parse(jsonStr, nullptr, false); if (value.is_discarded()) { HILOG_ERROR("failed to parse json sting: %{private}s.", jsonStr.c_str()); - return; + return false; } - auto CheckJsonNode = [value] (const std::string &node, JsonType jsonType) -> bool { + auto CheckJsonNode = [&value] (const std::string &node, JsonType jsonType) -> bool { if (value.find(node) == value.end()) { HILOG_ERROR("node %{private}s not exists.", node.c_str()); return false; @@ -66,36 +63,50 @@ void InnerMissionInfo::FromJsonStr(const std::string &jsonStr) } return false; }; - if (CheckJsonNode("MissionName", JsonType::STRING)) { - missionName = value["MissionName"]; + if (!CheckJsonNode("MissionName", JsonType::STRING)) { + return false; } - if (CheckJsonNode("IsSingleton", JsonType::BOOLEAN)) { - isSingletonMode = value["IsSingleton"]; + missionName = value["MissionName"].get(); + if (!CheckJsonNode("IsSingleton", JsonType::BOOLEAN)) { + return false; } - if (CheckJsonNode("MissionId", JsonType::NUMBER)) { - missionInfo.id = value["MissionId"]; + isSingletonMode = value["IsSingleton"].get(); + if (!CheckJsonNode("MissionId", JsonType::NUMBER)) { + return false; } - if (CheckJsonNode("RunningState", JsonType::NUMBER)) { - missionInfo.runningState = value["RunningState"]; + missionInfo.id = value["MissionId"].get(); + if (!CheckJsonNode("RunningState", JsonType::NUMBER)) { + return false; } - if (CheckJsonNode("LockedState", JsonType::BOOLEAN)) { - missionInfo.lockedState = value["LockedState"]; + missionInfo.runningState = value["RunningState"].get(); + if (!CheckJsonNode("LockedState", JsonType::BOOLEAN)) { + return false; } - if (CheckJsonNode("Continuable", JsonType::BOOLEAN)) { - missionInfo.continuable = value["Continuable"]; + missionInfo.lockedState = value["LockedState"].get(); + if (!CheckJsonNode("Continuable", JsonType::BOOLEAN)) { + return false; + } + missionInfo.continuable = value["Continuable"].get(); + if (!CheckJsonNode("Time", JsonType::STRING)) { + return false; } - if (CheckJsonNode("Time", JsonType::STRING)) { - missionInfo.time = value["Time"]; + missionInfo.time = value["Time"].get(); + if (!CheckJsonNode("Label", JsonType::STRING)) { + return false; } - if (CheckJsonNode("Label", JsonType::STRING)) { - missionInfo.label = value["Label"]; + missionInfo.label = value["Label"].get(); + if (!CheckJsonNode("IconPath", JsonType::STRING)) { + return false; } - if (CheckJsonNode("IconPath", JsonType::STRING)) { - missionInfo.iconPath = value["IconPath"]; + missionInfo.iconPath = value["IconPath"].get(); + if (!CheckJsonNode("Want", JsonType::STRING)) { + return false; } - if (CheckJsonNode("Want", JsonType::STRING)) { - missionInfo.want = *(Want::ParseUri(value["Want"])); + Want* want = Want::ParseUri(value["Want"].get()); + if (want) { + missionInfo.want = *want; } + return true; } void InnerMissionInfo::Dump(std::vector &info) const diff --git a/services/abilitymgr/src/kernal_ability_manager.cpp b/services/abilitymgr/src/kernal_ability_manager.cpp deleted file mode 100644 index 1667b8db46f95499b988c02d8de7ada0ac92dd51..0000000000000000000000000000000000000000 --- a/services/abilitymgr/src/kernal_ability_manager.cpp +++ /dev/null @@ -1,411 +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 "kernal_ability_manager.h" - -#include "ability_manager_errors.h" -#include "ability_manager_service.h" -#include "ability_util.h" -#include "app_scheduler.h" -#include "hilog_wrapper.h" - -namespace OHOS { -namespace AAFwk { -KernalAbilityManager::KernalAbilityManager(int userId) : userId_(userId) -{} - -KernalAbilityManager::~KernalAbilityManager() -{} - -int KernalAbilityManager::StartAbility(const AbilityRequest &abilityRequest) -{ - HILOG_INFO("start kernal systerm ability."); - std::lock_guard guard(stackLock_); - if (!waittingAbilityQueue_.empty()) { - HILOG_INFO("waiting queue is not empty, so enqueue systerm ui ability for waiting."); - EnqueueWaittingAbility(abilityRequest); - return START_ABILITY_WAITING; - } - - std::shared_ptr topAbilityRecord = GetCurrentTopAbility(); - auto requestFlag = GetFlagOfAbility(abilityRequest.abilityInfo.bundleName, abilityRequest.abilityInfo.name); - if (topAbilityRecord != nullptr) { - auto topFlag = - GetFlagOfAbility(topAbilityRecord->GetAbilityInfo().bundleName, topAbilityRecord->GetAbilityInfo().name); - if (topFlag == requestFlag && topAbilityRecord->GetAbilityState() == INITIAL) { - HILOG_INFO("top systerm ui ability need to restart."); - } - if (topAbilityRecord->GetAbilityState() == FOREGROUNDING_NEW) { - HILOG_INFO("top systerm ui ability is not foreground, so enqueue ability for waiting."); - EnqueueWaittingAbility(abilityRequest); - return START_ABILITY_WAITING; - } - } - - return StartAbilityLocked(abilityRequest); -} - -int KernalAbilityManager::StartAbilityLocked(const AbilityRequest &abilityRequest) -{ - std::shared_ptr targetAbility; - GetOrCreateAbilityRecord(abilityRequest, targetAbility); - CHECK_POINTER_AND_RETURN(targetAbility, ERR_INVALID_VALUE); - targetAbility->SetKernalSystemAbility(); - - HILOG_INFO("Load kernal system ability, bundleName:%{public}s , abilityName:%{public}s", - abilityRequest.abilityInfo.bundleName.c_str(), - abilityRequest.abilityInfo.name.c_str()); - - if (targetAbility->IsAbilityState(AbilityState::FOREGROUND_NEW) || - targetAbility->IsAbilityState(AbilityState::FOREGROUNDING_NEW)) { - HILOG_INFO("kernal system ability is already activing or activated."); - targetAbility->ForegroundAbility(); - return ERR_OK; - } - return targetAbility->LoadAbility(); -} - -int KernalAbilityManager::AttachAbilityThread( - const sptr &scheduler, const sptr &token) -{ - HILOG_INFO("Attach ability thread."); - std::lock_guard guard(stackLock_); - auto abilityRecord = GetAbilityRecordByToken(token); - CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); - - std::string flag = KernalAbilityManager::GetFlagOfAbility( - abilityRecord->GetAbilityInfo().bundleName, abilityRecord->GetAbilityInfo().name); - HILOG_INFO("ability: %{public}s", flag.c_str()); - - auto handler = DelayedSingleton::GetInstance()->GetEventHandler(); - CHECK_POINTER_AND_RETURN(handler, ERR_INVALID_VALUE); - - handler->RemoveEvent(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecord->GetEventId()); - - abilityRecord->SetScheduler(scheduler); - DelayedSingleton::GetInstance()->MoveToForground(token); - - return ERR_OK; -} - -void KernalAbilityManager::OnAbilityRequestDone(const sptr &token, const int32_t state) -{ - HILOG_INFO("On ability request done."); - std::lock_guard guard(stackLock_); - AppAbilityState abilitState = DelayedSingleton::GetInstance()->ConvertToAppAbilityState(state); - if (abilitState == AppAbilityState::ABILITY_STATE_FOREGROUND) { - auto abilityRecord = GetAbilityRecordByToken(token); - CHECK_POINTER(abilityRecord); - abilityRecord->ForegroundAbility(); - } -} - -void KernalAbilityManager::OnAppStateChanged(const AppInfo &info) -{ - std::lock_guard guard(stackLock_); - for (auto ability : abilities_) { - if (ability && (info.processName == ability->GetAbilityInfo().process || - info.processName == ability->GetApplicationInfo().bundleName)) { - auto appName = ability->GetApplicationInfo().name; - auto isExist = [&appName](const AppData &appData) { return appData.appName == appName; }; - auto iter = std::find_if(info.appData.begin(), info.appData.end(), isExist); - if (iter != info.appData.end()) { - ability->SetAppState(info.state); - } - } - } -} - -int KernalAbilityManager::AbilityTransitionDone(const sptr &token, int state) -{ - HILOG_INFO("Ability transition done."); - std::lock_guard guard(stackLock_); - auto abilityRecord = GetAbilityRecordByToken(token); - CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); - - std::string flag = KernalAbilityManager::GetFlagOfAbility( - abilityRecord->GetAbilityInfo().bundleName, abilityRecord->GetAbilityInfo().name); - int targetState = AbilityRecord::ConvertLifeCycleToAbilityState(static_cast(state)); - std::string abilityState = AbilityRecord::ConvertAbilityState(static_cast(targetState)); - HILOG_INFO("ability: %{public}s, state: %{public}s", flag.c_str(), abilityState.c_str()); - - switch (targetState) { - case AbilityState::FOREGROUND_NEW: { - return DispatchForeground(abilityRecord, targetState); - } - default: { - HILOG_WARN("don't support transiting state: %d", targetState); - return ERR_INVALID_VALUE; - } - } -} - -int KernalAbilityManager::DispatchForeground(const std::shared_ptr &abilityRecord, int state) -{ - auto handler = DelayedSingleton::GetInstance()->GetEventHandler(); - CHECK_POINTER_AND_RETURN(handler, ERR_INVALID_VALUE); - CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); - - if (!abilityRecord->IsAbilityState(AbilityState::FOREGROUNDING_NEW)) { - HILOG_ERROR("kernal ability transition life state error. start:%{public}d", state); - return ERR_INVALID_VALUE; - } - handler->RemoveEvent(AbilityManagerService::FOREGROUNDNEW_TIMEOUT_MSG, abilityRecord->GetEventId()); - - auto task = [kernalManager = shared_from_this(), abilityRecord]() { - kernalManager->CompleteForeground(abilityRecord); - }; - handler->PostTask(task); - return ERR_OK; -} - -void KernalAbilityManager::CompleteForeground(const std::shared_ptr &abilityRecord) -{ - HILOG_INFO("Complete foreground."); - std::lock_guard guard(stackLock_); - abilityRecord->SetAbilityState(AbilityState::FOREGROUND_NEW); - - auto handler = DelayedSingleton::GetInstance()->GetEventHandler(); - CHECK_POINTER(handler); - - auto task = [kernalManager = shared_from_this()]() { kernalManager->DequeueWaittingAbility(); }; - handler->PostTask(task, "DequeueWaittingAbility"); -} - -void KernalAbilityManager::GetOrCreateAbilityRecord( - const AbilityRequest &abilityRequest, std::shared_ptr &targetAbility) -{ - std::string abilityFlag = - KernalAbilityManager::GetFlagOfAbility(abilityRequest.abilityInfo.bundleName, abilityRequest.abilityInfo.name); - auto isExist = [targetFlag = abilityFlag](const std::shared_ptr &ability) { - if (ability == nullptr) { - return false; - } - return KernalAbilityManager::GetFlagOfAbility(ability->GetAbilityInfo().bundleName, - ability->GetAbilityInfo().name) == targetFlag; - }; - auto iter = std::find_if(abilities_.begin(), abilities_.end(), isExist); - if (iter != abilities_.end()) { - targetAbility = *iter; - targetAbility->SetWant(abilityRequest.want); - targetAbility->SetIsNewWant(true); - return; - } - targetAbility = AbilityRecord::CreateAbilityRecord(abilityRequest); - targetAbility->SetUseNewMission(); - abilities_.push_front(targetAbility); -} - -std::string KernalAbilityManager::GetFlagOfAbility(const std::string &bundleName, const std::string &abilityName) -{ - return bundleName + ":" + abilityName; -} - -int KernalAbilityManager::GetManagerUserId() const -{ - return userId_; -} - -std::shared_ptr KernalAbilityManager::GetCurrentTopAbility() const -{ - if (abilities_.empty()) { - return nullptr; - } - return abilities_.front(); -} - -std::shared_ptr KernalAbilityManager::GetAbilityRecordByToken(const sptr &token) -{ - std::lock_guard guard(stackLock_); - auto abilityToFind = Token::GetAbilityRecordByToken(token); - CHECK_POINTER_AND_RETURN(abilityToFind, nullptr); - - auto isExist = [targetAbility = abilityToFind](const std::shared_ptr &ability) { - if (ability == nullptr) { - return false; - } - return targetAbility == ability; - }; - auto iter = std::find_if(abilities_.begin(), abilities_.end(), isExist); - if (iter != abilities_.end()) { - return *iter; - } - - return nullptr; -} - -std::shared_ptr KernalAbilityManager::GetAbilityRecordByEventId(const int64_t eventId) const -{ - auto isExist = [targetEventId = eventId](const std::shared_ptr &ability) { - if (ability == nullptr) { - return false; - } - return (ability->GetEventId() == targetEventId); - }; - auto iter = std::find_if(abilities_.begin(), abilities_.end(), isExist); - if (iter != abilities_.end()) { - return *iter; - } - return nullptr; -} - -bool KernalAbilityManager::RemoveAbilityRecord(std::shared_ptr ability) -{ - CHECK_POINTER_RETURN_BOOL(ability); - for (auto iter = abilities_.begin(); iter != abilities_.end(); iter++) { - if ((*iter) == ability) { - abilities_.erase(iter); - return true; - } - } - HILOG_ERROR("can not find ability"); - return false; -} - -void KernalAbilityManager::EnqueueWaittingAbility(const AbilityRequest &abilityRequest) -{ - waittingAbilityQueue_.push(abilityRequest); - return; -} - -void KernalAbilityManager::DequeueWaittingAbility() -{ - std::lock_guard guard(stackLock_); - std::shared_ptr topAbility = GetCurrentTopAbility(); - if (topAbility != nullptr && topAbility->GetAbilityState() != FOREGROUND_NEW) { - HILOG_INFO("top ability is not foreground, must return for waiting again"); - return; - } - if (!waittingAbilityQueue_.empty()) { - AbilityRequest abilityRequest = waittingAbilityQueue_.front(); - waittingAbilityQueue_.pop(); - HILOG_INFO("bundleName: %{public}s, abilityName: %{public}s", - abilityRequest.abilityInfo.bundleName.c_str(), - abilityRequest.abilityInfo.name.c_str()); - - StartAbilityLocked(abilityRequest); - } -} -void KernalAbilityManager::DumpState(std::vector &info) -{ - info.emplace_back("SystemUIRecords:"); - for (auto &ability : abilities_) { - ability->Dump(info); - } -} - -void KernalAbilityManager::OnAbilityDied(std::shared_ptr abilityRecord) -{ - std::lock_guard guard(stackLock_); - CHECK_POINTER(abilityRecord); - if (!abilityRecord->IsKernalSystemAbility()) { - HILOG_ERROR("System UI on scheduler died, ability type is not system ui"); - return; - } - - if (GetAbilityRecordByToken(abilityRecord->GetToken()) == nullptr) { - HILOG_ERROR("System UI on scheduler died, record is not exist."); - return; - } - auto ams = DelayedSingleton::GetInstance(); - CHECK_POINTER(ams); - - auto handler = ams->GetEventHandler(); - CHECK_POINTER(handler); - - HILOG_INFO("System UI on scheduler died: '%{public}s'", abilityRecord->GetAbilityInfo().name.c_str()); - std::string name = abilityRecord->GetAbilityInfo().name; - abilityRecord->SetAbilityState(AbilityState::INITIAL); - auto timeoutTask = [ams, abilityRecord]() { - if (abilityRecord) { - ams->StartSystemUi(abilityRecord->GetAbilityInfo().name); - } - }; - handler->PostTask(timeoutTask, "SystemUi_Die_" + name, AbilityManagerService::RESTART_TIMEOUT); -} -void KernalAbilityManager::OnTimeOut(uint32_t msgId, int64_t eventId) -{ - std::lock_guard guard(stackLock_); - if (abilities_.empty()) { - HILOG_ERROR("System UI on time out event: ability stack is empty."); - return; - } - - auto abilityRecord = GetAbilityRecordByEventId(eventId); - CHECK_POINTER(abilityRecord); - - auto ams = DelayedSingleton::GetInstance(); - CHECK_POINTER(ams); - - auto handler = ams->GetEventHandler(); - CHECK_POINTER(handler); - - switch (msgId) { - case AbilityManagerService::LOAD_TIMEOUT_MSG: - case AbilityManagerService::FOREGROUNDNEW_TIMEOUT_MSG: { - std::string bundleName = abilityRecord->GetAbilityInfo().bundleName; - std::string name = abilityRecord->GetAbilityInfo().name; - RemoveAbilityRecord(abilityRecord); - auto task = [ams, bundleName]() { - ams->KillProcess(bundleName); - HILOG_ERROR("System UI on time out event: KillProcess:%{public}s", bundleName.c_str()); - }; - handler->PostTask(task); - auto timeoutTask = [ams, name]() { - ams->StartSystemUi(name); - HILOG_ERROR("System UI on time out event: restart:%{public}s", name.c_str()); - }; - handler->PostTask(timeoutTask, "SystemUi_Timeout_" + name, AbilityManagerService::RESTART_TIMEOUT); - break; - } - default: - break; - } -} - -void KernalAbilityManager::GetAbilityRunningInfos(std::vector &info) -{ - HILOG_DEBUG("Get ability running infos"); - std::lock_guard guard(stackLock_); - - for (auto &ability : abilities_) { - if (!ability) { - HILOG_DEBUG("ability is nullptr."); - continue; - } - - AbilityRunningInfo runningInfo; - AppExecFwk::RunningProcessInfo processInfo; - runningInfo.ability = ability->GetWant().GetElement(); - DelayedSingleton::GetInstance()-> - GetRunningProcessInfoByToken(ability->GetToken(), processInfo); - runningInfo.pid = processInfo.pid_; - runningInfo.uid = processInfo.uid_; - runningInfo.processName = processInfo.processName_; - runningInfo.startTime = ability->GetStartTime(); - runningInfo.abilityState = static_cast(ability->GetAbilityState()); - info.emplace_back(runningInfo); - } -} - - -void KernalAbilityManager::RestartAbility(const std::shared_ptr abilityRecord) -{ - CHECK_POINTER(abilityRecord); - HILOG_DEBUG("Restart ability system ui. %{public}s", abilityRecord->GetAbilityInfo().name.c_str()); - return; -} -} // namespace AAFwk -} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/kernal_system_app_manager.cpp b/services/abilitymgr/src/kernal_system_app_manager.cpp index a785eb6aca9cde04e0da1b527a0f54d4fe745c54..76ab01a7c45ac4e179f7778c08de9cd7e8fa9dc3 100644 --- a/services/abilitymgr/src/kernal_system_app_manager.cpp +++ b/services/abilitymgr/src/kernal_system_app_manager.cpp @@ -321,6 +321,13 @@ void KernalSystemAppManager::DumpState(std::vector &info) ability->Dump(info); } } +void KernalSystemAppManager::DumpSysState(std::vector &info, bool isClient) +{ + info.emplace_back("SystemUIRecords:"); + for (auto &ability : abilities_) { + ability->DumpSys(info, isClient); + } +} void KernalSystemAppManager::OnAbilityDied(std::shared_ptr abilityRecord) { @@ -335,18 +342,18 @@ void KernalSystemAppManager::OnAbilityDied(std::shared_ptr abilit HILOG_ERROR("System UI on scheduler died, record is not exist."); return; } - auto ams = DelayedSingleton::GetInstance(); - CHECK_POINTER(ams); + auto abilityms = DelayedSingleton::GetInstance(); + CHECK_POINTER(abilityms); - auto handler = ams->GetEventHandler(); + auto handler = abilityms->GetEventHandler(); CHECK_POINTER(handler); HILOG_INFO("System UI on scheduler died: '%{public}s'", abilityRecord->GetAbilityInfo().name.c_str()); std::string name = abilityRecord->GetAbilityInfo().name; abilityRecord->SetAbilityState(AbilityState::INITIAL); - auto timeoutTask = [ams, abilityRecord]() { + auto timeoutTask = [abilityms, abilityRecord]() { if (abilityRecord) { - ams->StartSystemUi(abilityRecord->GetAbilityInfo().name); + abilityms->StartingSystemUiAbility(); } }; handler->PostTask(timeoutTask, "SystemUi_Die_" + name, AbilityManagerService::RESTART_TIMEOUT); @@ -380,7 +387,7 @@ void KernalSystemAppManager::OnTimeOut(uint32_t msgId, int64_t eventId) }; handler->PostTask(task); auto timeoutTask = [abilityMS, name]() { - abilityMS->StartSystemUi(name); + abilityMS->StartingSystemUiAbility(); HILOG_ERROR("System UI on time out event: restart:%{public}s", name.c_str()); }; handler->PostTask(timeoutTask, "SystemUi_Timeout_" + name, AbilityManagerService::RESTART_TIMEOUT); diff --git a/services/abilitymgr/src/lifecycle_deal.cpp b/services/abilitymgr/src/lifecycle_deal.cpp index 3e5160e9f9af4528541115b74dfe4170e24b7d1d..2ab80063fdc0cb4072e980eaec8092221e10e684 100755 --- a/services/abilitymgr/src/lifecycle_deal.cpp +++ b/services/abilitymgr/src/lifecycle_deal.cpp @@ -160,7 +160,7 @@ void LifecycleDeal::ContinueAbility(const std::string& deviceId) abilityScheduler_->ContinueAbility(deviceId); } -void LifecycleDeal::NotifyContinuationResult(const int32_t result) +void LifecycleDeal::NotifyContinuationResult(int32_t result) { HILOG_INFO("NotifyContinuationResult."); auto abilityScheduler = GetScheduler(); diff --git a/services/abilitymgr/src/mission.cpp b/services/abilitymgr/src/mission.cpp index 8392bcbf1bf148a6ee1a4a027df949cee50c7ce8..7113b70418a0b8dec6fcd8163ceccf0b09dab28e 100644 --- a/services/abilitymgr/src/mission.cpp +++ b/services/abilitymgr/src/mission.cpp @@ -94,10 +94,21 @@ bool Mission::IsMovingState() const return isMovingToFront_; } +void Mission::SetANRState() +{ + isANRState_ = true; +} + +bool Mission::IsANRState() const +{ + return isANRState_; +} + void Mission::Dump(std::vector &info) { std::string dumpInfo = " Mission ID #" + std::to_string(missionId_); - dumpInfo += " mission name #[" + missionName_ + "]" + " lockedState #" + std::to_string(lockedState_); + dumpInfo += " mission name #[" + missionName_ + "]" + " lockedState #" + std::to_string(lockedState_) + + " ANR State #" + std::to_string(isANRState_); info.push_back(dumpInfo); if (abilityRecord_) { abilityRecord_->Dump(info); diff --git a/services/abilitymgr/src/mission_data_storage.cpp b/services/abilitymgr/src/mission_data_storage.cpp index 828ab061a7864306e7b83d38c5efb0008033ad2e..645c0df56a14f4a848fbdbba5628ebdd4257716c 100644 --- a/services/abilitymgr/src/mission_data_storage.cpp +++ b/services/abilitymgr/src/mission_data_storage.cpp @@ -15,8 +15,6 @@ #include "mission_data_storage.h" -#include - #include "file_util.h" #include "hilog_wrapper.h" #include "image_source.h" @@ -58,7 +56,10 @@ bool MissionDataStorage::LoadAllMissionInfo(std::list &mission } InnerMissionInfo misssionInfo; - misssionInfo.FromJsonStr(content); + if (!misssionInfo.FromJsonStr(content)) { + HILOG_ERROR("parse mission info failed. file: %{public}s", fileName.c_str()); + continue; + } missionInfoList.push_back(misssionInfo); } return true; @@ -131,7 +132,7 @@ bool MissionDataStorage::CheckFileNameValid(const std::string &fileName) return true; } -void MissionDataStorage::SaveMissionSnapshot(int32_t missionId, const MissionSnapshot& missionSnapshot) +void MissionDataStorage::SaveSnapshotFile(int32_t missionId, const MissionSnapshot& missionSnapshot) { std::string filePath = GetMissionSnapshotPath(missionId); std::string dirPath = OHOS::HiviewDFX::FileUtil::ExtractFilePath(filePath); @@ -150,6 +151,48 @@ void MissionDataStorage::SaveMissionSnapshot(int32_t missionId, const MissionSna } } +void MissionDataStorage::SaveMissionSnapshot(int32_t missionId, const MissionSnapshot& missionSnapshot) +{ + HILOG_INFO("snapshot: save snapshot from cache, missionId = %{public}d", missionId); + SaveCachedSnapshot(missionId, missionSnapshot); + SaveSnapshotFile(missionId, missionSnapshot); + HILOG_INFO("snapshot: delete snapshot from cache, missionId = %{public}d", missionId); + DeleteCachedSnapshot(missionId); +} + +bool MissionDataStorage::GetCachedSnapshot(int32_t missionId, MissionSnapshot& missionSnapshot) +{ + std::lock_guard lock(cachedPixelMapMutex_); + auto pixelMap = cachedPixelMap_.find(missionId); + if (pixelMap != cachedPixelMap_.end()) { + missionSnapshot.snapshot = pixelMap->second; + return true; + } + return false; +} + +bool MissionDataStorage::SaveCachedSnapshot(int32_t missionId, const MissionSnapshot& missionSnapshot) +{ + std::lock_guard lock(cachedPixelMapMutex_); + auto result = cachedPixelMap_.insert_or_assign(missionId, missionSnapshot.snapshot); + if (!result.second) { + HILOG_ERROR("snapshot: save snapshot cache failed, missionId = %{public}d", missionId); + return false; + } + return true; +} + +bool MissionDataStorage::DeleteCachedSnapshot(int32_t missionId) +{ + std::lock_guard lock(cachedPixelMapMutex_); + auto result = cachedPixelMap_.erase(missionId); + if (result != 1) { + HILOG_ERROR("snapshot: delete snapshot cache failed, missionId = %{public}d", missionId); + return false; + } + return true; +} + void MissionDataStorage::DeleteMissionSnapshot(int32_t missionId) { std::string filePath = GetMissionSnapshotPath(missionId); @@ -164,8 +207,12 @@ void MissionDataStorage::DeleteMissionSnapshot(int32_t missionId) } } -bool MissionDataStorage::GetMissionSnapshot(int missionId, MissionSnapshot& missionSnapshot) +bool MissionDataStorage::GetMissionSnapshot(int32_t missionId, MissionSnapshot& missionSnapshot) { + if (GetCachedSnapshot(missionId, missionSnapshot)) { + HILOG_INFO("snapshot: GetMissionSnapshot from cache, missionId = %{public}d", missionId); + return true; + } std::string filePath = GetMissionSnapshotPath(missionId); if (!OHOS::HiviewDFX::FileUtil::FileExists(filePath)) { HILOG_INFO("snapshot: storage snapshot not exists, missionId = %{public}d", missionId); @@ -188,7 +235,7 @@ bool MissionDataStorage::GetMissionSnapshot(int missionId, MissionSnapshot& miss return true; } -std::string MissionDataStorage::GetMissionSnapshotPath(int missionId) +std::string MissionDataStorage::GetMissionSnapshotPath(int32_t missionId) { return GetMissionDataDirPath() + "/" + MISSION_JSON_FILE_PREFIX + "_" + std::to_string(missionId) + PNG_FILE_SUFFIX; diff --git a/services/abilitymgr/src/mission_list.cpp b/services/abilitymgr/src/mission_list.cpp index 439df45cef9005ed2e283c1f95802acfcdfc8682..3771dc7c029bddb245d249cb0c387c3e81f65c4d 100644 --- a/services/abilitymgr/src/mission_list.cpp +++ b/services/abilitymgr/src/mission_list.cpp @@ -239,7 +239,7 @@ std::string MissionList::GetTypeName() return "NORMAL"; } case MissionListType::DEFAULT_STANDARD: { - return "DEFAULT_STAND"; + return "DEFAULT_STANDARD"; } case MissionListType::DEFAULT_SINGLE: { return "DEFAULT_SINGLE"; @@ -264,7 +264,8 @@ void MissionList::Dump(std::vector& info) } } -void MissionList::DumpStateByRecordId(std::vector &info, bool isClient, int32_t abilityRecordId) +void MissionList::DumpStateByRecordId( + std::vector &info, bool isClient, int32_t abilityRecordId, const std::vector ¶ms) { for (const auto& mission : missions_) { if (mission) { @@ -272,7 +273,7 @@ void MissionList::DumpStateByRecordId(std::vector &info, bool isCli if (abilityRecord) { if (abilityRecord->GetRecordId() == abilityRecordId) { HILOG_INFO("record begain to call DumpAbilityState %{public}s", __func__); - abilityRecord->DumpAbilityState(info, isClient); + abilityRecord->DumpAbilityState(info, isClient, params); return; } } @@ -281,12 +282,12 @@ void MissionList::DumpStateByRecordId(std::vector &info, bool isCli } void MissionList::DumpList(std::vector &info, bool isClient) { - std::string dumpInfo = " MissionList Type #" + GetTypeName(); + std::string dumpInfo = " MissionList Type #" + GetTypeName(); info.push_back(dumpInfo); for (const auto& mission : missions_) { if (mission) { - dumpInfo = " Mission ID #" + std::to_string(mission->GetMissionId()); + dumpInfo = " Mission ID #" + std::to_string(mission->GetMissionId()); dumpInfo += " mission name #[" + mission->GetMissionName() + "]" + " lockedState #" + std::to_string(mission->IsLockedState()); info.push_back(dumpInfo); @@ -294,7 +295,8 @@ void MissionList::DumpList(std::vector &info, bool isClient) auto abilityRecord = mission->GetAbilityRecord(); if (abilityRecord) { HILOG_INFO("record begain to call DumpAbilityState %{public}s", __func__); - abilityRecord->DumpAbilityState(info, isClient); + std::vector params; + abilityRecord->DumpAbilityState(info, isClient, params); } } } diff --git a/services/abilitymgr/src/mission_list_manager.cpp b/services/abilitymgr/src/mission_list_manager.cpp index 3ed3d7fe85b82f8bdbdecd218ff8ded83b2b323a..356412be32977ac1684e484a7d8a356d5b7f6c9c 100644 --- a/services/abilitymgr/src/mission_list_manager.cpp +++ b/services/abilitymgr/src/mission_list_manager.cpp @@ -145,13 +145,14 @@ int MissionListManager::GetMissionInfo(int32_t missionId, MissionInfo &missionIn return DelayedSingleton::GetInstance()->GetMissionInfoById(missionId, missionInfo); } -int MissionListManager::MoveMissionToFront(int32_t missionId) +int MissionListManager::MoveMissionToFront(int32_t missionId, std::shared_ptr startOptions) { std::lock_guard guard(managerLock_); - return MoveMissionToFront(missionId, true); + return MoveMissionToFront(missionId, true, startOptions); } -int MissionListManager::MoveMissionToFront(int32_t missionId, bool isCallerFromLauncher) +int MissionListManager::MoveMissionToFront(int32_t missionId, bool isCallerFromLauncher, + std::shared_ptr startOptions) { HILOG_INFO("move mission to front:%{public}d.", missionId); std::lock_guard guard(managerLock_); @@ -177,7 +178,11 @@ int MissionListManager::MoveMissionToFront(int32_t missionId, bool isCallerFromL HILOG_ERROR("get target ability record failed, missionId: %{public}d", missionId); return MOVE_MISSION_FAILED; } - + if (startOptions != nullptr) { + Want want(targetAbilityRecord->GetWant()); + want.SetParam(Want::PARAM_RESV_WINDOW_MODE, startOptions->GetWindowMode()); + targetAbilityRecord->SetWant(want); + } // schedule target ability to foreground. targetAbilityRecord->ProcessForegroundAbility(); HILOG_DEBUG("SetMovingState, missionId: %{public}d", missionId); @@ -483,12 +488,12 @@ void MissionListManager::MoveNoneTopMissionToDefaultList(const std::shared_ptrIsEmpty()) { auto item = missionList->GetTopMission(); - if (item == mission) { + if (item == nullptr || item == mission) { break; } missionList->RemoveMission(item); - if (mission->IsSingletonAbility()) { + if (item->IsSingletonAbility()) { defaultSingleList_->AddMissionToTop(item); } else { defaultStandardList_->AddMissionToTop(item); @@ -587,6 +592,63 @@ void MissionListManager::OnAbilityRequestDone(const sptr &token, } } +void MissionListManager::OnAppStateChanged(const AppInfo &info) +{ + std::lock_guard guard(managerLock_); + + if (info.state == AppState::TERMINATED || info.state == AppState::END) { + for (const auto& abilityRecord : terminateAbilityList_) { + if (!abilityRecord) { + HILOG_ERROR("abilityRecord is nullptr."); + continue; + } + if (info.processName == abilityRecord->GetAbilityInfo().process || + info.processName == abilityRecord->GetApplicationInfo().bundleName) { + abilityRecord->SetAppState(info.state); + } + } + } else { + for (const auto& missionList : currentMissionLists_) { + auto missions = missionList->GetAllMissions(); + for (const auto& missionInfo : missions) { + if (!missionInfo) { + HILOG_ERROR("missionInfo is nullptr."); + continue; + } + auto abilityRecord = missionInfo->GetAbilityRecord(); + if (info.processName == abilityRecord->GetAbilityInfo().process || + info.processName == abilityRecord->GetApplicationInfo().bundleName) { + abilityRecord->SetAppState(info.state); + } + } + } + auto defaultStandardListmissions = defaultStandardList_->GetAllMissions(); + for (const auto& missionInfo : defaultStandardListmissions) { + if (!missionInfo) { + HILOG_ERROR("defaultStandardListmissions is nullptr."); + continue; + } + auto abilityRecord = missionInfo->GetAbilityRecord(); + if (info.processName == abilityRecord->GetAbilityInfo().process || + info.processName == abilityRecord->GetApplicationInfo().bundleName) { + abilityRecord->SetAppState(info.state); + } + } + auto defaultSingleListmissions = defaultSingleList_->GetAllMissions(); + for (const auto& missionInfo : defaultSingleListmissions) { + if (!missionInfo) { + HILOG_ERROR("defaultSingleListmissions is nullptr."); + continue; + } + auto abilityRecord = missionInfo->GetAbilityRecord(); + if (info.processName == abilityRecord->GetAbilityInfo().process || + info.processName == abilityRecord->GetApplicationInfo().bundleName) { + abilityRecord->SetAppState(info.state); + } + } + } +} + std::shared_ptr MissionListManager::GetAbilityRecordByToken( const sptr &token) const { @@ -801,22 +863,10 @@ void MissionListManager::CompleteBackground(const std::shared_ptr abilityRecord->CallRequest(); abilityRecord->SetStartToBackground(false); } - - auto mission = abilityRecord->GetMission(); - if (!mission) { - HILOG_ERROR("snapshot: GetMission failed"); - return; - } - MissionSnapshot snapshot; - DelayedSingleton::GetInstance()->UpdateMissionSnapshot(mission->GetMissionId(), - abilityRecord->GetToken(), snapshot); - if (listenerController_) { - listenerController_->NotifyMissionSnapshotChanged(mission->GetMissionId()); - } } int MissionListManager::TerminateAbility(const std::shared_ptr &abilityRecord, - int resultCode, const Want *resultWant) + int resultCode, const Want *resultWant, bool flag) { std::string element = abilityRecord->GetWant().GetElement().GetURI(); HILOG_DEBUG("Terminate ability, ability is %{public}s", element.c_str()); @@ -838,7 +888,7 @@ int MissionListManager::TerminateAbility(const std::shared_ptr &a abilityRecord->SaveResultToCallers(resultCode, resultWant); } - return TerminateAbilityLocked(abilityRecord); + return TerminateAbilityLocked(abilityRecord, flag); } int MissionListManager::TerminateAbility(const std::shared_ptr &caller, int requestCode) @@ -858,15 +908,15 @@ int MissionListManager::TerminateAbility(const std::shared_ptr &c return result; } - return TerminateAbility(targetAbility, DEFAULT_INVAL_VALUE, nullptr); + return TerminateAbility(targetAbility, DEFAULT_INVAL_VALUE, nullptr, true); } -int MissionListManager::TerminateAbilityLocked(const std::shared_ptr &abilityRecord) +int MissionListManager::TerminateAbilityLocked(const std::shared_ptr &abilityRecord, bool flag) { std::string element = abilityRecord->GetWant().GetElement().GetURI(); HILOG_DEBUG("Terminate ability locked, ability is %{public}s", element.c_str()); // remove AbilityRecord out of stack - RemoveTerminatingAbility(abilityRecord); + RemoveTerminatingAbility(abilityRecord, flag); abilityRecord->SendResultToCallers(); // 1. if the ability was foregorund, first should find wether there is other ability foregorund @@ -902,7 +952,7 @@ int MissionListManager::TerminateAbilityLocked(const std::shared_ptr &abilityRecord) +void MissionListManager::RemoveTerminatingAbility(const std::shared_ptr &abilityRecord, bool flag) { std::string element = abilityRecord->GetWant().GetElement().GetURI(); HILOG_DEBUG("RemoveTerminatingAbility, ability is %{public}s", element.c_str()); @@ -925,9 +975,9 @@ void MissionListManager::RemoveTerminatingAbility(const std::shared_ptrGetAbilityState()); return; } - // 3. if run on a laptop, noting to do - if (IsPC()) { - HILOG_DEBUG("Run on a laptop, no need to schedule next ability."); + // 3. if close ability, noting to do + if (!flag) { + HILOG_DEBUG("close ability schedule."); return; } @@ -1071,7 +1121,7 @@ int MissionListManager::ClearMissionLocked(int missionId, std::shared_ptrSetTerminatingState(); - auto ret = TerminateAbilityLocked(abilityRecord); + auto ret = TerminateAbilityLocked(abilityRecord, false); if (ret != ERR_OK) { HILOG_ERROR("clear mission error: %{public}d.", ret); return REMOVE_MISSION_FAILED; @@ -1138,7 +1188,6 @@ int MissionListManager::SetMissionLockedState(int missionId, bool lockedState) HILOG_ERROR("mission is not exist, missionId %{public}d", missionId); return MISSION_NOT_FOUND; } - innerMissionInfo.missionInfo.time = Time2str(time(0)); innerMissionInfo.missionInfo.lockedState = lockedState; DelayedSingleton::GetInstance()->UpdateMissionInfo(innerMissionInfo); return ERR_OK; @@ -1151,6 +1200,7 @@ void MissionListManager::MoveToBackgroundTask(const std::shared_ptrGetWant().GetElement().GetURI(); HILOG_INFO("Ability record: %{public}s", backElement.c_str()); auto self(shared_from_this()); + UpdateMissionSnapshot(abilityRecord); auto task = [abilityRecord, self]() { HILOG_WARN("mission list manager move to background timeout."); self->CompleteBackground(abilityRecord); @@ -1158,6 +1208,18 @@ void MissionListManager::MoveToBackgroundTask(const std::shared_ptrBackgroundAbility(task); } +void MissionListManager::UpdateMissionSnapshot(const std::shared_ptr& abilityRecord) +{ + CHECK_POINTER(abilityRecord); + int32_t missionId = abilityRecord->GetMissionId(); + MissionSnapshot snapshot; + DelayedSingleton::GetInstance()->UpdateMissionSnapshot(missionId, abilityRecord->GetToken(), + snapshot); + if (listenerController_) { + listenerController_->NotifyMissionSnapshotChanged(missionId); + } +} + void MissionListManager::OnTimeOut(uint32_t msgId, int64_t eventId) { HILOG_DEBUG("On timeout, msgId is %{public}d", msgId); @@ -1573,7 +1635,7 @@ void MissionListManager::Dump(std::vector &info) } void MissionListManager::DumpMissionListByRecordId( - std::vector &info, bool isClient, int32_t abilityRecordId) + std::vector &info, bool isClient, int32_t abilityRecordId, const std::vector ¶ms) { std::lock_guard guard(managerLock_); std::string dumpInfo = "User ID #" + std::to_string(userId_); @@ -1581,69 +1643,71 @@ void MissionListManager::DumpMissionListByRecordId( for (const auto& missionList : currentMissionLists_) { if (missionList && missionList != launcherList_) { HILOG_INFO("missionList begain to call DumpMissionListByRecordId %{public}s", __func__); - missionList->DumpStateByRecordId(info, isClient, abilityRecordId); + missionList->DumpStateByRecordId(info, isClient, abilityRecordId, params); } } if (defaultStandardList_) { HILOG_INFO("defaultStandardList begain to call DumpMissionListByRecordId %{public}s", __func__); - defaultStandardList_->DumpStateByRecordId(info, isClient, abilityRecordId); + defaultStandardList_->DumpStateByRecordId(info, isClient, abilityRecordId, params); } if (defaultSingleList_) { HILOG_INFO("defaultSingleList begain to call DumpMissionListByRecordId %{public}s", __func__); - defaultSingleList_->DumpStateByRecordId(info, isClient, abilityRecordId); + defaultSingleList_->DumpStateByRecordId(info, isClient, abilityRecordId, params); } if (launcherList_) { HILOG_INFO("launcherList begain to call DumpMissionListByRecordId %{public}s", __func__); - launcherList_->DumpStateByRecordId(info, isClient, abilityRecordId); + launcherList_->DumpStateByRecordId(info, isClient, abilityRecordId, params); } } void MissionListManager::DumpMissionList(std::vector &info, bool isClient, const std::string &args) { std::lock_guard guard(managerLock_); + + if (args.size() != 0 && + args != "NORMAL" && + args != "DEFAULT_STANDARD" && + args != "DEFAULT_SINGLE" && + args != "LAUNCHER") { + info.emplace_back("MissionList Type NORMAL|DEFAULT_STANDARD|DEFAULT_SINGLE|LAUNCHER"); + return; + } + std::string dumpInfo = "User ID #" + std::to_string(userId_); info.push_back(dumpInfo); if (args.size() == 0 || args == "NORMAL") { - dumpInfo = " current mission lists:{"; + dumpInfo = " Current mission lists:"; info.push_back(dumpInfo); for (const auto& missionList : currentMissionLists_) { if (missionList) { missionList->DumpList(info, isClient); } } - dumpInfo = " }"; - info.push_back(dumpInfo); } if (args.size() == 0 || args == "DEFAULT_STANDARD") { - dumpInfo = " default stand mission list:{"; + dumpInfo = " default stand mission list:"; info.push_back(dumpInfo); if (defaultStandardList_) { defaultStandardList_->DumpList(info, isClient); } - dumpInfo = " }"; - info.push_back(dumpInfo); } if (args.size() == 0 || args == "DEFAULT_SINGLE") { - dumpInfo = " default single mission list:{"; + dumpInfo = " default single mission list:"; info.push_back(dumpInfo); if (defaultSingleList_) { defaultSingleList_->DumpList(info, isClient); } - dumpInfo = " }"; - info.push_back(dumpInfo); } if (args.size() == 0 || args == "LAUNCHER") { - dumpInfo = " launcher mission list:{"; + dumpInfo = " launcher mission list:"; info.push_back(dumpInfo); if (launcherList_) { launcherList_->DumpList(info, isClient); } - dumpInfo = " }"; - info.push_back(dumpInfo); } } @@ -1863,33 +1927,6 @@ std::shared_ptr MissionListManager::GetMissionBySpecifiedFlag(const std return defaultStandardList_->GetMissionBySpecifiedFlag(flag); } -bool MissionListManager::IsPC() -{ - if (MissionDmInitCallback::isInit_) { - return isPC_; - } - std::string pkgName = "ohos.aafwk.aafwk_standard"; - auto callback = std::make_shared(); - int32_t ret = DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(pkgName, callback); - if (ret != ERR_OK) { - HILOG_WARN("DeviceManager initialization failed."); - return false; - } - DistributedHardware::DmDeviceInfo deviceInfo; - ret = DistributedHardware::DeviceManager::GetInstance().GetLocalDeviceInfo(pkgName, deviceInfo); - if (ret != ERR_OK) { - HILOG_WARN("Failed to get local device info."); - return false; - } - MissionDmInitCallback::isInit_ = true; - if (deviceInfo.deviceTypeId != DistributedHardware::DmDeviceType::DEVICE_TYPE_PC) { - HILOG_WARN("The device is not a laptop."); - return false; - } - isPC_ = true; - return isPC_; -} - bool MissionListManager::MissionDmInitCallback::isInit_ = false; void MissionListManager::MissionDmInitCallback::OnRemoteDied() { @@ -1956,21 +1993,31 @@ void MissionListManager::GetAbilityRunningInfos(std::vector std::shared_ptr MissionListManager::GetCurrentTopAbility(const std::string &bundleName) { + std::lock_guard guard(managerLock_); + for (auto &missionList : currentMissionLists_) { if (!missionList) { HILOG_WARN("Invalid missionList."); continue; } - auto abilityRecord = missionList->GetLauncherRoot(); - if (!abilityRecord) { - HILOG_ERROR("Invalid ability record."); - return {}; - } + auto missions = missionList->GetAllMissions(); + for (auto &mission : missions) { + if (!mission) { + HILOG_WARN("Invalid mission."); + continue; + } - auto appInfo = abilityRecord->GetApplicationInfo(); - if (bundleName.compare(appInfo.bundleName)) { - return abilityRecord; + auto abilityRecord = mission->GetAbilityRecord(); + if (!abilityRecord) { + HILOG_WARN("Invalid ability record."); + continue; + } + + auto appInfo = abilityRecord->GetApplicationInfo(); + if (bundleName.compare(appInfo.bundleName) == 0) { + return abilityRecord; + } } } diff --git a/services/abilitymgr/src/pending_want_manager.cpp b/services/abilitymgr/src/pending_want_manager.cpp index f7461d333c9aec19453050c2e60d7df1ea15c303..0f4c522e1bfb23e1d520a61eb71585d99f17ac3d 100644 --- a/services/abilitymgr/src/pending_want_manager.cpp +++ b/services/abilitymgr/src/pending_want_manager.cpp @@ -156,6 +156,9 @@ bool PendingWantManager::CheckPendingWantRecordByKey( if (inputKey->GetRequestCode() != key->GetRequestCode()) { return false; } + if (inputKey->GetRequestWant().ToString().compare(key->GetRequestWant().ToString()) != 0) { + return false; + } if (!inputKey->GetRequestWant().OperationEquals(key->GetRequestWant())) { return false; } @@ -235,7 +238,8 @@ int32_t PendingWantManager::DeviceIdDetermine( return result; } DistributedClient dmsClient; - result = dmsClient.StartRemoteAbility(want, callerUid, requestCode); + uint32_t accessToken = IPCSkeleton::GetCallingTokenID(); + result = dmsClient.StartRemoteAbility(want, callerUid, requestCode, accessToken); if (result != ERR_OK) { HILOG_ERROR("%{public}s: StartRemoteAbility Error! result = %{public}d", __func__, result); } @@ -523,7 +527,7 @@ void PendingWantManager::Dump(std::vector &info) for (const auto &item : wantRecords_) { const auto &pendingKey = item.first; - dumpInfo = " PendWantRecord ID #" + std::to_string(pendingKey->GetUserId()) + + dumpInfo = " PendWantRecord ID #" + std::to_string(pendingKey->GetCode()) + " type #" + std::to_string(pendingKey->GetType()); info.push_back(dumpInfo); dumpInfo = " bundle name [" + pendingKey->GetBundleName() + "]"; @@ -547,5 +551,38 @@ void PendingWantManager::Dump(std::vector &info) } } } +void PendingWantManager::DumpByRecordId(std::vector &info, const std::string &args) +{ + std::string dumpInfo = " PendingWantRecords:"; + info.push_back(dumpInfo); + + for (const auto &item : wantRecords_) { + const auto &pendingKey = item.first; + if (args == std::to_string(pendingKey->GetCode())) { + dumpInfo = " PendWantRecord ID #" + std::to_string(pendingKey->GetCode()) + + " type #" + std::to_string(pendingKey->GetType()); + info.push_back(dumpInfo); + dumpInfo = " bundle name [" + pendingKey->GetBundleName() + "]"; + info.push_back(dumpInfo); + dumpInfo = " result who [" + pendingKey->GetRequestWho() + "]"; + info.push_back(dumpInfo); + dumpInfo = " request code #" + std::to_string(pendingKey->GetRequestCode()) + + " flags #" + std::to_string(pendingKey->GetFlags()); + info.push_back(dumpInfo); + dumpInfo = " resolved type [" + pendingKey->GetRequestResolvedType() + "]"; + info.push_back(dumpInfo); + dumpInfo = " Wants:"; + info.push_back(dumpInfo); + auto Wants = pendingKey->GetAllWantsInfos(); + for (const auto& Want : Wants) { + dumpInfo = " uri [" + Want.want.GetElement().GetDeviceID() + "//" + + Want.want.GetElement().GetBundleName() + "/" + Want.want.GetElement().GetAbilityName() + "]"; + info.push_back(dumpInfo); + dumpInfo = " resolved types [" + Want.resolvedTypes + "]"; + info.push_back(dumpInfo); + } + } + } +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/screenshot_response.cpp b/services/abilitymgr/src/screenshot_response.cpp index b54be5f62e8f205bc4109390b5b8bc45bdc27e18..7ffe506cd047b5248287166e1da96cf385deda63 100644 --- a/services/abilitymgr/src/screenshot_response.cpp +++ b/services/abilitymgr/src/screenshot_response.cpp @@ -13,10 +13,6 @@ * limitations under the License. */ -#include -#include -#include -#include #include "hilog_wrapper.h" #include "screenshot_response.h" diff --git a/services/abilitymgr/src/shared_memory.cpp b/services/abilitymgr/src/shared_memory.cpp index 4a40c04c192eb4b45f9cc1da87a3e6e150e0f194..621209f63bd603400f0eca0e54b84c5e462c80c9 100644 --- a/services/abilitymgr/src/shared_memory.cpp +++ b/services/abilitymgr/src/shared_memory.cpp @@ -14,10 +14,11 @@ */ #include "shared_memory.h" -#include -#include + #include +#include #include +#include #include "hilog_wrapper.h" #include "securec.h" @@ -77,8 +78,6 @@ int SharedMemory::PushSharedMemory(const void *data, const int size) return -1; } - // memcpy(shared, data, size); - if (shmdt(shared) == -1) { ReleaseShmId(shmId); HILOG_ERROR("shmdt failed: %{public}d.", errno); @@ -90,6 +89,10 @@ int SharedMemory::PushSharedMemory(const void *data, const int size) void* SharedMemory::PopSharedMemory(int shmKey, int size) { + if (size <= 0) { + HILOG_ERROR("size is invalid: %{public}d.", size); + return nullptr; + } void *data = reinterpret_cast(malloc(size)); int shmId = shmget(shmKey, 0, 0 | SHM_READ_WRITE_PERMISSIONS); if (shmId == -1) { @@ -111,7 +114,6 @@ void* SharedMemory::PopSharedMemory(int shmKey, int size) HILOG_ERROR("Failed to memory copy, retCode[%{public}d].", retCode); return nullptr; } - // memcpy(data, shared, size); if (shmdt(shared) == -1) { ReleaseShmId(shmId); diff --git a/services/abilitymgr/src/start_options.cpp b/services/abilitymgr/src/start_options.cpp index 20eb4bfd33af410f4bf68d5d27c14aa979080452..e7bc58c95962709e5811ba18804a40eaaa89036c 100644 --- a/services/abilitymgr/src/start_options.cpp +++ b/services/abilitymgr/src/start_options.cpp @@ -17,8 +17,20 @@ namespace OHOS { namespace AAFwk { +StartOptions::StartOptions(const StartOptions &other) +{ + windowMode_ = other.windowMode_; + displayId_ = other.displayId_; +} -const std::string StartOptions::STRING_DISPLAY_ID = "ohos.aafwk.displayId"; +StartOptions &StartOptions::operator=(const StartOptions &other) +{ + if (this != &other) { + windowMode_ = other.windowMode_; + displayId_ = other.displayId_; + } + return *this; +} bool StartOptions::ReadFromParcel(Parcel &parcel) { diff --git a/services/abilitymgr/test/BUILD.gn b/services/abilitymgr/test/BUILD.gn index f131c140d4d413a6285d26b83525370122839498..b048a156ae3f283944c73aa5954d82fc15aefdae 100644 --- a/services/abilitymgr/test/BUILD.gn +++ b/services/abilitymgr/test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -43,7 +43,6 @@ ohos_source_set("abilityms_test_source") { "${services_path}/abilitymgr/src/data_ability_record.cpp", "${services_path}/abilitymgr/src/image_info.cpp", "${services_path}/abilitymgr/src/inner_mission_info.cpp", - "${services_path}/abilitymgr/src/kernal_ability_manager.cpp", "${services_path}/abilitymgr/src/kernal_system_app_manager.cpp", "${services_path}/abilitymgr/src/launch_param.cpp", "${services_path}/abilitymgr/src/lifecycle_deal.cpp", @@ -130,6 +129,7 @@ ohos_source_set("abilityms_test_source") { deps = [ "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", "${innerkits_path}/base:base", + "${innerkits_path}/uri_permission:uri_permission_mgr", "${innerkits_path}/want:want", "${services_path}/abilitymgr/test/mock/libs/sa_mgr:sa_mgr_mock", "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", @@ -145,6 +145,7 @@ ohos_source_set("abilityms_test_source") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "bytrace_standard:bytrace_core", "ces_standard:cesfwk_core", "ces_standard:cesfwk_innerkits", diff --git a/services/abilitymgr/test/mock/include/mock_app_manager_client.h b/services/abilitymgr/test/mock/include/mock_app_manager_client.h index ffd8d4d331b55915a26c01d3e4b9ef3e94152951..c6620b266d0e22cc0a0d834c77cdbfa065c806ab 100644 --- a/services/abilitymgr/test/mock/include/mock_app_manager_client.h +++ b/services/abilitymgr/test/mock/include/mock_app_manager_client.h @@ -28,8 +28,8 @@ public: {} ~MockAppMgrClient() {} - MOCK_METHOD4(LoadAbility, AppMgrResultCode(const sptr &token, const sptr &preToken, - const AbilityInfo &abilityInfo, const ApplicationInfo &appInfo)); + MOCK_METHOD5(LoadAbility, AppMgrResultCode(const sptr &token, const sptr &preToken, + const AbilityInfo &abilityInfo, const ApplicationInfo &appInfo, const AAFwk::Want &want)); MOCK_METHOD1(TerminateAbility, AppMgrResultCode(const sptr &)); MOCK_METHOD2(UpdateAbilityState, AppMgrResultCode(const sptr &token, const AbilityState state)); diff --git a/services/abilitymgr/test/mock/include/mock_app_mgr_client.h b/services/abilitymgr/test/mock/include/mock_app_mgr_client.h index 102804069dfdc9a56ab59f530a70c8ad98daa5e6..74457168805124bcf81ec127c6da0c79982713f1 100644 --- a/services/abilitymgr/test/mock/include/mock_app_mgr_client.h +++ b/services/abilitymgr/test/mock/include/mock_app_mgr_client.h @@ -29,7 +29,7 @@ public: virtual ~MockAppMgrClient() {}; virtual AppMgrResultCode LoadAbility(const sptr &token, const sptr &preToken, - const AbilityInfo &abilityInfo, const ApplicationInfo &appInfo) + const AbilityInfo &abilityInfo, const ApplicationInfo &appInfo, const AAFwk::Want &want) { HILOG_INFO("MockAppMgrClient LoadAbility enter."); token_ = token; diff --git a/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h b/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h index 03bb8e5c183f9a09b5bf7320e82f049387619487..bc9551997f34f767b915a6c10623cb226b352070 100755 --- a/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h +++ b/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h @@ -97,11 +97,11 @@ public: { return std::vector>(); }; - virtual void NotifyContinuationResult(const int32_t result) override + virtual void NotifyContinuationResult(int32_t result) override {}; virtual void ContinueAbility(const std::string& deviceId) override {}; - virtual void DumpAbilityInfo(std::vector &info) override + virtual void DumpAbilityInfo(const std::vector ¶ms, std::vector &info) override {}; virtual sptr CallRequest() override { diff --git a/services/abilitymgr/test/mock/libs/ability_scheduler_mock/ability_scheduler_mock.h b/services/abilitymgr/test/mock/libs/ability_scheduler_mock/ability_scheduler_mock.h index 34bcf6228f5ab4af557b514bdd3d538270aa7c60..ec5ea8943c5098f01998f4854e1d93311e8bcff4 100755 --- a/services/abilitymgr/test/mock/libs/ability_scheduler_mock/ability_scheduler_mock.h +++ b/services/abilitymgr/test/mock/libs/ability_scheduler_mock/ability_scheduler_mock.h @@ -41,9 +41,9 @@ public: MOCK_METHOD3(ScheduleCommandAbility, void(const Want &, bool, int)); MOCK_METHOD1(NotifyTopActiveAbilityChanged, void(bool flag)); MOCK_METHOD2(NotifyMultiWinModeChanged, void(int32_t winModeKey, bool flag)); - MOCK_METHOD1(NotifyContinuationResult, void(const int32_t result)); + MOCK_METHOD1(NotifyContinuationResult, void(int32_t result)); MOCK_METHOD1(ContinueAbility, void(const std::string& deviceId)); - MOCK_METHOD1(DumpAbilityInfo, void(std::vector &info)); + MOCK_METHOD2(DumpAbilityInfo, void(const std::vector ¶ms, std::vector &info)); int InvokeSendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { @@ -150,4 +150,4 @@ public: int code_ = 0; }; } // namespace AAFwk -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/BUILD.gn b/services/abilitymgr/test/mock/libs/appexecfwk_core/BUILD.gn index 4fd28ea4ce44b1a6ba5f431d264ad1404c3daa4e..5bf898704cac882a98ea477c7f14bf9710328f5a 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/BUILD.gn +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/BUILD.gn @@ -29,6 +29,7 @@ config("appexecfwk_core_mock_config") { "//base/notification/ces_standard/interfaces/innerkits/native/include/", "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/aakit/include/", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr/", ] } diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_mgr_client.h b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_mgr_client.h index 607c1fbf4d23bdc73ebfd6aee66594426065f213..f46e167b0515962d93cc30860d2ac96e672a564e 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_mgr_client.h +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/appmgr/app_mgr_client.h @@ -24,6 +24,7 @@ // #include "app_mgr_constants.h" #include "iapp_state_callback.h" #include "running_process_info.h" +#include "want.h" namespace OHOS { namespace AppExecFwk { @@ -42,7 +43,7 @@ public: * @return Returns RESULT_OK on success, others on failure. */ virtual AppMgrResultCode LoadAbility(const sptr &token, const sptr &preToken, - const AbilityInfo &abilityInfo, const ApplicationInfo &appInfo); + const AbilityInfo &abilityInfo, const ApplicationInfo &appInfo, const AAFwk::Want &want); /** * Terminate ability. diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h deleted file mode 100644 index d911ef15d0a2bf06c273b82d61e9c62f15542fc3..0000000000000000000000000000000000000000 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h +++ /dev/null @@ -1,507 +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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_BUNDLEMGR_BUNDLE_MGR_INTERFACE_H -#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_BUNDLEMGR_BUNDLE_MGR_INTERFACE_H - -#include "ability_info.h" -#include "form_info.h" -#include "shortcut_info.h" -#include "module_usage_record.h" -#include "application_info.h" -#include "bundle_info.h" -#include "bundle_user_mgr_interface.h" -#include "hap_module_info.h" -#include "permission_def.h" -#include "bundle_installer_interface.h" -#include "bundle_status_callback_interface.h" -#include "clean_cache_callback_interface.h" -#include "common_event_info.h" -#include "on_permission_changed_callback_interface.h" -#include "ohos/aafwk/content/want.h" -#include "distributed_bundle_info.h" - -namespace OHOS { -namespace AppExecFwk { -enum class DumpFlag { - DUMP_BUNDLE_LIST = 1, // corresponse to option "-bundle-list" - DUMP_ALL_BUNDLE_INFO, // corresponse to option "-bundle" - DUMP_BUNDLE_INFO, // corresponse to option "-bundle [name]" -}; - -class IBundleMgr : public IRemoteBroker { -public: - DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.BundleMgr"); - - using Want = OHOS::AAFwk::Want; - /** - * @brief Obtains the ApplicationInfo based on a given bundle name. - * @param appName Indicates the application bundle name to be queried. - * @param flag Indicates the flag used to specify information contained - * in the ApplicationInfo object that will be returned. - * @param userId Indicates the user ID. - * @param appInfo Indicates the obtained ApplicationInfo object. - * @return Returns true if the application is successfully obtained; returns false otherwise. - */ - virtual bool GetApplicationInfo( - const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) = 0; - /** - * @brief Obtains information about all installed applications of a specified user. - * @param flag Indicates the flag used to specify information contained - * in the ApplicationInfo objects that will be returned. - * @param userId Indicates the user ID. - * @param appInfos Indicates all of the obtained ApplicationInfo objects. - * @return Returns true if the application is successfully obtained; returns false otherwise. - */ - virtual bool GetApplicationInfos( - const ApplicationFlag flag, const int userId, std::vector &appInfos) = 0; - /** - * @brief Obtains the BundleInfo based on a given bundle name. - * @param bundleName Indicates the application bundle name to be queried. - * @param flag Indicates the information contained in the BundleInfo object to be returned. - * @param bundleInfo Indicates the obtained BundleInfo object. - * @param userId Indicates the user ID. - * @return Returns true if the BundleInfo is successfully obtained; returns false otherwise. - */ - virtual bool GetBundleInfo( - const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId = 0) = 0; - /** - * @brief Obtains BundleInfo of all bundles available in the system. - * @param flag Indicates the flag used to specify information contained in the BundleInfo that will be returned. - * @param bundleInfos Indicates all of the obtained BundleInfo objects. - * @param userId Indicates the user ID. - * @return Returns true if the BundleInfos is successfully obtained; returns false otherwise. - */ - virtual bool GetBundleInfos( - const BundleFlag flag, std::vector &bundleInfos, int32_t userId = 0) = 0; - /** - * @brief Obtains the application UID based on the given bundle name and user ID. - * @param bundleName Indicates the bundle name of the application. - * @param userId Indicates the user ID. - * @return Returns the uid if successfully obtained; returns -1 otherwise. - */ - virtual int GetUidByBundleName(const std::string &bundleName, const int userId) = 0; - /** - * @brief Obtains the application ID based on the given bundle name and user ID. - * @param bundleName Indicates the bundle name of the application. - * @param userId Indicates the user ID. - * @return Returns the application ID if successfully obtained; returns empty string otherwise. - */ - virtual std::string GetAppIdByBundleName(const std::string &bundleName, const int userId) = 0; - /** - * @brief Obtains the bundle name of a specified application based on the given UID. - * @param uid Indicates the uid. - * @param bundleName Indicates the obtained bundle name. - * @return Returns true if the bundle name is successfully obtained; returns false otherwise. - */ - virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) = 0; - /** - * @brief Obtains all bundle names of a specified application based on the given application UID. - * @param uid Indicates the uid. - * @param bundleNames Indicates the obtained bundle names. - * @return Returns true if the bundle names is successfully obtained; returns false otherwise. - */ - virtual bool GetBundlesForUid(const int uid, std::vector &bundleNames) = 0; - /** - * @brief Obtains the formal name associated with the given UID. - * @param uid Indicates the uid. - * @param name Indicates the obtained formal name. - * @return Returns true if the formal name is successfully obtained; returns false otherwise. - */ - virtual bool GetNameForUid(const int uid, std::string &name) = 0; - /** - * @brief Obtains an array of all group IDs associated with a specified bundle. - * @param bundleName Indicates the bundle name. - * @param gids Indicates the group IDs associated with the specified bundle. - * @return Returns true if the gids is successfully obtained; returns false otherwise. - */ - virtual bool GetBundleGids(const std::string &bundleName, std::vector &gids) = 0; - /** - * @brief Obtains the type of a specified application based on the given bundle name. - * @param bundleName Indicates the bundle name. - * @return Returns "system" if the bundle is a system application; returns "third-party" otherwise. - */ - virtual std::string GetAppType(const std::string &bundleName) = 0; - /** - * @brief Check whether the app is system app by it's UID. - * @param uid Indicates the uid. - * @return Returns true if the bundle is a system application; returns false otherwise. - */ - virtual bool CheckIsSystemAppByUid(const int uid) = 0; - /** - * @brief Obtains the BundleInfo of application bundles based on the specified metaData. - * @param metaData Indicates the metadata to get in the bundle. - * @param bundleInfos Indicates all of the obtained BundleInfo objects. - * @return Returns true if the BundleInfos is successfully obtained; returns false otherwise. - */ - virtual bool GetBundleInfosByMetaData(const std::string &metaData, std::vector &bundleInfos) = 0; - /** - * @brief Query the AbilityInfo by the given Want. - * @param want Indicates the information of the ability. - * @param abilityInfo Indicates the obtained AbilityInfo object. - * @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise. - */ - virtual bool QueryAbilityInfo(const Want &want, AbilityInfo &abilityInfo) = 0; - /** - * @brief Query the AbilityInfo of list by the given Want. - * @param want Indicates the information of the ability. - * @param abilityInfos Indicates the obtained AbilityInfos object. - * @return Returns true if the AbilityInfos is successfully obtained; returns false otherwise. - */ - virtual bool QueryAbilityInfos(const Want &want, std::vector &abilityInfos) = 0; - /** - * @brief Query the AbilityInfo by ability.uri in config.json. - * @param abilityUri Indicates the uri of the ability. - * @param abilityInfo Indicates the obtained AbilityInfo object. - * @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise. - */ - virtual bool QueryAbilityInfosForClone(const Want &want, std::vector &abilityInfos) = 0; - virtual bool QueryAbilityInfoByUri(const std::string &abilityUri, AbilityInfo &abilityInfo) = 0; - /** - * @brief Obtains the BundleInfo of all keep-alive applications in the system. - * @param bundleInfos Indicates all of the obtained BundleInfo objects. - * @return Returns true if the BundleInfos is successfully obtained; returns false otherwise. - */ - virtual bool QueryKeepAliveBundleInfos(std::vector &bundleInfos) = 0; - /** - * @brief Obtains the label of a specified ability. - * @param bundleName Indicates the bundle name. - * @param className Indicates the ability class name. - * @return Returns the label of the ability if exist; returns empty string otherwise. - */ - virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) = 0; - /** - * @brief Obtains information about an application bundle contained in an ohos Ability Package (HAP). - * @param hapFilePath Indicates the absolute file path of the HAP. - * @param flag Indicates the information contained in the BundleInfo object to be returned. - * @param bundleInfo Indicates the obtained BundleInfo object. - * @return Returns true if the BundleInfo is successfully obtained; returns false otherwise. - */ - virtual bool GetBundleArchiveInfo( - const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) = 0; - /** - * @brief Obtain the HAP module info of a specific ability. - * @param abilityInfo Indicates the ability. - * @param hapModuleInfo Indicates the obtained HapModuleInfo object. - * @return Returns true if the HapModuleInfo is successfully obtained; returns false otherwise. - */ - virtual bool GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) = 0; - /** - * @brief Obtains the Want for starting the main ability of an application based on the given bundle name. - * @param bundleName Indicates the bundle name. - * @param want Indicates the obtained launch Want object. - * @return Returns true if the launch Want object is successfully obtained; returns false otherwise. - */ - virtual bool GetLaunchWantForBundle(const std::string &bundleName, Want &want) = 0; - /** - * @brief Checks whether the publickeys of two bundles are the same. - * @param firstBundleName Indicates the first bundle name. - * @param secondBundleName Indicates the second bundle name. - * @return Returns SIGNATURE_UNKNOWN_BUNDLE if at least one of the given bundles is not found; - * returns SIGNATURE_NOT_MATCHED if their publickeys are different; - * returns SIGNATURE_MATCHED if their publickeys are the same. - */ - virtual int CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) = 0; - /** - * @brief Checks whether a specified bundle has been granted a specific permission. - * @param bundleName Indicates the name of the bundle to check. - * @param permission Indicates the permission to check. - * @return Returns 0 if the bundle has the permission; returns -1 otherwise. - */ - virtual int CheckPermission(const std::string &bundleName, const std::string &permission) = 0; - /** - * @brief Obtains detailed information about a specified permission. - * @param permissionName Indicates the name of the ohos permission. - * @param permissionDef Indicates the object containing detailed information about the given ohos permission. - * @return Returns true if the PermissionDef object is successfully obtained; returns false otherwise. - */ - virtual bool GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) = 0; - /** - * @brief Obtains all known permission groups in the system. - * @param permissionDefs Indicates the list of objects containing the permission group information. - * @return Returns true if the PermissionDef objects is successfully obtained; returns false otherwise. - */ - virtual bool GetAllPermissionGroupDefs(std::vector &permissionDefs) = 0; - /** - * @brief Obtains all known permission groups in the system. - * @param permissions Indicates the permission array. - * @param appNames Indicates the list of application names that have the specified permissions. - * @return Returns true if the application names is successfully obtained; returns false otherwise. - */ - virtual bool GetAppsGrantedPermissions( - const std::vector &permissions, std::vector &appNames) = 0; - /** - * @brief Checks whether the system has a specified capability. - * @param capName Indicates the name of the system feature to check. - * @return Returns true if the given feature specified by name is available in the system; returns false otherwise. - */ - virtual bool HasSystemCapability(const std::string &capName) = 0; - /** - * @brief Obtains the capabilities that are available in the system. - * @param systemCaps Indicates the list of capabilities available in the system. - * @return Returns true if capabilities in the system are successfully obtained; returns false otherwise. - */ - virtual bool GetSystemAvailableCapabilities(std::vector &systemCaps) = 0; - /** - * @brief Checks whether the current device has been started in safe mode. - * @return Returns true if the device is in safe mode; returns false otherwise. - */ - virtual bool IsSafeMode() = 0; - /** - * @brief Clears cache data of a specified application. - * @param bundleName Indicates the bundle name of the application whose cache data is to be cleared. - * @param cleanCacheCallback Indicates the callback to be invoked for returning the operation result. - * @return Returns true if this function is successfully called; returns false otherwise. - */ - virtual bool CleanBundleCacheFiles( - const std::string &bundleName, const sptr &cleanCacheCallback) = 0; - /** - * @brief Clears application running data of a specified application. - * @param bundleName Indicates the bundle name of the application whose data is to be cleared. - * @return Returns true if the data cleared successfully; returns false otherwise. - */ - virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0) = 0; - /** - * @brief Register the specific bundle status callback. - * @param bundleStatusCallback Indicates the callback to be invoked for returning the bundle status changed result. - * @return Returns true if this function is successfully called; returns false otherwise. - */ - virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) = 0; - /** - * @brief Clear the specific bundle status callback. - * @param bundleStatusCallback Indicates the callback to be cleared. - * @return Returns true if this function is successfully called; returns false otherwise. - */ - virtual bool ClearBundleStatusCallback(const sptr &bundleStatusCallback) = 0; - /** - * @brief Unregister all the callbacks of status changed. - * @return Returns true if this function is successfully called; returns false otherwise. - */ - virtual bool UnregisterBundleStatusCallback() = 0; - /** - * @brief Dump the bundle informations with specific flags. - * @param flag Indicates the information contained in the dump result. - * @param bundleName Indicates the bundle name if needed. - * @param userId Indicates the user ID. - * @param result Indicates the dump information result. - * @return Returns true if the dump result is successfully obtained; returns false otherwise. - */ - virtual bool DumpInfos( - const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result) = 0; - /** - * @brief Checks whether a specified application is enabled. - * @param bundleName Indicates the bundle name of the application. - * @return Returns true if the application is enabled; returns false otherwise. - */ - virtual bool IsApplicationEnabled(const std::string &bundleName) = 0; - /** - * @brief Sets whether to enable a specified application. - * @param bundleName Indicates the bundle name of the application. - * @param isEnable Specifies whether to enable the application. - * The value true means to enable it, and the value false means to disable it. - * @return Returns true if the application is enabled; returns false otherwise. - */ - virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) = 0; - /** - * @brief Sets whether to enable a specified ability. - * @param abilityInfo Indicates information about the ability to check. - * @return Returns true if the ability is enabled; returns false otherwise. - */ - virtual bool IsAbilityEnabled(const AbilityInfo &abilityInfo) = 0; - /** - * @brief Sets whether to enable a specified ability. - * @param abilityInfo Indicates information about the ability. - * @param isEnabled Specifies whether to enable the ability. - * The value true means to enable it, and the value false means to disable it. - * @return Returns true if the ability is enabled; returns false otherwise. - */ - virtual bool SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) = 0; - /** - * @brief Obtains the icon of a specified ability. - * @param bundleName Indicates the bundle name. - * @param className Indicates the ability class name. - * @return Returns the icon resource string of the ability if exist; returns empty string otherwise. - */ - virtual std::string GetAbilityIcon(const std::string &bundleName, const std::string &className) = 0; - /** - * @brief Confirms with the permission management module to check whether a request prompt is required for granting - * a certain permission. - * @param bundleName Indicates the name of the bundle to check. - * @param permission Indicates the permission to check. - * @param userId Indicates the user id. - * @return Returns true if the current application does not have the permission and the user does not turn off - * further requests; returns false if the current application already has the permission, the permission is rejected - * by the system, or the permission is denied by the user and the user has turned off further requests. - */ - virtual bool CanRequestPermission( - const std::string &bundleName, const std::string &permissionName, const int userId) = 0; - /** - * @brief Requests a certain permission from user. - * @param bundleName Indicates the name of the bundle to request permission. - * @param permission Indicates the permission to request permission. - * @param userId Indicates the user id. - * @return Returns true if the permission request successfully; returns false otherwise. - */ - virtual bool RequestPermissionFromUser( - const std::string &bundleName, const std::string &permission, const int userId) = 0; - /** - * @brief Registers a callback for listening for permission changes of all UIDs. - * @param callback Indicates the callback method to register. - * @return Returns true if this function is successfully called; returns false otherwise. - */ - virtual bool RegisterAllPermissionsChanged(const sptr &callback) = 0; - /** - * @brief Registers a callback for listening for permission changes of specified UIDs. - * @param uids Indicates the list of UIDs whose permission changes will be monitored. - * @param callback Indicates the callback method to register. - * @return Returns true if this function is successfully called; returns false otherwise. - */ - virtual bool RegisterPermissionsChanged( - const std::vector &uids, const sptr &callback) = 0; - /** - * @brief Unregisters a specified callback for listening for permission changes. - * @param callback Indicates the callback method to register. - * @return Returns true if this function is successfully called; returns false otherwise. - */ - virtual bool UnregisterPermissionsChanged(const sptr &callback) = 0; - /** - * @brief Obtains the FormInfo objects provided by all applications on the device. - * @param formInfo list of FormInfo objects if obtained; returns an empty List if no FormInfo is available on the - * device. - * @return Returns true if this function is successfully called; returns false otherwise. - */ - virtual bool GetAllFormsInfo(std::vector &formInfos) = 0; - /** - * @brief Obtains the FormInfo objects provided by a specified application on the device. - * @param bundleName Indicates the bundle name of the application. - * @param formInfo list of FormInfo objects if obtained; returns an empty List if no FormInfo is available on the - * device. - * @return Returns true if this function is successfully called; returns false otherwise. - */ - virtual bool GetFormsInfoByApp(const std::string &bundleName, std::vector &formInfos) = 0; - /** - * @brief Obtains the FormInfo objects provided by a specified. - * @param formInfo list of FormInfo objects if obtained; returns an empty List if no FormInfo is available on the - * device. - * @param moduleName Indicates the module name of the application. - * @param bundleName Indicates the bundle name of the application. - * @return Returns true if this function is successfully called; returns false otherwise. - */ - virtual bool GetFormsInfoByModule( - const std::string &bundleName, const std::string &moduleName, std::vector &formInfos) = 0; - /** - * @brief Obtains the ShortcutInfo objects provided by a specified application on the device. - * @param bundleName Indicates the bundle name of the application. - * @param shortcutInfos List of ShortcutInfo objects if obtained. - * @return Returns true if this function is successfully called; returns false otherwise. - */ - virtual bool GetShortcutInfos(const std::string &bundleName, std::vector &shortcutInfos) = 0; - /** - * @brief Get module usage record list in descending order of lastLaunchTime. - * @param maxNum the return size of the records, must be in range of 1 to 1000. - * @param moduleUsageRecords List of ModuleUsageRecord objects if obtained. - * @return Returns true if this function is successfully called; returns false otherwise. - */ - virtual bool GetModuleUsageRecords(const int32_t number, std::vector &moduleUsageRecords) = 0; - /** - * @brief Obtains the interface used to install and uninstall bundles. - * @return Returns a pointer to IBundleInstaller class if exist; returns nullptr otherwise. - */ - virtual sptr GetBundleInstaller() = 0; - /** - * @brief Obtains the interface used to create or delete user. - * @return Returns a pointer to IBundleUserMgr class if exist; returns nullptr otherwise. - */ - virtual sptr GetBundleUserMgr() = 0; - /** - * @brief Notify a specified ability for ability. - * @param bundleName Indicates the bundle name of the ability to ability. - * @param abilityName Indicates the name of the ability to ability. - * @param launchTime Indicates the ability launchTime. - * @return Returns true if this function is successfully called; returns false otherwise. - */ - virtual bool NotifyAbilityLifeStatus( - const std::string &bundleName, const std::string &abilityName, const int64_t launchTime, const int uid = 0) = 0; - virtual bool GetBundleGidsByUid(const std::string &bundleName, const int &uid, std::vector &gids) = 0; - virtual bool QueryAbilityInfosByUri(const std::string &abilityUri, std::vector &abilityInfos) = 0; - virtual int CheckPermissionByUid( - const std::string &bundleName, const std::string &permission, const int userId) = 0; - virtual bool GetAllCommonEventInfo(const std::string &eventKey, std::vector &commonEventInfos) = 0; - virtual bool RemoveClonedBundle(const std::string &bundleName, const int32_t uid) = 0; - virtual bool BundleClone(const std::string &bundleName) = 0; - virtual bool CheckBundleNameInAllowList(const std::string &bundleName) = 0; - virtual bool GetDistributedBundleInfo( - const std::string &networkId, int32_t userId, const std::string &bundleName, - DistributedBundleInfo &distributedBundleInfo) = 0; - - enum class Message { - GET_APPLICATION_INFO, - GET_APPLICATION_INFOS, - GET_BUNDLE_INFO, - GET_BUNDLE_INFOS, - GET_UID_BY_BUNDLE_NAME, - GET_APPID_BY_BUNDLE_NAME, - GET_BUNDLE_NAME_FOR_UID, - GET_BUNDLES_FOR_UID, - GET_NAME_FOR_UID, - GET_BUNDLE_GIDS, - GET_APP_TYPE, - CHECK_IS_SYSTEM_APP_BY_UID, - GET_BUNDLE_INFOS_BY_METADATA, - QUERY_ABILITY_INFO, - QUERY_ABILITY_INFOS, - QUERY_ABILITY_INFO_BY_URI, - QUERY_KEEPALIVE_BUNDLE_INFOS, - GET_ABILITY_LABEL, - GET_BUNDLE_ARCHIVE_INFO, - GET_HAP_MODULE_INFO, - GET_LAUNCH_WANT_FOR_BUNDLE, - CHECK_PUBLICKEYS, - CHECK_PERMISSION, - GET_PERMISSION_DEF, - GET_ALL_PERMISSION_GROUP_DEFS, - GET_APPS_GRANTED_PERMISSIONS, - HAS_SYSTEM_CAPABILITY, - GET_SYSTEM_AVAILABLE_CAPABILITIES, - IS_SAFE_MODE, - CLEAN_BUNDLE_CACHE_FILES, - CLEAN_BUNDLE_DATA_FILES, - REGISTER_BUNDLE_STATUS_CALLBACK, - CLEAR_BUNDLE_STATUS_CALLBACK, - UNREGISTER_BUNDLE_STATUS_CALLBACK, - DUMP_INFOS, - IS_APPLICATION_ENABLED, - SET_APPLICATION_ENABLED, - IS_ABILITY_ENABLED, - SET_ABILITY_ENABLED, - GET_ABILITY_ICON, - CAN_REQUEST_PERMISSION, - REQUEST_PERMISSION_FROM_USER, - REGISTER_ALL_PERMISSIONS_CHANGED, - REGISTER_PERMISSIONS_CHANGED, - UNREGISTER_PERMISSIONS_CHANGED, - GET_ALL_FORMS_INFO, - GET_FORMS_INFO_BY_APP, - GET_FORMS_INFO_BY_MODULE, - GET_MODULE_USAGE_RECORD, - GET_SHORTCUT_INFO, - GET_ALL_COMMON_EVENT_INFO, - GET_BUNDLE_INSTALLER, - NOTIFY_ABILITY_LIFE_STATUS, - }; -}; -} // namespace AppExecFwk -} // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_BUNDLEMGR_BUNDLE_MGR_INTERFACE_H diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/mock_bundle_manager.h b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/mock_bundle_manager.h index e7b572911db278d4503fdbc1bb3641f614e464df..9f26de661771c5f56c1dd80f737cdceb9412281d 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/mock_bundle_manager.h +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/mock_bundle_manager.h @@ -180,8 +180,6 @@ public: MOCK_METHOD1(HasSystemCapability, bool(const std::string &capName)); MOCK_METHOD1(GetSystemAvailableCapabilities, bool(std::vector &systemCaps)); MOCK_METHOD0(IsSafeMode, bool()); - MOCK_METHOD2(CleanBundleCacheFiles, - bool(const std::string &bundleName, const sptr &cleanCacheCallback)); MOCK_METHOD2(CleanBundleDataFiles, bool(const std::string &bundleName, const int userId)); MOCK_METHOD3(RequestPermissionFromUser, bool(const std::string &bundleName, const std::string &permission, const int userId)); @@ -191,7 +189,6 @@ public: MOCK_METHOD4( DumpInfos, bool(const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result)); MOCK_METHOD1(IsApplicationEnabled, bool(const std::string &bundleName)); - MOCK_METHOD2(SetApplicationEnabled, bool(const std::string &bundleName, bool isEnable)); MOCK_METHOD0(GetBundleInstaller, sptr()); MOCK_METHOD0(GetBundleUserMgr, sptr()); MOCK_METHOD2(GetAppIdByBundleName, std::string(const std::string &bundleName, const int userId)); @@ -200,7 +197,6 @@ public: MOCK_METHOD2(QueryAbilityInfos, bool(const Want &want, std::vector &abilityInfos)); MOCK_METHOD2(QueryAbilityInfosForClone, bool(const Want &want, std::vector &abilityInfos)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &abilityInfo)); - MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &abilityInfo, bool isEnabled)); MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); MOCK_METHOD3( CanRequestPermission, bool(const std::string &bundleName, const std::string &permissionName, const int userId)); @@ -217,7 +213,6 @@ public: class BundleMgrStub : public IRemoteStub { public: - DECLARE_INTERFACE_DESCRIPTOR(u"IBundleMgr"); virtual int OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; }; @@ -228,6 +223,7 @@ public: ~BundleMgrService(); bool QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) override; + bool QueryAbilityInfo(const Want &want, int32_t flags, int32_t userId, AbilityInfo &abilityInfo) override; bool QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) override; bool GetApplicationInfo( const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override; @@ -264,14 +260,11 @@ public: MOCK_METHOD1(HasSystemCapability, bool(const std::string &capName)); MOCK_METHOD1(GetSystemAvailableCapabilities, bool(std::vector &systemCaps)); MOCK_METHOD0(IsSafeMode, bool()); - MOCK_METHOD2(CleanBundleCacheFiles, - bool(const std::string &bundleName, const sptr &cleanCacheCallback)); MOCK_METHOD2(CleanBundleDataFiles, bool(const std::string &bundleName, const int userId)); MOCK_METHOD3(RequestPermissionFromUser, bool(const std::string &bundleName, const std::string &permission, const int userId)); MOCK_METHOD1(RegisterBundleStatusCallback, bool(const sptr &bundleStatusCallback)); MOCK_METHOD1(ClearBundleStatusCallback, bool(const sptr &)); - MOCK_METHOD2(SetApplicationEnabled, bool(const std::string &bundleName, bool isEnable)); MOCK_METHOD0(GetBundleInstaller, sptr()); MOCK_METHOD0(GetBundleUserMgr, sptr()); MOCK_METHOD2(GetAppIdByBundleName, std::string(const std::string &bundleName, const int userId)); @@ -280,7 +273,6 @@ public: MOCK_METHOD2(QueryAbilityInfos, bool(const Want &want, std::vector &abilityInfos)); MOCK_METHOD2(QueryAbilityInfosForClone, bool(const Want &want, std::vector &abilityInfos)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &abilityInfo)); - MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &abilityInfo, bool isEnabled)); MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); MOCK_METHOD3( CanRequestPermission, bool(const std::string &bundleName, const std::string &permissionName, const int userId)); diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_mgr_client.cpp b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_mgr_client.cpp index c5ad1856b2816ffaa29c3f8718678662ad29d556..5166af58d6fa67c7fb401eb7a29be3667a6339b0 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_mgr_client.cpp +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/app_mgr_client.cpp @@ -35,7 +35,7 @@ AppMgrClient::~AppMgrClient() {} AppMgrResultCode AppMgrClient::LoadAbility(const sptr &token, const sptr &preToken, - const AbilityInfo &abilityInfo, const ApplicationInfo &appInfo) + const AbilityInfo &abilityInfo, const ApplicationInfo &appInfo, const AAFwk::Want &want) { return AppMgrResultCode::RESULT_OK; } diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp index 033011f7eb4c160aabb4fc3f87114847323326b3..5bf784570ecf1986c717b3ad53688eafaae023b9 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp @@ -43,7 +43,8 @@ bool AppScheduler::Init(const std::weak_ptr &callback) } int AppScheduler::LoadAbility(const sptr &token, const sptr &preToken, - const AppExecFwk::AbilityInfo &abilityInfo, const AppExecFwk::ApplicationInfo &applicationInfo) + const AppExecFwk::AbilityInfo &abilityInfo, const AppExecFwk::ApplicationInfo &applicationInfo, + const AAFwk::Want &want) { HILOG_INFO("Test AppScheduler::LoadAbility()"); if (applicationInfo.bundleName.find("com.ix.First.Test") != std::string::npos) { diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/src/bundlemgr/mock_bundle_manager.cpp b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/bundlemgr/mock_bundle_manager.cpp index 2b08969a3bfbdf7f61da222f16c35b759ead9c23..992e6eba03d6ff3b4f4231d44b4c95779d98512f 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/src/bundlemgr/mock_bundle_manager.cpp +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/bundlemgr/mock_bundle_manager.cpp @@ -23,7 +23,6 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::AAFwk; - int BundleMgrProxy::QueryWantAbility( const AAFwk::Want &__attribute__((unused)) want, std::vector &__attribute__((unused)) abilityInfos) { @@ -144,6 +143,11 @@ bool BundleMgrService::QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &ab return true; } +bool BundleMgrService::QueryAbilityInfo(const Want &want, int32_t flags, int32_t userId, AbilityInfo &abilityInfo) +{ + return QueryAbilityInfo(want, abilityInfo); +} + bool BundleMgrService::QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) { return false; @@ -155,13 +159,15 @@ bool BundleMgrService::GetApplicationInfo( if (appName.empty()) { return false; } + appInfo.name = "Helloworld"; + appInfo.bundleName = "com.ix.hiworld"; return true; } bool BundleMgrService::CheckIsSystemAppByUid(const int uid) { int maxSysUid {MAX_SYS_UID}; - int baseSysUid{ROOT_UID}; + int baseSysUid {ROOT_UID}; if (uid >= baseSysUid && uid <= maxSysUid) { return true; } @@ -208,6 +214,5 @@ bool BundleMgrService::NotifyAbilityLifeStatus( GTEST_LOG_(INFO) << "BundleMgrService::NotifyAbilityLifeStatus()"; return true; } - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/abilitymgr/test/mock/libs/sa_mgr/src/sa_mgr_client_mock.cpp b/services/abilitymgr/test/mock/libs/sa_mgr/src/sa_mgr_client_mock.cpp index dfa19fa27eeab660f95dd71363e293c622e19df4..02dc7dcb7caf2173ce3b6b96906a77e108f3086e 100644 --- a/services/abilitymgr/test/mock/libs/sa_mgr/src/sa_mgr_client_mock.cpp +++ b/services/abilitymgr/test/mock/libs/sa_mgr/src/sa_mgr_client_mock.cpp @@ -34,6 +34,16 @@ SaMgrClient::~SaMgrClient() sptr SaMgrClient::GetSystemAbility(const int32_t systemAbilityId) { HILOG_INFO("Test GetSystemAbility id : %{public}d", systemAbilityId); + if (servicesMap_[systemAbilityId] == nullptr) { + OHOS::sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + HILOG_ERROR("%s:fail to get Registry", __func__); + return nullptr; + } + OHOS::sptr object = systemAbilityManager->GetSystemAbility(systemAbilityId); + servicesMap_[systemAbilityId] = object; + } return servicesMap_[systemAbilityId]; } diff --git a/services/abilitymgr/test/unittest/phone/ability_connect_callback_proxy_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_connect_callback_proxy_test/BUILD.gn index 77e68597de69685eb5ea452d0016eabd3fc82fb3..e072fdb22882a0e7be9fae554c15860ae251aed0 100755 --- a/services/abilitymgr/test/unittest/phone/ability_connect_callback_proxy_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_connect_callback_proxy_test/BUILD.gn @@ -56,6 +56,7 @@ ohos_unittest("ability_connect_callback_proxy_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/ability_connect_callback_stub_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_connect_callback_stub_test/BUILD.gn index ca6e8b98f5fa7e65ef1b29cd5a92aba3c7ca3347..1c5f5ed5bd45581f1cdadc502424155909c54b51 100755 --- a/services/abilitymgr/test/unittest/phone/ability_connect_callback_stub_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_connect_callback_stub_test/BUILD.gn @@ -58,6 +58,7 @@ ohos_unittest("ability_connect_callback_stub_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/ability_connect_manage_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_connect_manage_test/BUILD.gn index 91f93684ba2dee7bcfa431b7ba06296b8e2408a5..aea69090441ba3d89cac9f70816324b1def85f28 100755 --- a/services/abilitymgr/test/unittest/phone/ability_connect_manage_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_connect_manage_test/BUILD.gn @@ -55,6 +55,7 @@ ohos_unittest("ability_connect_manage_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/ability_connect_manage_test/ability_connect_manage_test.cpp b/services/abilitymgr/test/unittest/phone/ability_connect_manage_test/ability_connect_manage_test.cpp index d8f8f7ca995e69c4c5c01ecf3a990893721cf152..befdd368c613c1c658e2f6b921109abe25a9035a 100644 --- a/services/abilitymgr/test/unittest/phone/ability_connect_manage_test/ability_connect_manage_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_connect_manage_test/ability_connect_manage_test.cpp @@ -272,8 +272,8 @@ HWTEST_F(AbilityConnectManageTest, AAFWK_Connect_Service_004, TestSize.Level1) auto result2 = ConnectManager()->TerminateAbility(service->GetToken()); WaitUntilTaskDone(handler); - EXPECT_EQ(OHOS::AAFwk::TERMINATE_SERVICE_IS_CONNECTED, result2); - EXPECT_NE(service->GetAbilityState(), TERMINATING); + EXPECT_EQ(0, result2); + EXPECT_EQ(service->GetAbilityState(), TERMINATING); } /* @@ -364,8 +364,8 @@ HWTEST_F(AbilityConnectManageTest, AAFWK_Connect_Service_007, TestSize.Level1) auto result2 = ConnectManager()->StopServiceAbility(abilityRequest_); WaitUntilTaskDone(handler); - EXPECT_EQ(OHOS::AAFwk::TERMINATE_SERVICE_IS_CONNECTED, result2); - EXPECT_NE(service->GetAbilityState(), TERMINATING); + EXPECT_EQ(0, result2); + EXPECT_EQ(service->GetAbilityState(), TERMINATING); } /* diff --git a/services/abilitymgr/test/unittest/phone/ability_dump_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_dump_test/BUILD.gn index ad2f1c7fb4fdae859303cf0efd5e95c122974e70..e49ed72def07d3663818348272bb1f40d1e758a1 100755 --- a/services/abilitymgr/test/unittest/phone/ability_dump_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_dump_test/BUILD.gn @@ -59,6 +59,7 @@ ohos_unittest("ability_dump_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/ability_dump_test/ability_dump_test.cpp b/services/abilitymgr/test/unittest/phone/ability_dump_test/ability_dump_test.cpp index 7acebdee358998dac4bf73e64c6d7982a61a87a8..0fa75e58c25e6bb5ceda9ee3ad2b327405878342 100644 --- a/services/abilitymgr/test/unittest/phone/ability_dump_test/ability_dump_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_dump_test/ability_dump_test.cpp @@ -60,7 +60,6 @@ static ElementName g_testAbility4("device", "com.ix.hiRadio", "RadioAbility"); static ElementName g_testAbility5("device", "com.ix.hiRadio", "RadioTopAbility"); static ElementName g_launcherAbility("device", "com.ix.hiWord", "LauncherAbility"); static std::shared_ptr g_abilityMs = nullptr; -static std::shared_ptr g_appTestService = nullptr; } // namespace bool IsTestAbility1Exist(const std::string &state) @@ -126,23 +125,30 @@ void AbilityDumpTest::OnStartAms() g_abilityMs->handler_ = std::make_shared(g_abilityMs->eventLoop_, g_abilityMs); g_abilityMs->connectManager_ = std::make_shared(); + g_abilityMs->connectManagers_.emplace(0, g_abilityMs->connectManager_); EXPECT_TRUE(g_abilityMs->handler_); EXPECT_TRUE(g_abilityMs->connectManager_); g_abilityMs->connectManager_->SetEventHandler(g_abilityMs->handler_); g_abilityMs->dataAbilityManager_ = std::make_shared(); + g_abilityMs->dataAbilityManagers_.emplace(0, g_abilityMs->dataAbilityManager_); EXPECT_TRUE(g_abilityMs->dataAbilityManager_); g_abilityMs->amsConfigResolver_ = std::make_shared(); EXPECT_TRUE(g_abilityMs->amsConfigResolver_); g_abilityMs->amsConfigResolver_->Parse(); + g_abilityMs->currentMissionListManager_ = std::make_shared(0); + g_abilityMs->currentMissionListManager_->Init(); + g_abilityMs->pendingWantManager_ = std::make_shared(); EXPECT_TRUE(g_abilityMs->pendingWantManager_); int userId = g_abilityMs->GetUserId(); g_abilityMs->SetStackManager(userId, true); + EXPECT_TRUE(g_abilityMs->GetStackManager()); + g_abilityMs->stackManagers_.emplace(0, g_abilityMs->GetStackManager()); g_abilityMs->systemAppManager_ = std::make_shared(userId); EXPECT_TRUE(g_abilityMs->systemAppManager_); @@ -167,20 +173,15 @@ void AbilityDumpTest::TearDownTestCase() void AbilityDumpTest::SetUp() { - g_abilityMs = OHOS::DelayedSingleton::GetInstance(); - g_appTestService = OHOS::DelayedSingleton::GetInstance(); OnStartAms(); WaitUntilTaskFinished(); - g_appTestService->Start(); - StartAbilityes(); } void AbilityDumpTest::TearDown() { g_abilityMs->OnStop(); - OHOS::DelayedSingleton::DestroyInstance(); } void AbilityDumpTest::StartAbilityes() @@ -189,6 +190,7 @@ void AbilityDumpTest::StartAbilityes() auto currentTopAbilityRecord = g_abilityMs->currentStackManager_->GetCurrentTopAbility(); if (currentTopAbilityRecord) { currentTopAbilityRecord->SetAbilityState(AbilityState::ACTIVE); + return; } startAbility6(); @@ -456,8 +458,9 @@ HWTEST_F(AbilityDumpTest, Ability_Dump_009, TestSize.Level2) std::string args("--mission 0"); std::vector result; g_abilityMs->DumpState(args, result); - EXPECT_EQ(result.end(), std::find_if(result.begin(), result.end(), IsTestAbility2Exist)); - EXPECT_EQ(result.end(), std::find_if(result.begin(), result.end(), IsTestAbility3Exist)); + + EXPECT_NE(result.end(), std::find_if(result.begin(), result.end(), IsTestAbility2Exist)); + EXPECT_NE(result.end(), std::find_if(result.begin(), result.end(), IsTestAbility3Exist)); EXPECT_EQ(result.end(), std::find_if(result.begin(), result.end(), IsTestAbility4Exist)); GTEST_LOG_(INFO) << "Ability_Dump_009 end"; @@ -480,9 +483,9 @@ HWTEST_F(AbilityDumpTest, Ability_Dump_010, TestSize.Level2) EXPECT_EQ(result.end(), std::find_if(result.begin(), result.end(), IsLaunchAbilityExist)); EXPECT_EQ(result.end(), std::find_if(result.begin(), result.end(), IsTestAbility1Exist)); - EXPECT_EQ(result.end(), std::find_if(result.begin(), result.end(), IsTestAbility2Exist)); - EXPECT_EQ(result.end(), std::find_if(result.begin(), result.end(), IsTestAbility3Exist)); - EXPECT_EQ(result.end(), std::find_if(result.begin(), result.end(), IsTestAbility4Exist)); + EXPECT_NE(result.end(), std::find_if(result.begin(), result.end(), IsTestAbility2Exist)); + EXPECT_NE(result.end(), std::find_if(result.begin(), result.end(), IsTestAbility3Exist)); + EXPECT_NE(result.end(), std::find_if(result.begin(), result.end(), IsTestAbility4Exist)); GTEST_LOG_(INFO) << "Ability_Dump_010 end"; } diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/BUILD.gn index 1e1f40c6691ba2d18f67d31000e28625a347553b..f52e46e79d2898dd08f909dd2abbd43e4e402b80 100755 --- a/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/BUILD.gn @@ -58,6 +58,7 @@ ohos_unittest("ability_manager_proxy_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", 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 bf6c9c53302e39e565fa0e7079fd49594664db66..b29bb10bcec4e65dd9c2911323cd5deb58c8df86 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 @@ -101,7 +101,11 @@ public: { return 0; } - + virtual int CloseAbility(const sptr &token, int resultCode = DEFAULT_INVAL_VALUE, + const Want *resultWant = nullptr) override + { + return 0; + } virtual int MinimizeAbility(const sptr &token, bool fromUser) override { return 0; @@ -371,9 +375,9 @@ public: return true; } - virtual bool SendANRProcessID(int pid) override + virtual int SendANRProcessID(int pid) override { - return true; + return 0; } MOCK_METHOD2(TerminateAbilityByCaller, int(const sptr &callerToken, int requestCode)); @@ -393,7 +397,7 @@ public: MOCK_METHOD2(GetPendingRequestWant, int(const sptr &target, std::shared_ptr &want)); MOCK_METHOD1(GetSystemMemoryAttr, void(AppExecFwk::SystemMemoryAttr &memoryInfo)); MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); - MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result)); + MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, int32_t result)); MOCK_METHOD5(ContinueMission, int(const std::string &srcDeviceId, const std::string &dstDeviceId, int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams)); MOCK_METHOD2(ContinueAbility, int(const std::string &deviceId, int32_t missionId)); @@ -409,6 +413,7 @@ public: MOCK_METHOD1(CleanMission, int(int32_t missionId)); MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); + MOCK_METHOD2(MoveMissionToFront, int(int32_t missionId, const StartOptions &startOptions)); MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD2(GetWantSenderInfo, int(const sptr &target, std::shared_ptr &info)); MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector &info)); diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_service_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_manager_service_test/BUILD.gn index 4b9d017fdf97b555276036cd131918471e420295..e57df554d35e3510d750652a816a293ed2bc125b 100755 --- a/services/abilitymgr/test/unittest/phone/ability_manager_service_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_manager_service_test/BUILD.gn @@ -58,6 +58,7 @@ ohos_unittest("ability_manager_service_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "dsoftbus_standard:softbus_client", "hiviewdfx_hilog_native:libhilog", diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_service_test/ability_manager_service_test.cpp b/services/abilitymgr/test/unittest/phone/ability_manager_service_test/ability_manager_service_test.cpp index cbf4ca0753cd84a8c30b579a5f5b93ab36c5acb8..6a0eb76d93ed42e5292c9976defc853b90372850 100644 --- a/services/abilitymgr/test/unittest/phone/ability_manager_service_test/ability_manager_service_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_manager_service_test/ability_manager_service_test.cpp @@ -97,9 +97,9 @@ public: static constexpr int TEST_WAIT_TIME = 100000; public: - std::shared_ptr abilityMs_ {nullptr}; - AbilityRequest abilityRequest_ {}; + AbilityRequest abilityRequest_; std::shared_ptr abilityRecord_ {nullptr}; + std::shared_ptr abilityMs_ = DelayedSingleton::GetInstance(); }; int AbilityManagerServiceTest::StartAbility(const Want &want) @@ -128,12 +128,12 @@ void AbilityManagerServiceTest::OnStartAms() abilityMs_->handler_ = std::make_shared(abilityMs_->eventLoop_, abilityMs_); abilityMs_->connectManager_ = std::make_shared(); + abilityMs_->connectManagers_.emplace(0, abilityMs_->connectManager_); EXPECT_TRUE(abilityMs_->handler_); EXPECT_TRUE(abilityMs_->connectManager_); - abilityMs_->connectManager_->SetEventHandler(abilityMs_->handler_); - abilityMs_->dataAbilityManager_ = std::make_shared(); + abilityMs_->dataAbilityManagers_.emplace(0, abilityMs_->dataAbilityManager_); EXPECT_TRUE(abilityMs_->dataAbilityManager_); abilityMs_->amsConfigResolver_ = std::make_shared(); @@ -143,13 +143,15 @@ void AbilityManagerServiceTest::OnStartAms() abilityMs_->pendingWantManager_ = std::make_shared(); EXPECT_TRUE(abilityMs_->pendingWantManager_); + abilityMs_->currentMissionListManager_ = std::make_shared(0); + abilityMs_->currentMissionListManager_->Init(); int userId = abilityMs_->GetUserId(); abilityMs_->SetStackManager(userId, true); + EXPECT_TRUE(abilityMs_->GetStackManager()); + abilityMs_->stackManagers_.emplace(0, abilityMs_->GetStackManager()); abilityMs_->systemAppManager_ = std::make_shared(userId); EXPECT_TRUE(abilityMs_->systemAppManager_); - abilityMs_->eventLoop_->Run(); - return; } @@ -158,9 +160,7 @@ void AbilityManagerServiceTest::OnStartAms() void AbilityManagerServiceTest::OnStopAms() { - abilityMs_->eventLoop_.reset(); - abilityMs_->handler_.reset(); - abilityMs_->state_ = ServiceRunningState::STATE_NOT_START; + abilityMs_->OnStop(); } void AbilityManagerServiceTest::SetUpTestCase() @@ -176,7 +176,6 @@ void AbilityManagerServiceTest::TearDownTestCase() void AbilityManagerServiceTest::SetUp() { - abilityMs_ = OHOS::DelayedSingleton::GetInstance(); OnStartAms(); WaitUntilTaskFinished(); if (abilityRecord_ == nullptr) { @@ -185,13 +184,11 @@ void AbilityManagerServiceTest::SetUp() abilityRequest_.abilityInfo.type = AbilityType::DATA; abilityRecord_ = AbilityRecord::CreateAbilityRecord(abilityRequest_); } - } void AbilityManagerServiceTest::TearDown() { OnStopAms(); - OHOS::DelayedSingleton::DestroyInstance(); } /* @@ -1589,9 +1586,8 @@ HWTEST_F(AbilityManagerServiceTest, startAbility_004, TestSize.Level1) HWTEST_F(AbilityManagerServiceTest, startContinuation_001, TestSize.Level1) { Want want; - ElementName element("device", "com.ix.musicService", "MusicService"); + ElementName element("", "com.ix.musicService", "MusicService"); want.SetElement(element); - sptr abilityToken = new (std::nothrow) MockAbilityToken(); auto result = abilityMs_->StartContinuation(want, abilityToken, 0); EXPECT_EQ(OHOS::ERR_INVALID_VALUE, result); @@ -1611,7 +1607,6 @@ HWTEST_F(AbilityManagerServiceTest, startContinuation_002, TestSize.Level1) EXPECT_EQ(true, getLocalDeviceId); ElementName element(localDeviceId, "com.ix.hiMusic", "MusicAbility"); want.SetElement(element); - sptr abilityToken = new (std::nothrow) MockAbilityToken(); auto result = abilityMs_->StartContinuation(want, abilityToken, 0); EXPECT_NE(OHOS::ERR_OK, result); @@ -1675,7 +1670,7 @@ HWTEST_F(AbilityManagerServiceTest, NotifyContinuationResult_001, TestSize.Level int32_t missionId = 0; int32_t isSuccess = 0; auto result = abilityMs_->NotifyContinuationResult(missionId, isSuccess); - EXPECT_EQ(OHOS::ERR_INVALID_VALUE, result); + EXPECT_EQ(OHOS::ERR_OK, result); } /** @@ -1963,10 +1958,12 @@ HWTEST_F(AbilityManagerServiceTest, systemDialog_002, TestSize.Level1) Want want; ElementName elementdialog("device", AbilityConfig::SYSTEM_UI_BUNDLE_NAME, AbilityConfig::SYSTEM_DIALOG_NAME); want.SetElement(elementdialog); + EXPECT_TRUE(abilityMs_->GetStackManager()); auto result = StartAbility(want); EXPECT_EQ(OHOS::ERR_OK, result); auto stackManager = abilityMs_->GetStackManager(); auto dialogAbility = stackManager->GetCurrentTopAbility(); + EXPECT_TRUE(dialogAbility); auto dialogtoken = dialogAbility->GetToken(); EXPECT_TRUE(dialogAbility->GetAbilityInfo().bundleName == AbilityConfig::SYSTEM_UI_BUNDLE_NAME); diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/BUILD.gn index f73cc0fb17c55031a63ebfc517c78e77a50f01ba..92fbd890229182c0ffb6b78be80f42da8399f54e 100755 --- a/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/BUILD.gn @@ -58,6 +58,7 @@ ohos_unittest("ability_manager_stub_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/ability_manager_stub_impl_mock.h b/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/ability_manager_stub_impl_mock.h index 344172f54992adb057a04bf43afd08fe0e37b215..970bd387adb7f52b7f318807220c933355f237ef 100644 --- a/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/ability_manager_stub_impl_mock.h +++ b/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/ability_manager_stub_impl_mock.h @@ -49,7 +49,7 @@ public: MOCK_METHOD2(GetWantSenderInfo, int(const sptr &target, std::shared_ptr &info)); MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); - MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result)); + MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, int32_t result)); MOCK_METHOD5(ContinueMission, int(const std::string &srcDeviceId, const std::string &dstDeviceId, int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams)); MOCK_METHOD2(ContinueAbility, int(const std::string &deviceId, int32_t missionId)); @@ -101,7 +101,11 @@ public: { return 0; } - + virtual int CloseAbility(const sptr &token, int resultCode = DEFAULT_INVAL_VALUE, + const Want *resultWant = nullptr) override + { + return 0; + } virtual int MinimizeAbility(const sptr &token, bool fromUser) override { return 0; @@ -357,6 +361,10 @@ public: { return 0; } + virtual int MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) override + { + return 0; + } virtual int GetMissionInfos(const std::string& deviceId, int32_t numMax, std::vector &missionInfos) override { @@ -418,9 +426,9 @@ public: { return true; } - virtual bool SendANRProcessID(int pid) override + virtual int SendANRProcessID(int pid) override { - return true; + return 0; } virtual int StartUserTest(const Want &want, const sptr &observer) override diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_test/ability_manager_stub_mock.h b/services/abilitymgr/test/unittest/phone/ability_manager_test/ability_manager_stub_mock.h index c7af16c31827a49985c07079bb982642dffd58b2..86e8505154fc367c2106b4b06fdcdc5da46e7504 100644 --- a/services/abilitymgr/test/unittest/phone/ability_manager_test/ability_manager_stub_mock.h +++ b/services/abilitymgr/test/unittest/phone/ability_manager_test/ability_manager_stub_mock.h @@ -35,6 +35,11 @@ public: MOCK_METHOD4(SendRequest, int(uint32_t, MessageParcel &, MessageParcel &, MessageOption &)); MOCK_METHOD2(StartAbility, int(const Want &, int)); MOCK_METHOD3(TerminateAbility, int(const sptr &, int, const Want *)); + virtual int CloseAbility(const sptr &token, int resultCode = DEFAULT_INVAL_VALUE, + const Want *resultWant = nullptr) override + { + return 0; + } virtual int MinimizeAbility(const sptr &token, bool fromUser = false) override { return 0; @@ -124,7 +129,7 @@ public: return 0; } MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); - MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result)); + MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, int32_t result)); MOCK_METHOD5(ContinueMission, int(const std::string &srcDeviceId, const std::string &dstDeviceId, int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams)); MOCK_METHOD2(ContinueAbility, int(const std::string &deviceId, int32_t missionId)); diff --git a/services/abilitymgr/test/unittest/phone/ability_record_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_record_test/BUILD.gn index e0cb1722d0ad8240224fc38e9d0a465fda78e97d..0e35f783aa0e1440e0435a6be303c0de7ae0c103 100755 --- a/services/abilitymgr/test/unittest/phone/ability_record_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_record_test/BUILD.gn @@ -55,6 +55,7 @@ ohos_unittest("ability_record_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/ability_record_test/ability_record_test.cpp b/services/abilitymgr/test/unittest/phone/ability_record_test/ability_record_test.cpp index 71202da4478be0de3b0a80295a10f2934a1942c1..547699defa8d589673bcb37dcfcebd2abb410b0f 100644 --- a/services/abilitymgr/test/unittest/phone/ability_record_test/ability_record_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_record_test/ability_record_test.cpp @@ -53,7 +53,6 @@ void AbilityRecordTest::SetUpTestCase(void) void AbilityRecordTest::TearDownTestCase(void) { OHOS::DelayedSingleton::GetInstance()->OnStop(); - OHOS::DelayedSingleton::DestroyInstance(); } void AbilityRecordTest::SetUp(void) diff --git a/services/abilitymgr/test/unittest/phone/ability_scheduler_proxy_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_scheduler_proxy_test/BUILD.gn index 5eceb53bb068c0d5a70b3c961487be2e6b8de96f..02d680eff9af1b73c0a0bd1faa57d6fd76ef75ec 100755 --- a/services/abilitymgr/test/unittest/phone/ability_scheduler_proxy_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_scheduler_proxy_test/BUILD.gn @@ -58,6 +58,7 @@ ohos_unittest("ability_scheduler_proxy_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/BUILD.gn index 758834f27cbab224cafb260e2d1e7e134201ad67..99516fcda778cbf29034ffb9957bfa86dfdad416 100755 --- a/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/BUILD.gn @@ -55,6 +55,7 @@ ohos_unittest("ability_scheduler_stub_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_schedule_stub_mock.h b/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_schedule_stub_mock.h index a1a4ef18a9813e5b80d0881985e723586171e0d7..ce061009455fb9542e134f5bd19a36c0883b36d4 100755 --- a/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_schedule_stub_mock.h +++ b/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_schedule_stub_mock.h @@ -129,11 +129,11 @@ public: { return std::vector>(); } - virtual void NotifyContinuationResult(const int32_t result) override + virtual void NotifyContinuationResult(int32_t result) override {} virtual void ContinueAbility(const std::string& deviceId) override {} - virtual void DumpAbilityInfo(std::vector &info) override + virtual void DumpAbilityInfo(const std::vector ¶ms, std::vector &info) override {} virtual sptr CallRequest() override { @@ -143,4 +143,4 @@ public: } // namespace AAFwk } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/services/abilitymgr/test/unittest/phone/ability_service_start_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_service_start_test/BUILD.gn index a54263041ee26362a06d70f4dabe83ae5c9a469b..3448571be2f85f77bc4c17f764b9397564cde948 100755 --- a/services/abilitymgr/test/unittest/phone/ability_service_start_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_service_start_test/BUILD.gn @@ -57,6 +57,7 @@ ohos_unittest("ability_service_start_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/ability_service_start_test/ability_service_start_test.cpp b/services/abilitymgr/test/unittest/phone/ability_service_start_test/ability_service_start_test.cpp index a4bb852ab213fba61ca28d887bb21527fa1995e1..5164dce77f5c58c0e154a7a058f7776a09236bec 100644 --- a/services/abilitymgr/test/unittest/phone/ability_service_start_test/ability_service_start_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_service_start_test/ability_service_start_test.cpp @@ -49,14 +49,16 @@ void AbilityServiceStartTest::TearDownTestCase() OHOS::DelayedSingleton::DestroyInstance(); } -void AbilityServiceStartTest::TearDown() -{} - void AbilityServiceStartTest::SetUp() { aams_ = OHOS::DelayedSingleton::GetInstance(); } +void AbilityServiceStartTest::TearDown() +{ + aams_->OnStop(); +} + /* * Feature: AbilityManagerService * Function: Service diff --git a/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/BUILD.gn index c8cc259ba14c79ee6e8f0271fa3dbdc9e8fff7c0..8237b90354290a607cab820d912219ea9198f9b6 100755 --- a/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/BUILD.gn @@ -60,6 +60,7 @@ ohos_unittest("ability_stack_manager_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/ability_stack_manager_test.cpp b/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/ability_stack_manager_test.cpp index e22a8cce45b35fa0cd90c1f87ad2364cdd988aef..d4a48a6cb73637d3c7e62a4bedf34a960710ee78 100644 --- a/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/ability_stack_manager_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/ability_stack_manager_test.cpp @@ -137,7 +137,6 @@ void AbilityStackManagerTest::TearDown() { stackManager_.reset(); abilityMs_->OnStop(); - OHOS::DelayedSingleton::DestroyInstance(); } void AbilityStackManagerTest::init() diff --git a/services/abilitymgr/test/unittest/phone/ability_token_proxy_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_token_proxy_test/BUILD.gn index 061ce0d99e71aa45b5c006b40593a27b5f435658..d494af6662b67cb84237ad856ab9cc808f9f1558 100755 --- a/services/abilitymgr/test/unittest/phone/ability_token_proxy_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_token_proxy_test/BUILD.gn @@ -55,6 +55,7 @@ ohos_unittest("ability_token_proxy_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/ability_token_stub_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_token_stub_test/BUILD.gn index d53822f375ea259f7a92c6735eae526973eac5cd..0938daba97e7b5b651fe5786369db18bc8a063aa 100755 --- a/services/abilitymgr/test/unittest/phone/ability_token_stub_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_token_stub_test/BUILD.gn @@ -55,6 +55,7 @@ ohos_unittest("ability_token_stub_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/ability_with_applications_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_with_applications_test/BUILD.gn index 73bb5e52da816c12a7949a30902c32d5aa0c4368..960e6bc85b4df2050ec76f0def1814005a61cfa7 100755 --- a/services/abilitymgr/test/unittest/phone/ability_with_applications_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_with_applications_test/BUILD.gn @@ -59,6 +59,7 @@ ohos_unittest("ability_with_applications_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/ability_with_applications_test/ability_with_applications_test.cpp b/services/abilitymgr/test/unittest/phone/ability_with_applications_test/ability_with_applications_test.cpp index 9a2aeefe2427af3bb5552b58823c78e13c411815..8f43d1050790e6a553fcd47f9ac62192e958308e 100644 --- a/services/abilitymgr/test/unittest/phone/ability_with_applications_test/ability_with_applications_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_with_applications_test/ability_with_applications_test.cpp @@ -78,7 +78,6 @@ void AbilityWithApplicationsTest::SetUp() void AbilityWithApplicationsTest::TearDown() { abilityMs_->OnStop(); - OHOS::DelayedSingleton::DestroyInstance(); } void AbilityWithApplicationsTest::OnStartabilityAms() @@ -95,12 +94,14 @@ void AbilityWithApplicationsTest::OnStartabilityAms() abilityMs_->handler_ = std::make_shared(abilityMs_->eventLoop_, abilityMs_); abilityMs_->connectManager_ = std::make_shared(); + abilityMs_->connectManagers_.emplace(0, abilityMs_->connectManager_); EXPECT_TRUE(abilityMs_->handler_); EXPECT_TRUE(abilityMs_->connectManager_); abilityMs_->connectManager_->SetEventHandler(abilityMs_->handler_); abilityMs_->dataAbilityManager_ = std::make_shared(); + abilityMs_->dataAbilityManagers_.emplace(0, abilityMs_->dataAbilityManager_); EXPECT_TRUE(abilityMs_->dataAbilityManager_); abilityMs_->amsConfigResolver_ = std::make_shared(); @@ -110,6 +111,9 @@ void AbilityWithApplicationsTest::OnStartabilityAms() abilityMs_->pendingWantManager_ = std::make_shared(); EXPECT_TRUE(abilityMs_->pendingWantManager_); + abilityMs_->currentMissionListManager_ = std::make_shared(0); + abilityMs_->currentMissionListManager_->Init(); + int userId = abilityMs_->GetUserId(); abilityMs_->SetStackManager(userId, true); abilityMs_->systemAppManager_ = std::make_shared(userId); @@ -275,7 +279,7 @@ HWTEST_F(AbilityWithApplicationsTest, Teminate_Ability_With_Applications_001, Te EXPECT_TRUE(curMission != nullptr); if (topAbility) { - EXPECT_EQ("com.ix.test1", topAbility->GetAbilityInfo().applicationName); + EXPECT_EQ("com.ix.test2", topAbility->GetAbilityInfo().applicationName); EXPECT_NE(BACKGROUND, topAbility->GetAbilityState()); } @@ -296,7 +300,7 @@ HWTEST_F(AbilityWithApplicationsTest, Teminate_Ability_With_Applications_001, Te } if (topAbility) { - EXPECT_EQ("com.ohos.launcher", topAbility->GetAbilityInfo().applicationName); + EXPECT_EQ("com.ix.test1", topAbility->GetAbilityInfo().applicationName); EXPECT_NE(ACTIVE, topAbility->GetAbilityState()); } diff --git a/services/abilitymgr/test/unittest/phone/abilityms_appms_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/abilityms_appms_test/BUILD.gn index b4a5ce8c0868b3df0cc8e9a38e746f724d666218..404a2f9920b1b783acebfe05bb67f42cfc03b7d0 100755 --- a/services/abilitymgr/test/unittest/phone/abilityms_appms_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/abilityms_appms_test/BUILD.gn @@ -59,6 +59,7 @@ ohos_unittest("abilityms_appms_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/abilityms_appms_test/abilityms_appms_test.cpp b/services/abilitymgr/test/unittest/phone/abilityms_appms_test/abilityms_appms_test.cpp index 98adb3ee6cd145301c7010e5d71a46afb592f50c..a529e853178f331ecd1a0a2491bc7356270dafe6 100644 --- a/services/abilitymgr/test/unittest/phone/abilityms_appms_test/abilityms_appms_test.cpp +++ b/services/abilitymgr/test/unittest/phone/abilityms_appms_test/abilityms_appms_test.cpp @@ -82,12 +82,11 @@ public: void OnStartabilityAms(); std::shared_ptr GetAbilityRecord() const; void ResetAbilityRecord(); - void startAbility(); + void StartAbility(); public: std::shared_ptr abilityRecord_ {nullptr}; - std::shared_ptr callback_ {nullptr}; - std::shared_ptr abilityMs_ {nullptr}; + std::shared_ptr abilityMs_ = DelayedSingleton::GetInstance(); }; void AbilityMsAppmsTest::OnStartabilityAms() @@ -104,6 +103,8 @@ void AbilityMsAppmsTest::OnStartabilityAms() abilityMs_->handler_ = std::make_shared(abilityMs_->eventLoop_, abilityMs_); abilityMs_->connectManager_ = std::make_shared(); + abilityMs_->dataAbilityManager_ = std::make_shared(); + abilityMs_->dataAbilityManagers_.emplace(0, abilityMs_->dataAbilityManager_); EXPECT_TRUE(abilityMs_->handler_); EXPECT_TRUE(abilityMs_->connectManager_); @@ -133,29 +134,28 @@ void AbilityMsAppmsTest::OnStartabilityAms() } void AbilityMsAppmsTest::SetUpTestCase(void) -{} -void AbilityMsAppmsTest::TearDownTestCase(void) -{} - -void AbilityMsAppmsTest::SetUp(void) { - sptr bundleObject = new BundleMgrService(); DelayedSingleton::GetInstance()->RegisterSystemAbility( - OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject); - DelayedSingleton::GetInstance(); + OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, new BundleMgrService()); + DelayedSingleton::GetInstance()->Init(std::make_shared()); +} - callback_ = std::make_shared(); +void AbilityMsAppmsTest::TearDownTestCase(void) +{ + OHOS::DelayedSingleton::DestroyInstance(); + DelayedSingleton::DestroyInstance(); +} - DelayedSingleton::GetInstance()->Init(callback_); - abilityMs_ = DelayedSingleton::GetInstance(); +void AbilityMsAppmsTest::SetUp(void) +{ OnStartabilityAms(); - startAbility(); + StartAbility(); GTEST_LOG_(INFO) << "SetUp"; } void AbilityMsAppmsTest::TearDown(void) { - DelayedSingleton::DestroyInstance(); + abilityMs_->OnStop(); GTEST_LOG_(INFO) << "TearDown"; } @@ -180,7 +180,7 @@ void AbilityMsAppmsTest::ResetAbilityRecord() abilityRecord_->Init(); } -void AbilityMsAppmsTest::startAbility() +void AbilityMsAppmsTest::StartAbility() { Want want; AbilityInfo abilityInfo; @@ -276,11 +276,13 @@ HWTEST_F(AbilityMsAppmsTest, AaFwk_AbilityMS_AppMS_004, TestSize.Level1) sptr scheduler = new AbilityScheduler(); std::shared_ptr abilityRecord = nullptr; sptr token = nullptr; - auto checkStateFun = [&scheduler, &token, &abilityRecord]() { auto stackManager = DelayedSingleton::GetInstance()->GetStackManager(); + EXPECT_TRUE(stackManager); abilityRecord = stackManager->GetCurrentTopAbility(); + EXPECT_TRUE(abilityRecord); token = abilityRecord->GetToken(); + EXPECT_TRUE(token); DelayedSingleton::GetInstance()->AttachAbilityThread(scheduler, token); }; @@ -315,7 +317,9 @@ HWTEST_F(AbilityMsAppmsTest, AaFwk_AbilityMS_AppMS_005, TestSize.Level1) auto checkSourceActivtingState = [&stackManager, &sourceAbilityRecord, &scheduler, &sourcetoken]() { stackManager = DelayedSingleton::GetInstance()->GetStackManager(); sourceAbilityRecord = stackManager->GetCurrentTopAbility(); + EXPECT_TRUE(sourceAbilityRecord); sourcetoken = sourceAbilityRecord->GetToken(); + EXPECT_TRUE(sourcetoken); DelayedSingleton::GetInstance()->AttachAbilityThread(scheduler, sourcetoken); auto sourceAbilityInfo = sourceAbilityRecord->GetAbilityInfo(); EXPECT_EQ(sourceAbilityInfo.bundleName, "com.ix.hiworld"); diff --git a/services/abilitymgr/test/unittest/phone/app_scheduler_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/app_scheduler_test/BUILD.gn index da1442f77bd8bbfd0e8f4eb12a806a72a9d51404..1c807996239a4ab9ea009de004544102bf5b69a7 100755 --- a/services/abilitymgr/test/unittest/phone/app_scheduler_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/app_scheduler_test/BUILD.gn @@ -57,6 +57,7 @@ ohos_unittest("app_scheduler_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "bytrace_standard:bytrace_core", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", diff --git a/services/abilitymgr/test/unittest/phone/app_scheduler_test/app_scheduler_test.cpp b/services/abilitymgr/test/unittest/phone/app_scheduler_test/app_scheduler_test.cpp index 1dcc730a1d08da2f582af98aa30a05e3e95716f3..e3f332f4efbe860afb3b8b4fcd10bd803fc07a87 100644 --- a/services/abilitymgr/test/unittest/phone/app_scheduler_test/app_scheduler_test.cpp +++ b/services/abilitymgr/test/unittest/phone/app_scheduler_test/app_scheduler_test.cpp @@ -128,7 +128,7 @@ HWTEST_F(AppSchedulerTest, AppScheduler_oprator_003, TestSize.Level1) EXPECT_EQ((int)ERR_OK, DelayedSingleton::GetInstance()->LoadAbility( - token, pretoken, record->GetAbilityInfo(), record->GetApplicationInfo())); + token, pretoken, record->GetAbilityInfo(), record->GetApplicationInfo(), record->GetWant())); } /* @@ -159,7 +159,7 @@ HWTEST_F(AppSchedulerTest, AppScheduler_oprator_004, TestSize.Level1) DelayedSingleton::GetInstance()->appMgrClient_ = nullptr; EXPECT_NE((int)ERR_OK, DelayedSingleton::GetInstance()->LoadAbility( - token, pretoken, record->GetAbilityInfo(), record->GetApplicationInfo())); + token, pretoken, record->GetAbilityInfo(), record->GetApplicationInfo(), record->GetWant())); } /* diff --git a/services/abilitymgr/test/unittest/phone/configuration_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/configuration_test/BUILD.gn index 021e20e46aff767077954385a431f21fcf39c31f..5550f0a415d89bf70c83c65bbb28121e98e625a5 100755 --- a/services/abilitymgr/test/unittest/phone/configuration_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/configuration_test/BUILD.gn @@ -59,6 +59,7 @@ ohos_unittest("configuration_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/connection_record_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/connection_record_test/BUILD.gn index 66275bc45a17ad141e37aa025ddd08977ef8f6c0..5d93f1f55a26d7bb71ffdeab81ebb4c2ff9eac8a 100755 --- a/services/abilitymgr/test/unittest/phone/connection_record_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/connection_record_test/BUILD.gn @@ -56,6 +56,7 @@ ohos_unittest("connection_record_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/data_ability_manager_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/data_ability_manager_test/BUILD.gn index b8da729debb40bbb530d652a63cc5972263ffe50..2d2f88add92261cb5b6158783ca5110445448bb7 100755 --- a/services/abilitymgr/test/unittest/phone/data_ability_manager_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/data_ability_manager_test/BUILD.gn @@ -65,6 +65,7 @@ ohos_unittest("data_ability_manager_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "bytrace_standard:bytrace_core", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", diff --git a/services/abilitymgr/test/unittest/phone/data_ability_record_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/data_ability_record_test/BUILD.gn index 77926dfa97633f49618992d4161c7da0facaa328..e9a738877fb7ffc681598a911c1a71efa81d252c 100755 --- a/services/abilitymgr/test/unittest/phone/data_ability_record_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/data_ability_record_test/BUILD.gn @@ -63,6 +63,7 @@ ohos_unittest("data_ability_record_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/info_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/info_test/BUILD.gn index 2a7115df103db6659c53351d6b0c1cf2bedece5d..41e10660eecb94b4ed1aba2aab8d7ac01c33a374 100755 --- a/services/abilitymgr/test/unittest/phone/info_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/info_test/BUILD.gn @@ -57,6 +57,7 @@ ohos_unittest("info_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/kernal_system_app_manager_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/kernal_system_app_manager_test/BUILD.gn index 0346377ea1df2b3b465a001279d459bfe076112f..50f8c4b2e439aa2f3522d179b4a052255d4259de 100755 --- a/services/abilitymgr/test/unittest/phone/kernal_system_app_manager_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/kernal_system_app_manager_test/BUILD.gn @@ -58,6 +58,7 @@ ohos_unittest("kernal_system_app_mgr_test") { "//utils/native/base:utils", ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/kernal_system_app_manager_test/kernal_system_app_manager_test.cpp b/services/abilitymgr/test/unittest/phone/kernal_system_app_manager_test/kernal_system_app_manager_test.cpp index 8d5191d5e1d052a6f4811223c308e506179fcb9d..73f7fdbb84154775661c44f6303a71dbc65d715a 100644 --- a/services/abilitymgr/test/unittest/phone/kernal_system_app_manager_test/kernal_system_app_manager_test.cpp +++ b/services/abilitymgr/test/unittest/phone/kernal_system_app_manager_test/kernal_system_app_manager_test.cpp @@ -74,15 +74,12 @@ void KernalSystemAppManagerTest::SetUpTestCase() int systemAbilityId = 401; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( systemAbilityId, new (std::nothrow) AppExecFwk::BundleMgrService()); - DelayedSingleton::GetInstance(); DelayedSingleton::GetInstance()->OnStart(); } void KernalSystemAppManagerTest::TearDownTestCase() { OHOS::DelayedSingleton::GetInstance()->OnStop(); - OHOS::DelayedSingleton::DestroyInstance(); - OHOS::DelayedSingleton::DestroyInstance(); } diff --git a/services/abilitymgr/test/unittest/phone/lifecycle_deal_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/lifecycle_deal_test/BUILD.gn index d0996dfc3301af0d641ee7cdeebbdee9a063c6b3..cfc5daf2eb8e9c3201ae22cee67d2866ce530b64 100755 --- a/services/abilitymgr/test/unittest/phone/lifecycle_deal_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/lifecycle_deal_test/BUILD.gn @@ -58,6 +58,7 @@ ohos_unittest("lifecycle_deal_test") { external_deps = [ "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", "bundle_framework:appexecfwk_core", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", diff --git a/services/abilitymgr/test/unittest/phone/lifecycle_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/lifecycle_test/BUILD.gn index ac8cf6512bc67ecc6a6e3824ecc9b54504b685f2..f7d87c2c354a9892d965eeecbe2f2a5a886d89b6 100755 --- a/services/abilitymgr/test/unittest/phone/lifecycle_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/lifecycle_test/BUILD.gn @@ -57,6 +57,7 @@ ohos_unittest("lifecycle_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/lifecycle_test/lifecycle_test.cpp b/services/abilitymgr/test/unittest/phone/lifecycle_test/lifecycle_test.cpp index 1d88e6e649867432d8f28ddd1bfbbc251321a231..caba94dd3fd1cd9ffacc30f96407bc0ad0639ad1 100644 --- a/services/abilitymgr/test/unittest/phone/lifecycle_test/lifecycle_test.cpp +++ b/services/abilitymgr/test/unittest/phone/lifecycle_test/lifecycle_test.cpp @@ -80,7 +80,7 @@ public: public: int startLancherFlag_ = false; - std::shared_ptr abilityMs_ {nullptr}; + std::shared_ptr abilityMs_ = OHOS::DelayedSingleton::GetInstance(); std::shared_ptr launcherAbilityRecord_ {nullptr}; // launcher ability OHOS::sptr launcherToken_ {nullptr}; // token of launcher ability std::shared_ptr nextAbilityRecord_ {nullptr}; // ability being launched @@ -98,34 +98,31 @@ void LifecycleTest::OnStartabilityAms() } abilityMs_->state_ = ServiceRunningState::STATE_RUNNING; - abilityMs_->eventLoop_ = AppExecFwk::EventRunner::Create(AbilityConfig::NAME_ABILITY_MGR_SERVICE); EXPECT_TRUE(abilityMs_->eventLoop_); - abilityMs_->handler_ = std::make_shared(abilityMs_->eventLoop_, abilityMs_); abilityMs_->connectManager_ = std::make_shared(); + abilityMs_->connectManagers_.emplace(0, abilityMs_->connectManager_); EXPECT_TRUE(abilityMs_->handler_); EXPECT_TRUE(abilityMs_->connectManager_); - abilityMs_->connectManager_->SetEventHandler(abilityMs_->handler_); - abilityMs_->dataAbilityManager_ = std::make_shared(); + abilityMs_->dataAbilityManagers_.emplace(0, abilityMs_->dataAbilityManager_); EXPECT_TRUE(abilityMs_->dataAbilityManager_); - abilityMs_->amsConfigResolver_ = std::make_shared(); EXPECT_TRUE(abilityMs_->amsConfigResolver_); abilityMs_->amsConfigResolver_->Parse(); - + abilityMs_->currentMissionListManager_ = std::make_shared(0); + abilityMs_->currentMissionListManager_->Init(); abilityMs_->pendingWantManager_ = std::make_shared(); EXPECT_TRUE(abilityMs_->pendingWantManager_); - int userId = abilityMs_->GetUserId(); abilityMs_->SetStackManager(userId, true); + EXPECT_TRUE(abilityMs_->GetStackManager()); + abilityMs_->stackManagers_.emplace(0, abilityMs_->GetStackManager()); abilityMs_->systemAppManager_ = std::make_shared(userId); EXPECT_TRUE(abilityMs_->systemAppManager_); - abilityMs_->eventLoop_->Run(); - return; } @@ -145,7 +142,6 @@ void LifecycleTest::TearDownTestCase(void) void LifecycleTest::SetUp(void) { - abilityMs_ = OHOS::DelayedSingleton::GetInstance(); OnStartabilityAms(); WaitUntilTaskFinished(); StartLauncherAbility(); @@ -155,7 +151,6 @@ void LifecycleTest::SetUp(void) void LifecycleTest::TearDown(void) { abilityMs_->OnStop(); - OHOS::DelayedSingleton::DestroyInstance(); launcherAbilityRecord_.reset(); launcherToken_ = nullptr; nextAbilityRecord_.reset(); @@ -163,7 +158,6 @@ void LifecycleTest::TearDown(void) launcherScheduler_ = nullptr; nextScheduler_ = nullptr; command_.reset(); - abilityMs_.reset(); startLancherFlag_ = false; } @@ -210,9 +204,9 @@ bool LifecycleTest::StartNextAbility() auto stackManager = abilityMs_->GetStackManager(); EXPECT_TRUE(stackManager); if (stackManager) { - GTEST_LOG_(ERROR) << "top BundleName :" + GTEST_LOG_(ERROR) << "top BundleName :" << stackManager->GetCurrentTopAbility()->GetWant().GetElement().GetBundleName(); - GTEST_LOG_(ERROR) << "top AbilityName :" + GTEST_LOG_(ERROR) << "top AbilityName :" << stackManager->GetCurrentTopAbility()->GetWant().GetElement().GetAbilityName(); stackManager->GetCurrentTopAbility()->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); } diff --git a/services/abilitymgr/test/unittest/phone/lock_screen_white_list_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/lock_screen_white_list_test/BUILD.gn index dc01b5da9b34824ee6ec8eb35739791a6b29dadb..2b8b768ba8817d6c778e5f9589e658c2ecb9a7a3 100755 --- a/services/abilitymgr/test/unittest/phone/lock_screen_white_list_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/lock_screen_white_list_test/BUILD.gn @@ -61,6 +61,7 @@ ohos_unittest("lock_screen_white_list_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/mission_list_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/mission_list_test/BUILD.gn index b78161b10091c2f178bb1f699c46a7c6fedac66d..edcc5c6c6c07945cacd10e400c89b22e0d0c849f 100755 --- a/services/abilitymgr/test/unittest/phone/mission_list_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/mission_list_test/BUILD.gn @@ -55,6 +55,7 @@ ohos_unittest("mission_list_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/mission_record_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/mission_record_test/BUILD.gn index 7efb097b7810fb33ef77cb91b051719273663823..32fe28154ff1fc68439cf5f2416c0cd7c12f81bf 100755 --- a/services/abilitymgr/test/unittest/phone/mission_record_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/mission_record_test/BUILD.gn @@ -55,6 +55,7 @@ ohos_unittest("mission_record_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/mission_stack_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/mission_stack_test/BUILD.gn index cfd41f71d6496a3b0ecf8b7e0bd3cfb69ffa3bfc..e593f79c7045d656b740d98c99ee4b796d0f4b52 100755 --- a/services/abilitymgr/test/unittest/phone/mission_stack_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/mission_stack_test/BUILD.gn @@ -55,6 +55,7 @@ ohos_unittest("mission_stack_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/mission_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/mission_test/BUILD.gn index 8328c8302c0aad486a9370e4750936f35c88ca5d..1016e3b220b25e2e066ef621fc56dd9e42341118 100755 --- a/services/abilitymgr/test/unittest/phone/mission_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/mission_test/BUILD.gn @@ -55,6 +55,7 @@ ohos_unittest("mission_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/pending_want_key_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/pending_want_key_test/BUILD.gn index c85962e2f376e90d5c5635bf591a5cda7121d4d0..3e0e13e260b70fbb4bcb7a8a6140798759b13702 100755 --- a/services/abilitymgr/test/unittest/phone/pending_want_key_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/pending_want_key_test/BUILD.gn @@ -50,6 +50,7 @@ ohos_unittest("pending_want_key_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/pending_want_manager_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/pending_want_manager_test/BUILD.gn index bdcf01bfa947918bcc552a93bf8e14e87f23575f..e721a1d5bce30466fd28ed81cb25d9ad48f46b57 100755 --- a/services/abilitymgr/test/unittest/phone/pending_want_manager_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/pending_want_manager_test/BUILD.gn @@ -54,6 +54,7 @@ ohos_unittest("pending_want_manager_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/pending_want_manager_test/pending_want_manager_test.cpp b/services/abilitymgr/test/unittest/phone/pending_want_manager_test/pending_want_manager_test.cpp index 95e043170d13f73ef68cb84cfe88ca9f4159bc2f..db35827b34336b617bae84c96ccaa2e473cdf83f 100644 --- a/services/abilitymgr/test/unittest/phone/pending_want_manager_test/pending_want_manager_test.cpp +++ b/services/abilitymgr/test/unittest/phone/pending_want_manager_test/pending_want_manager_test.cpp @@ -132,7 +132,6 @@ void PendingWantManagerTest::SetUp() void PendingWantManagerTest::TearDown() { abilityMs_->OnStop(); - OHOS::DelayedSingleton::DestroyInstance(); } WantSenderInfo PendingWantManagerTest::MakeWantSenderInfo(Want &want, int32_t flags, int32_t userId, int32_t type) diff --git a/services/abilitymgr/test/unittest/phone/pending_want_record_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/pending_want_record_test/BUILD.gn index 9d1098d667b7e809ef7cc4e6c2dc37c93c5a8af5..3923e207737ac861961889bfd0e1b002ee985a4b 100755 --- a/services/abilitymgr/test/unittest/phone/pending_want_record_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/pending_want_record_test/BUILD.gn @@ -54,6 +54,7 @@ ohos_unittest("pending_want_record_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/pending_want_record_test/pending_want_record_test.cpp b/services/abilitymgr/test/unittest/phone/pending_want_record_test/pending_want_record_test.cpp index 142bfb6d0802e5c7ab4c0313c849913561fdaf82..c26613675491ed4dcd4deeddcc5a9a23e379a872 100644 --- a/services/abilitymgr/test/unittest/phone/pending_want_record_test/pending_want_record_test.cpp +++ b/services/abilitymgr/test/unittest/phone/pending_want_record_test/pending_want_record_test.cpp @@ -46,9 +46,10 @@ using OHOS::AppExecFwk::ElementName; namespace OHOS { namespace AAFwk { +namespace { #define SLEEP(milli) std::this_thread::sleep_for(std::chrono::seconds(milli)) - -namespace {} // namespace +const int INVALID_CALLER_UID_ERR = 29360128; +} // namespace class PendingWantRecordTest : public testing::Test { public: static void SetUpTestCase(); @@ -74,7 +75,6 @@ public: public: std::shared_ptr pendingManager_ {nullptr}; - std::shared_ptr abilityMs_ {nullptr}; }; int PendingWantRecordTest::CancelReceiver::performReceiveCount = 0; @@ -100,17 +100,15 @@ void PendingWantRecordTest::SetUpTestCase() void PendingWantRecordTest::TearDownTestCase() { OHOS::DelayedSingleton::DestroyInstance(); - OHOS::DelayedSingleton::DestroyInstance(); } void PendingWantRecordTest::SetUp() { - abilityMs_ = OHOS::DelayedSingleton::GetInstance(); - abilityMs_->OnStart(); } void PendingWantRecordTest::TearDown() -{} +{ +} WantSenderInfo PendingWantRecordTest::MakeWantSenderInfo(Want &want, int32_t flags, int32_t userId, int32_t type) { @@ -330,7 +328,7 @@ HWTEST_F(PendingWantRecordTest, PendingWantRecordTest_0800, TestSize.Level1) std::make_shared(pendingManager_, 1, nullptr, key); EXPECT_NE(pendingWantRecord, nullptr); SenderInfo info; - EXPECT_EQ(pendingWantRecord->SenderInner(info), NO_ERROR); + EXPECT_EQ(pendingWantRecord->SenderInner(info), INVALID_CALLER_UID_ERR); EXPECT_TRUE(info.resolvedType == key->GetRequestResolvedType()); } diff --git a/services/abilitymgr/test/unittest/phone/resume_mission_container_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/resume_mission_container_test/BUILD.gn index c6e2f72cca915c002edd8028f314a42687f63350..c50b7e90963f181969f4357e2e9ce6e7280926fc 100755 --- a/services/abilitymgr/test/unittest/phone/resume_mission_container_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/resume_mission_container_test/BUILD.gn @@ -53,6 +53,7 @@ ohos_unittest("resume_mission_container_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/screenshot_handler_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/screenshot_handler_test/BUILD.gn index 7f9b0ab38a9fa60fba138b17abf7ebcef510d3ef..e0d5bbbf1f9a6ad51854473251f6cc621235ccb8 100755 --- a/services/abilitymgr/test/unittest/phone/screenshot_handler_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/screenshot_handler_test/BUILD.gn @@ -61,6 +61,7 @@ ohos_unittest("ability_screenshot_handler_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/sender_info_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/sender_info_test/BUILD.gn index 8250b307c92901da02520a39ccc21b44ff15950a..e6fda6bebe4c4fee87f852a6b56daa73344b8400 100755 --- a/services/abilitymgr/test/unittest/phone/sender_info_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/sender_info_test/BUILD.gn @@ -54,6 +54,7 @@ ohos_unittest("sender_info_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/terminate_ability_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/terminate_ability_test/BUILD.gn index 76af6acb6262be54f7113348de36ac48fcc7fddd..b96dcc1575981b150c418263a889d66c6433b937 100755 --- a/services/abilitymgr/test/unittest/phone/terminate_ability_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/terminate_ability_test/BUILD.gn @@ -59,6 +59,7 @@ ohos_unittest("terminate_ability_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/terminate_ability_test/terminate_ability_test.cpp b/services/abilitymgr/test/unittest/phone/terminate_ability_test/terminate_ability_test.cpp index da3c9d8ca3baf5f48fe9bb4d66e8d1a377c2e215..cbfeec4338f69c11bb18a1bf0880ee96a7555516 100644 --- a/services/abilitymgr/test/unittest/phone/terminate_ability_test/terminate_ability_test.cpp +++ b/services/abilitymgr/test/unittest/phone/terminate_ability_test/terminate_ability_test.cpp @@ -76,7 +76,7 @@ static void WaitUntilTaskFinished() const uint32_t maxRetryTime = 1000; const uint32_t sleepTime = 1000; uint32_t count = 0; - auto handler = OHOS::DelayedSingleton::GetInstance()->GetEventHandler(); + auto handler = g_aams->GetEventHandler(); std::atomic taskCalled(false); auto f = [&taskCalled]() { taskCalled.store(true); }; if (handler->PostTask(f)) { @@ -138,12 +138,14 @@ void TerminateAbilityTest::OnStartAms() g_aams->handler_ = std::make_shared(g_aams->eventLoop_, g_aams); g_aams->connectManager_ = std::make_shared(); + g_aams->connectManagers_.emplace(0, g_aams->connectManager_); EXPECT_TRUE(g_aams->handler_); EXPECT_TRUE(g_aams->connectManager_); g_aams->connectManager_->SetEventHandler(g_aams->handler_); g_aams->dataAbilityManager_ = std::make_shared(); + g_aams->dataAbilityManagers_.emplace(0, g_aams->dataAbilityManager_); EXPECT_TRUE(g_aams->dataAbilityManager_); g_aams->amsConfigResolver_ = std::make_shared(); @@ -153,6 +155,9 @@ void TerminateAbilityTest::OnStartAms() g_aams->pendingWantManager_ = std::make_shared(); EXPECT_TRUE(g_aams->pendingWantManager_); + g_aams->currentMissionListManager_ = std::make_shared(0); + g_aams->currentMissionListManager_->Init(); + int userId = g_aams->GetUserId(); g_aams->SetStackManager(userId, true); g_aams->systemAppManager_ = std::make_shared(userId); @@ -188,7 +193,6 @@ void TerminateAbilityTest::SetUp(void) void TerminateAbilityTest::TearDown(void) { g_aams->OnStop(); - OHOS::DelayedSingleton::DestroyInstance(); } bool TerminateAbilityTest::StartAbility( @@ -354,7 +358,7 @@ HWTEST_F(TerminateAbilityTest, AAFWK_g_aamsTerminateAbility_004, TestSize.Level1 EXPECT_TRUE(launcherAbilityRecord); // last launcherAbilityRecord - EXPECT_EQ(g_aams->TerminateAbility(launcherToken, -1, nullptr), TERMINATE_LAUNCHER_DENIED); + EXPECT_EQ(g_aams->TerminateAbility(launcherToken, -1, nullptr), 0); WaitUntilTaskFinished(); } @@ -399,7 +403,7 @@ HWTEST_F(TerminateAbilityTest, AAFWK_g_aamsTerminateAbility_005, TestSize.Level1 EXPECT_NE(launcherAbilityRecord->GetAbilityState(), OHOS::AAFwk::AbilityState::BACKGROUND); // clear launcherAbilityRecord - EXPECT_EQ(g_aams->TerminateAbility(launcherToken, -1, nullptr), TERMINATE_LAUNCHER_DENIED); + EXPECT_EQ(g_aams->TerminateAbility(launcherToken, -1, nullptr), 0); WaitUntilTaskFinished(); } @@ -472,7 +476,7 @@ HWTEST_F(TerminateAbilityTest, AAFWK_g_aamsTerminateAbility_007, TestSize.Level1 EXPECT_TRUE(serverResult == nullptr); // clear launcherAbilityRecord - EXPECT_EQ(g_aams->TerminateAbility(launcherTokenA, -1, nullptr), TERMINATE_LAUNCHER_DENIED); + EXPECT_EQ(g_aams->TerminateAbility(launcherTokenA, -1, nullptr), 0); WaitUntilTaskFinished(); } @@ -512,7 +516,7 @@ HWTEST_F(TerminateAbilityTest, AAFWK_g_aamsTerminateAbility_008, TestSize.Level1 // caller is active EXPECT_NE(testAbilityRecordA->GetAbilityState(), OHOS::AAFwk::AbilityState::BACKGROUND); // clear launcherAbilityRecord - EXPECT_EQ(g_aams->TerminateAbility(tokenA, -1, nullptr), 0); + EXPECT_EQ(g_aams->TerminateAbility(tokenA, -1, nullptr), ERR_INVALID_VALUE); WaitUntilTaskFinished(); } @@ -556,7 +560,7 @@ HWTEST_F(TerminateAbilityTest, AAFWK_g_aamsTerminateAbility_009, TestSize.Level1 // caller is active EXPECT_NE(launcherAbilityRecordA->GetAbilityState(), OHOS::AAFwk::AbilityState::BACKGROUND); // clear launcherAbilityRecord - EXPECT_EQ(g_aams->TerminateAbility(launcherTokenA, -1, nullptr), TERMINATE_LAUNCHER_DENIED); + EXPECT_EQ(g_aams->TerminateAbility(launcherTokenA, -1, nullptr), ERR_INVALID_VALUE); } /* @@ -654,7 +658,7 @@ HWTEST_F(TerminateAbilityTest, AAFWK_g_aamsTerminateAbility_011, TestSize.Level1 PacMap saveData; EXPECT_NE(g_aams->AbilityTransitionDone(launcherTokenA, OHOS::AAFwk::AbilityState::ACTIVE, saveData), 0); EXPECT_EQ(g_aams->TerminateAbility(launcherTokenC, -1, &want), 0); - EXPECT_EQ(g_aams->TerminateAbility(launcherTokenA, -1, &want), TERMINATE_LAUNCHER_DENIED); + EXPECT_EQ(g_aams->TerminateAbility(launcherTokenA, -1, &want), 0); WaitUntilTaskFinished(); } diff --git a/services/abilitymgr/test/unittest/phone/want_receiver_proxy_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/want_receiver_proxy_test/BUILD.gn index 0f6d0fa0ec4ab54cb9ea78b0227bb2da68a60c12..ef69a506a6c29cdc2eb85db1472a1056a7740bfb 100755 --- a/services/abilitymgr/test/unittest/phone/want_receiver_proxy_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/want_receiver_proxy_test/BUILD.gn @@ -55,6 +55,7 @@ ohos_unittest("want_receiver_proxy_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/want_receiver_stub_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/want_receiver_stub_test/BUILD.gn index f4d265e82f543ac939b036e53d52d8079204d154..5a2d38e81a668154efd24577a8a0abfa5037883c 100755 --- a/services/abilitymgr/test/unittest/phone/want_receiver_stub_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/want_receiver_stub_test/BUILD.gn @@ -56,6 +56,7 @@ ohos_unittest("want_receiver_stub_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/want_sender_info_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/want_sender_info_test/BUILD.gn index fb571a29d88c5dc7c0326141731327e71f323453..e55ba85c80d511d7988f180146b59594eebb55e8 100755 --- a/services/abilitymgr/test/unittest/phone/want_sender_info_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/want_sender_info_test/BUILD.gn @@ -54,6 +54,7 @@ ohos_unittest("want_sender_info_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/want_sender_proxy_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/want_sender_proxy_test/BUILD.gn index f1edbed31c88a496cf4b41191ca75de0149e1df2..3c9d898325bb325e8bdd9d5c8316cc18108c9255 100755 --- a/services/abilitymgr/test/unittest/phone/want_sender_proxy_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/want_sender_proxy_test/BUILD.gn @@ -55,6 +55,7 @@ ohos_unittest("want_sender_proxy_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/want_sender_stub_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/want_sender_stub_test/BUILD.gn index ae59d37bc736828f0ea132b97d3e7c17469e2a48..59a0a0489ac2d162987b14efca73206c12f676ce 100755 --- a/services/abilitymgr/test/unittest/phone/want_sender_stub_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/want_sender_stub_test/BUILD.gn @@ -56,6 +56,7 @@ ohos_unittest("want_sender_stub_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/wants_info_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/wants_info_test/BUILD.gn index 4f5d38f4623849ea9b1e30608d73d25976427bef..28e7e5b1894937b86e503bdb243c60fb8c5e9508 100755 --- a/services/abilitymgr/test/unittest/phone/wants_info_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/wants_info_test/BUILD.gn @@ -55,6 +55,7 @@ ohos_unittest("wants_info_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/services/abilitymgr/test/unittest/phone/window_info_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/window_info_test/BUILD.gn index 31e81a792421a90d40508071223306f7fe0c37f9..75d7230e7d7525beb7b0bb303d1a2e305c8d9461 100755 --- a/services/abilitymgr/test/unittest/phone/window_info_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/window_info_test/BUILD.gn @@ -47,6 +47,7 @@ ohos_unittest("window_info_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", ] diff --git a/services/appmgr/BUILD.gn b/services/appmgr/BUILD.gn index 84cb63309ee5b40f0fbfd83a77ea6c3cf6a99dab..4647bde21cc3645e7a4ef89db49730324db452a4 100644 --- a/services/appmgr/BUILD.gn +++ b/services/appmgr/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -114,6 +114,7 @@ ohos_shared_library("libams") { "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${innerkits_path}/uri_permission:uri_permission_mgr", "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//base/global/i18n_standard/frameworks/intl:intl_util", "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", @@ -129,6 +130,7 @@ ohos_shared_library("libams") { "bytrace_standard:bytrace_core", "ces_standard:cesfwk_core", "ces_standard:cesfwk_innerkits", + "hicollie_native:libhicollie", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/appmgr/include/ability_running_record.h b/services/appmgr/include/ability_running_record.h index eee811ed0a08cfc6fa4fb92640dbf233afbba475..10e363b41a3c5ea362af91fca5eac0c2666c7013 100644 --- a/services/appmgr/include/ability_running_record.h +++ b/services/appmgr/include/ability_running_record.h @@ -23,6 +23,7 @@ #include "ability_info.h" #include "application_info.h" #include "app_mgr_constants.h" +#include "want.h" namespace OHOS { namespace AppExecFwk { @@ -45,6 +46,15 @@ public: */ const std::shared_ptr &GetAbilityInfo() const; + /** + * @brief Obtains the info of the ability. + * + * @return Returns the ability want. + */ + const std::shared_ptr &GetWant() const; + + void SetWant(const std::shared_ptr &want); + /** * @brief Obtains the token of the ability. * @@ -169,6 +179,7 @@ private: bool isTerminating_ = false; AbilityState state_ = AbilityState::ABILITY_STATE_BEGIN; std::shared_ptr info_; + std::shared_ptr want_ = nullptr; sptr token_; sptr preToken_; }; diff --git a/services/appmgr/include/ams_mgr_scheduler.h b/services/appmgr/include/ams_mgr_scheduler.h index 64d6b1d34cd00b341d9b96a7683886f1829b57c3..a148acf9c8fe149c656c6599d5a85327f1fad2f0 100644 --- a/services/appmgr/include/ams_mgr_scheduler.h +++ b/services/appmgr/include/ams_mgr_scheduler.h @@ -51,7 +51,8 @@ public: * @return */ virtual void LoadAbility(const sptr &token, const sptr &preToken, - const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo) override; + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo, + const std::shared_ptr &want) override; /** * TerminateAbility, call TerminateAbility() through the proxy object, terminate the token ability. diff --git a/services/appmgr/include/app_death_recipient.h b/services/appmgr/include/app_death_recipient.h index 39179e0b3a0e9864b882dc210820b8634f83b888..0bd39e48c3ab32105a57d5e14bcacc1ff6ad29ad 100644 --- a/services/appmgr/include/app_death_recipient.h +++ b/services/appmgr/include/app_death_recipient.h @@ -42,7 +42,10 @@ public: */ void SetAppMgrServiceInner(const std::shared_ptr &serviceInner); + void SetIsRenderProcess(bool isRenderProcess); + private: + bool isRenderProcess_ = false; std::weak_ptr handler_; std::weak_ptr appMgrServiceInner_; }; diff --git a/services/appmgr/include/app_mgr_service.h b/services/appmgr/include/app_mgr_service.h index 3ed7ee2b964bf5b1107b821d2f1709cf9b5f4961..6ddc838ea5cbe7459bf863db71e0b087069e8e1b 100644 --- a/services/appmgr/include/app_mgr_service.h +++ b/services/appmgr/include/app_mgr_service.h @@ -215,6 +215,20 @@ public: virtual void ScheduleAcceptWantDone( const int32_t recordId, const AAFwk::Want &want, const std::string &flag) override; + /** + * Get the token of ability records by process ID. + * + * @param pid The process id. + * @param tokens The token of ability records. + * @return Returns true on success, others on failure. + */ + int GetAbilityRecordsByProcessID(const int pid, std::vector> &tokens) override; + + virtual int StartRenderProcess(const std::string &renderParam, int32_t ipcFd, + int32_t sharedFd, pid_t &renderPid) override; + + virtual void AttachRenderProcess(const sptr &shceduler) override; + private: /** * Init, Initialize application services. diff --git a/services/appmgr/include/app_mgr_service_inner.h b/services/appmgr/include/app_mgr_service_inner.h index 6d38e4a0c079e9a394369b8e80b4ee6fd2c8aafc..043dd320f53fbcb0a071b5c0895220ed0b0809a1 100644 --- a/services/appmgr/include/app_mgr_service_inner.h +++ b/services/appmgr/include/app_mgr_service_inner.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -67,11 +67,13 @@ public: * @param preToken, the unique identification to call the ability. * @param abilityInfo, the ability information. * @param appInfo, the app information. + * @param want the ability want. * * @return */ virtual void LoadAbility(const sptr &token, const sptr &preToken, - const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo); + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo, + const std::shared_ptr &want); /** * TerminateAbility, terminate the token ability. @@ -269,23 +271,6 @@ public: */ virtual int32_t GetProcessRunningInfosByUserId(std::vector &info, int32_t userId); - // Get AppRunningRecord according to appInfo. Create if not exists. - // Create ability record if not exists and abilityInfo not null. - // Return AppRunningRecord pointer if success get or create. - // If error occurs, error code is in |result| - - /** - * CreateAppRunningRecord, create application record information. - * - * @param token, the unique identification to the ability. - * @param abilityInfo, ability information. - * @param appInfo, app information. - * @param processName, the app process name. - * @param uid, app uid in Application record. - * @param result, If error occurs, error code is in |result|. - * - * @return AppRunningRecord pointer if success create. - */ std::shared_ptr CreateAppRunningRecord( const sptr &token, const sptr &preToken, @@ -293,7 +278,8 @@ public: const std::shared_ptr &abilityInfo, const std::string &processName, const BundleInfo &bundleInfo, - const HapModuleInfo &hapModuleInfo); + const HapModuleInfo &hapModuleInfo, + const std::shared_ptr &want); /** * OnStop, Application management service stopped. @@ -422,9 +408,10 @@ public: * OnRemoteDied, Equipment death notification. * * @param remote, Death client. + * @param isRenderProcess is render process died. * @return */ - void OnRemoteDied(const wptr &remote); + void OnRemoteDied(const wptr &remote, bool isRenderProcess = false); /** * AddAppDeathRecipient, Add monitoring death application record. @@ -566,6 +553,20 @@ public: void ScheduleAcceptWantDone(const int32_t recordId, const AAFwk::Want &want, const std::string &flag); + /** + * Get the token of ability records by process ID. + * + * @param pid The process id. + * @param tokens The token of ability records. + * @return Returns true on success, others on failure. + */ + int GetAbilityRecordsByProcessID(const int pid, std::vector> &tokens); + + virtual int32_t StartRenderProcess(const pid_t hostPid, const std::string &renderParam, + int32_t ipcFd, int32_t sharedFd, pid_t &renderPid); + + virtual void AttachRenderProcess(const pid_t pid, const sptr &scheduler); + private: void StartEmptyResidentProcess(const BundleInfo &info, const std::string &processName, int restartCount); @@ -578,7 +579,7 @@ private: bool GetBundleInfo(const std::string &bundelName, BundleInfo &bundleInfo); void MakeProcessName(std::string &processName, const std::shared_ptr &abilityInfo, - const std::shared_ptr &appInfo); + const std::shared_ptr &appInfo, HapModuleInfo &hapModuleInfo); /** * StartAbility, load the ability that needed to be started(Start on the basis of the original process). * Start on a new boot process @@ -591,7 +592,7 @@ private: */ void StartAbility(const sptr &token, const sptr &preToken, const std::shared_ptr &abilityInfo, const std::shared_ptr &appRecord, - const HapModuleInfo &hapModuleInfo); + const HapModuleInfo &hapModuleInfo, const std::shared_ptr &want); /** * UnsuspendApplication, Application process state switch to unsuspend. @@ -790,6 +791,11 @@ private: void GetGlobalConfiguration(); + int StartRenderProcessImpl(const std::shared_ptr &renderRecord, + const std::shared_ptr appRecord, pid_t &renderPid); + + void OnRenderRemoteDied(const wptr &remote); + private: /** * ClearUpApplicationData, clear the application data. diff --git a/services/appmgr/include/app_running_manager.h b/services/appmgr/include/app_running_manager.h index 8d38a1c0b23f1da23b2f05c7aac9468f451f85f4..480fb095df42bb9d8c71075c3847e87bb95b54de 100644 --- a/services/appmgr/include/app_running_manager.h +++ b/services/appmgr/include/app_running_manager.h @@ -148,6 +148,8 @@ public: void ClipStringContent(const std::regex &re, const std::string &sorce, std::string &afferCutStr); void HandleAddAbilityStageTimeOut(const int64_t eventId); void HandleStartSpecifiedAbilityTimeOut(const int64_t eventId); + std::shared_ptr GetAppRunningRecordByRenderPid(const pid_t pid); + void OnRemoteRenderDied(const wptr &remote); private: std::shared_ptr GetAbilityRunningRecord(const int64_t eventId); diff --git a/services/appmgr/include/app_running_record.h b/services/appmgr/include/app_running_record.h index 2a010e28da4bccdf0d24b8d01a30529a780e111f..759010ff9bfaf8e808acac8a8f7799cc856b61dc 100644 --- a/services/appmgr/include/app_running_record.h +++ b/services/appmgr/include/app_running_record.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,6 +21,7 @@ #include #include #include "iremote_object.h" +#include "irender_scheduler.h" #include "ability_running_record.h" #include "ability_state_data.h" #include "application_info.h" @@ -33,6 +34,7 @@ #include "priority_object.h" #include "app_lifecycle_deal.h" #include "module_running_record.h" +#include "app_spawn_msg_wrapper.h" namespace OHOS { namespace AppExecFwk { @@ -41,6 +43,45 @@ const int RESTART_RESIDENT_PROCESS_MAX_TIMES = 15; } class AbilityRunningRecord; class AppMgrServiceInner; +class AppRunningRecord; + +/** + * @class RenderRecord + * Record webview render process info. + */ +class RenderRecord { +public: + RenderRecord(pid_t hostPid, const std::string& renderParam, + int32_t ipcFd, int32_t sharedFd, const std::shared_ptr &host); + + virtual ~RenderRecord(); + + static std::shared_ptr CreateRenderRecord(pid_t hostPid, const std::string& renderParam, + int32_t ipcFd, int32_t sharedFd, const std::shared_ptr &host); + + void SetPid(pid_t pid); + pid_t GetPid(); + pid_t GetHostPid(); + std::string GetRenderParam(); + int32_t GetIpcFd(); + int32_t GetSharedFd(); + std::shared_ptr GetHostRecord(); + sptr GetScheduler(); + void SetScheduler(const sptr &scheduler); + void SetDeathRecipient(const sptr recipient); + void RegisterDeathRecipient(); + +private: + pid_t pid_ = 0; + pid_t hostPid_ = 0; + std::string renderParam_; + int32_t ipcFd_ = 0; + int32_t sharedFd_ = 0; + std::weak_ptr host_; // webview host + sptr renderScheduler_; + sptr deathRecipient_ = nullptr; +}; + class AppRunningRecord : public std::enable_shared_from_this { public: static int64_t appEventId_; @@ -174,19 +215,9 @@ public: */ sptr GetApplicationClient() const; - // Add new module instance to current running modules list managed by this process - /** - * AddModule, Add new module instance to current running modules list managed by this process. - * - * @param appInfo, the app info. - * @param token, the unique identification to the ability. - * @param abilityInfo, the ability info. - * @param hapModuleInfo, the hapModule info. - * - * @return the ability record. - */ void AddModule(const std::shared_ptr &appInfo, const std::shared_ptr &abilityInfo, - const sptr &token, const HapModuleInfo &hapModuleInfo); + const sptr &token, const HapModuleInfo &hapModuleInfo, + const std::shared_ptr &want); void AddModules(const std::shared_ptr &appInfo, const std::vector &moduleInfos); @@ -425,6 +456,11 @@ public: const std::list> GetAppInfoList(); + inline const std::shared_ptr GetApplicationInfo() + { + return appInfo_; + } + void SetRestartResidentProcCount(int count); void DecRestartResidentProcCount(); int GetRestartResidentProcCount() const; @@ -450,6 +486,11 @@ public: void ScheduleAcceptWantDone(); const AAFwk::Want &GetSpecifiedWant() const; + void SetRenderRecord(const std::shared_ptr &record); + std::shared_ptr GetRenderRecord(); + void SetStartMsg(const AppSpawnStartMsg &msg); + AppSpawnStartMsg GetStartMsg(); + private: /** * SearchTheModuleInfoNeedToUpdated, Get an uninitialized abilitystage data. @@ -528,6 +569,10 @@ private: std::string moduleName_; UserTestRecord userTestRecord_; + + // render record + std::shared_ptr renderRecord_ = nullptr; + AppSpawnStartMsg startMsg_; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/include/app_spawn_client.h b/services/appmgr/include/app_spawn_client.h index 862e80345572bd60bf1a0838b9bd4063119a2a53..96c6cbdba27046306c8b9d65858fd98828835268 100644 --- a/services/appmgr/include/app_spawn_client.h +++ b/services/appmgr/include/app_spawn_client.h @@ -29,7 +29,7 @@ public: /** * Constructor. */ - AppSpawnClient(); + explicit AppSpawnClient(bool isWebViewSpawn = false); /** * Destructor diff --git a/services/appmgr/include/app_spawn_msg_wrapper.h b/services/appmgr/include/app_spawn_msg_wrapper.h index 5d923cde860d9fc333c92fc5f344c352d4cde883..acbaeef24d978795a6759501dd11ec1abb369d93 100644 --- a/services/appmgr/include/app_spawn_msg_wrapper.h +++ b/services/appmgr/include/app_spawn_msg_wrapper.h @@ -33,6 +33,8 @@ struct AppSpawnStartMsg { std::string soPath; uint32_t accessTokenId; std::string apl; + std::string bundleName; + std::string renderParam; // only webview spawn need this param. }; using AppSpawnMsg = AppSpawn::ClientSocket::AppProperty; diff --git a/services/appmgr/include/app_spawn_socket.h b/services/appmgr/include/app_spawn_socket.h index ef133c455abd192461b499a405cbd054df8b95fa..a4c60afa08f60296bf7d822b69cfcf17c07a9930 100644 --- a/services/appmgr/include/app_spawn_socket.h +++ b/services/appmgr/include/app_spawn_socket.h @@ -29,7 +29,7 @@ public: /** * Constructor. */ - AppSpawnSocket(); + explicit AppSpawnSocket(bool isWebViewSpawn = false); /** * Destructor diff --git a/services/appmgr/include/module_running_record.h b/services/appmgr/include/module_running_record.h index 17b8a51ba0bb34c61d96b4142e09701f43f3e256..050c9782e38b3e28799b0942343894b20c3fcace 100644 --- a/services/appmgr/include/module_running_record.h +++ b/services/appmgr/include/module_running_record.h @@ -71,17 +71,8 @@ public: */ std::shared_ptr GetAbilityRunningRecordByToken(const sptr &token) const; - // Add new ability instance to current running abilities list managed by this process - /** - * AddAbility, Add new ability instance to current running abilities list managed by this process. - * - * @param token, the unique identification to the ability. - * @param abilityInfo, the ability info. - * - * @return the ability record. - */ - std::shared_ptr AddAbility( - const sptr &token, const std::shared_ptr &abilityInfo); + std::shared_ptr AddAbility(const sptr &token, + const std::shared_ptr &abilityInfo, const std::shared_ptr &want); bool IsLastAbilityRecord(const sptr &token); diff --git a/services/appmgr/include/remote_client_manager.h b/services/appmgr/include/remote_client_manager.h index 35656ea55639e172bd943573e30a873e93afac95..1ab9ff8344523f64eab755a8784019f4512366d1 100644 --- a/services/appmgr/include/remote_client_manager.h +++ b/services/appmgr/include/remote_client_manager.h @@ -57,9 +57,12 @@ public: */ void SetBundleManager(sptr bundleManager); + std::shared_ptr GetWebviewSpawnClient(); + private: std::shared_ptr appSpawnClient_; sptr bundleManager_; + std::shared_ptr webviewSpawnClient_; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/lmks.cfg b/services/appmgr/lmks.cfg index e02a3865092b6c72b49216a8a0a5f4b22bc261e6..543b9700b84d18411957cd78c75b597ffaccb68e 100755 --- a/services/appmgr/lmks.cfg +++ b/services/appmgr/lmks.cfg @@ -1,11 +1,4 @@ { - "jobs" : [{ - "name" : "late-fs", - "cmds" : [ - "start lmks" - ] - } - ], "services" : [{ "name" : "lmks", "path" : ["/system/bin/lmks"], diff --git a/services/appmgr/src/ability_running_record.cpp b/services/appmgr/src/ability_running_record.cpp index 8c218661ec38c399f09080472457c835c024f055..4b77e95f315149f412b48ecae2e69bdb52f32f25 100644 --- a/services/appmgr/src/ability_running_record.cpp +++ b/services/appmgr/src/ability_running_record.cpp @@ -36,6 +36,16 @@ const std::shared_ptr &AbilityRunningRecord::GetAbilityInfo() const return info_; } +const std::shared_ptr &AbilityRunningRecord::GetWant() const +{ + return want_; +} + +void AbilityRunningRecord::SetWant(const std::shared_ptr &want) +{ + want_ = want; +} + const sptr &AbilityRunningRecord::GetToken() const { return token_; diff --git a/services/appmgr/src/ams_mgr_scheduler.cpp b/services/appmgr/src/ams_mgr_scheduler.cpp index 90019d2fbe1b8e564b756556fa1f87fad52dc5e1..5a91e41d3702b09c9e843f0df04b2324a66dd404 100644 --- a/services/appmgr/src/ams_mgr_scheduler.cpp +++ b/services/appmgr/src/ams_mgr_scheduler.cpp @@ -51,7 +51,8 @@ AmsMgrScheduler::~AmsMgrScheduler() } void AmsMgrScheduler::LoadAbility(const sptr &token, const sptr &preToken, - const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo) + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo, + const std::shared_ptr &want) { if (!abilityInfo || !appInfo) { APP_LOGE("param error"); @@ -64,7 +65,7 @@ void AmsMgrScheduler::LoadAbility(const sptr &token, const sptr loadAbilityFunc = - std::bind(&AppMgrServiceInner::LoadAbility, amsMgrServiceInner_, token, preToken, abilityInfo, appInfo); + std::bind(&AppMgrServiceInner::LoadAbility, amsMgrServiceInner_, token, preToken, abilityInfo, appInfo, want); amsHandler_->PostTask(loadAbilityFunc, TASK_LOAD_ABILITY); } @@ -193,6 +194,7 @@ int32_t AmsMgrScheduler::KillApplication(const std::string &bundleName) if (!IsReady()) { return ERR_INVALID_OPERATION; } + return amsMgrServiceInner_->KillApplication(bundleName); } diff --git a/services/appmgr/src/app_death_recipient.cpp b/services/appmgr/src/app_death_recipient.cpp index 9c841c0310a1b08c55678815b701ebe69a1185d9..6ccba58de7f011804bdb2f9fb1a8ec7b93c74372 100644 --- a/services/appmgr/src/app_death_recipient.cpp +++ b/services/appmgr/src/app_death_recipient.cpp @@ -42,7 +42,7 @@ void AppDeathRecipient::OnRemoteDied(const wptr &remote) return; } - std::function onRemoteDiedFunc = std::bind(&AppMgrServiceInner::OnRemoteDied, serviceInner, remote); + auto onRemoteDiedFunc = std::bind(&AppMgrServiceInner::OnRemoteDied, serviceInner, remote, isRenderProcess_); handler->PostTask(onRemoteDiedFunc, TASK_ON_REMOTE_DIED); } @@ -55,5 +55,10 @@ void AppDeathRecipient::SetAppMgrServiceInner(const std::shared_ptr &ability) { if (appThread_) { - appThread_->ScheduleLaunchAbility(*(ability->GetAbilityInfo()), ability->GetToken()); + appThread_->ScheduleLaunchAbility(*(ability->GetAbilityInfo()), ability->GetToken(), + ability->GetWant()); } } diff --git a/services/appmgr/src/app_mgr_service.cpp b/services/appmgr/src/app_mgr_service.cpp index 32ded035fb51fa6cfa434535044cfd920c0be95a..b4ed936eb90b83da8fe49a406f1194e049b6d4dd 100755 --- a/services/appmgr/src/app_mgr_service.cpp +++ b/services/appmgr/src/app_mgr_service.cpp @@ -44,6 +44,7 @@ const std::string TASK_CLEAR_UP_APPLICATION_DATA = "ClearUpApplicationDataTask"; const std::string TASK_STARTUP_RESIDENT_PROCESS = "StartupResidentProcess"; const std::string TASK_ADD_ABILITY_STAGE_DONE = "AddAbilityStageDone"; const std::string TASK_START_USER_TEST_PROCESS = "StartUserTestProcess"; +const std::string TASK_ATTACH_RENDER_PROCESS = "AttachRenderTask"; } // namespace REGISTER_SYSTEM_ABILITY_BY_ID(AppMgrService, APP_MGR_SERVICE_ID, true); @@ -399,5 +400,39 @@ void AppMgrService::ScheduleAcceptWantDone(const int32_t recordId, const AAFwk:: auto task = [=]() { appMgrServiceInner_->ScheduleAcceptWantDone(recordId, want, flag); }; handler_->PostTask(task); } + +int AppMgrService::GetAbilityRecordsByProcessID(const int pid, std::vector> &tokens) +{ + if (!IsReady()) { + return ERR_INVALID_OPERATION; + } + return appMgrServiceInner_->GetAbilityRecordsByProcessID(pid, tokens); +} + +int32_t AppMgrService::StartRenderProcess(const std::string &renderParam, int32_t ipcFd, + int32_t sharedFd, pid_t &renderPid) +{ + if (!IsReady()) { + APP_LOGE("StartRenderProcess failed, AppMgrService not ready."); + return ERR_INVALID_OPERATION; + } + + return appMgrServiceInner_->StartRenderProcess(IPCSkeleton::GetCallingPid(), + renderParam, ipcFd, sharedFd, renderPid); +} + +void AppMgrService::AttachRenderProcess(const sptr &scheduler) +{ + APP_LOGD("AttachRenderProcess called."); + if (!IsReady()) { + APP_LOGE("AttachRenderProcess failed, not ready."); + return; + } + + auto pid = IPCSkeleton::GetCallingPid(); + auto fun = std::bind(&AppMgrServiceInner::AttachRenderProcess, + appMgrServiceInner_, pid, iface_cast(scheduler)); + handler_->PostTask(fun, TASK_ATTACH_RENDER_PROCESS); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/app_mgr_service_inner.cpp b/services/appmgr/src/app_mgr_service_inner.cpp index e69f774742fbe5bdd11378b8f30dd6a07e36e75f..9ba99d1e9c3240026483d39738e5a2fd4ec7039c 100644 --- a/services/appmgr/src/app_mgr_service_inner.cpp +++ b/services/appmgr/src/app_mgr_service_inner.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -32,10 +32,12 @@ #include "common_event_support.h" #include "iremote_object.h" #include "iservice_registry.h" +#include "ipc_skeleton.h" #include "os_account_manager.h" #include "permission/permission_kit.h" #include "system_ability_definition.h" #include "locale_config.h" +#include "uri_permission_manager_client.h" namespace OHOS { namespace AppExecFwk { @@ -53,6 +55,7 @@ constexpr int KILL_PROCESS_DELAYTIME_MICRO_SECONDS = 200; const std::string CLASS_NAME = "ohos.app.MainThread"; const std::string FUNC_NAME = "main"; const std::string SO_PATH = "system/lib64/libmapleappkit.z.so"; +const std::string RENDER_PARAM = "invalidparam"; const int32_t SIGNAL_KILL = 9; const std::string REQ_PERMISSION = "ohos.permission.LOCATION_IN_BACKGROUND"; constexpr int32_t SYSTEM_UID = 1000; @@ -61,6 +64,9 @@ constexpr int32_t USER_SCALE = 200000; constexpr int32_t BASE_USER_RANGE = 200000; +constexpr ErrCode APPMGR_ERR_OFFSET = ErrCodeOffset(SUBSYS_APPEXECFWK, 0x01); +constexpr ErrCode ERR_ALREADY_EXIST_RENDER = APPMGR_ERR_OFFSET + 100; // error code for already exist render. + int32_t GetUserIdByUid(int32_t uid) { return uid / BASE_USER_RANGE; @@ -87,7 +93,8 @@ AppMgrServiceInner::~AppMgrServiceInner() {} void AppMgrServiceInner::LoadAbility(const sptr &token, const sptr &preToken, - const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo) + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo, + const std::shared_ptr &want) { BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); if (!CheckLoadabilityConditions(token, abilityInfo, appInfo)) { @@ -108,22 +115,23 @@ void AppMgrServiceInner::LoadAbility(const sptr &token, const spt } std::string processName; - MakeProcessName(processName, abilityInfo, appInfo); + MakeProcessName(processName, abilityInfo, appInfo, hapModuleInfo); APP_LOGI("processName = [%{public}s]", processName.c_str()); auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo); if (!appRecord) { appRecord = - CreateAppRunningRecord(token, preToken, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo); + CreateAppRunningRecord(token, preToken, appInfo, abilityInfo, + processName, bundleInfo, hapModuleInfo, want); if (!appRecord) { - APP_LOGI("CreateAppRunningRecord failed, appRecord is nullptr"); + APP_LOGE("CreateAppRunningRecord failed, appRecord is nullptr"); return; } StartProcess(abilityInfo->applicationName, processName, appRecord, abilityInfo->applicationInfo.uid, abilityInfo->applicationInfo.bundleName); } else { - StartAbility(token, preToken, abilityInfo, appRecord, hapModuleInfo); + StartAbility(token, preToken, abilityInfo, appRecord, hapModuleInfo, want); } PerfProfile::GetInstance().SetAbilityLoadEndTime(GetTickCount()); PerfProfile::GetInstance().Dump(); @@ -150,7 +158,7 @@ bool AppMgrServiceInner::CheckLoadabilityConditions(const sptr &t } void AppMgrServiceInner::MakeProcessName(std::string &processName, const std::shared_ptr &abilityInfo, - const std::shared_ptr &appInfo) + const std::shared_ptr &appInfo, HapModuleInfo &hapModuleInfo) { if (!abilityInfo || !appInfo) { return; @@ -163,6 +171,12 @@ void AppMgrServiceInner::MakeProcessName(std::string &processName, const std::sh processName = appInfo->process; return; } + // check after abilityInfo, because abilityInfo contains extension process. + if (hapModuleInfo.isStageBasedModel && !hapModuleInfo.process.empty()) { + processName = hapModuleInfo.process; + APP_LOGI("Stage mode, Make processName:%{public}s", processName.c_str()); + return; + } processName = appInfo->bundleName; } @@ -427,6 +441,13 @@ int32_t AppMgrServiceInner::KillApplicationByUserId(const std::string &bundleNam APP_LOGE("GetBundleManager fail"); return ERR_NO_INIT; } + + int32_t callerUid = IPCSkeleton::GetCallingUid(); + if (!bundleMgr_->CheckIsSystemAppByUid(callerUid)) { + APP_LOGE("caller is not systemApp, callerUid %{public}d", callerUid); + return ERR_INVALID_VALUE; + } + APP_LOGI("userId value is %{public}d", userId); int uid = bundleMgr_->GetUidByBundleName(bundleName, userId); APP_LOGI("uid value is %{public}d", uid); @@ -451,7 +472,9 @@ int32_t AppMgrServiceInner::KillApplicationByUserId(const std::string &bundleNam void AppMgrServiceInner::ClearUpApplicationData(const std::string &bundleName, int32_t callerUid, pid_t callerPid) { BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); - ClearUpApplicationDataByUserId(bundleName, callerUid, callerPid, Constants::DEFAULT_USERID); + auto userId = GetUserIdByUid(callerUid); + APP_LOGI("userId:%{public}d", userId); + ClearUpApplicationDataByUserId(bundleName, callerUid, callerPid, userId); } void AppMgrServiceInner::ClearUpApplicationDataByUserId( @@ -646,7 +669,7 @@ std::shared_ptr AppMgrServiceInner::GetAppRunningRecordByPid(c std::shared_ptr AppMgrServiceInner::CreateAppRunningRecord(const sptr &token, const sptr &preToken, const std::shared_ptr &appInfo, const std::shared_ptr &abilityInfo, const std::string &processName, const BundleInfo &bundleInfo, - const HapModuleInfo &hapModuleInfo) + const HapModuleInfo &hapModuleInfo, const std::shared_ptr &want) { BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); if (!appRunningManager_) { @@ -658,7 +681,7 @@ std::shared_ptr AppMgrServiceInner::CreateAppRunningRecord(con } appRecord->SetEventHandler(eventHandler_); - appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, want); if (preToken) { auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token); @@ -700,10 +723,7 @@ void AppMgrServiceInner::UpdateAbilityState(const sptr &token, co APP_LOGE("token is null!"); return; } - if (state > AbilityState::ABILITY_STATE_BACKGROUND || state < AbilityState::ABILITY_STATE_FOREGROUND) { - APP_LOGE("state is not foreground or background!"); - return; - } + auto appRecord = GetAppRunningRecordByAbilityToken(token); if (!appRecord) { APP_LOGE("app is not exist!"); @@ -718,6 +738,20 @@ void AppMgrServiceInner::UpdateAbilityState(const sptr &token, co APP_LOGE("current state is already, no need update!"); return; } + auto type = abilityRecord->GetAbilityInfo()->type; + if (type == AppExecFwk::AbilityType::SERVICE && + (state == AbilityState::ABILITY_STATE_CREATE || + state == AbilityState::ABILITY_STATE_TERMINATED || + state == AbilityState::ABILITY_STATE_CONNECTED || + state == AbilityState::ABILITY_STATE_DISCONNECTED)) { + APP_LOGI("StateChangedNotifyObserver service type, state:%{public}d", static_cast(state)); + appRecord->StateChangedNotifyObserver(abilityRecord, static_cast(state), true); + return; + } + if (state > AbilityState::ABILITY_STATE_BACKGROUND || state < AbilityState::ABILITY_STATE_FOREGROUND) { + APP_LOGE("state is not foreground or background!"); + return; + } if (appRecord->GetState() == ApplicationState::APP_STATE_SUSPENDED) { appRecord->SetState(ApplicationState::APP_STATE_BACKGROUND); OptimizerAppStateChanged(appRecord, ApplicationState::APP_STATE_SUSPENDED); @@ -905,7 +939,7 @@ void AppMgrServiceInner::KillProcessesByUserId(int32_t userId) void AppMgrServiceInner::StartAbility(const sptr &token, const sptr &preToken, const std::shared_ptr &abilityInfo, const std::shared_ptr &appRecord, - const HapModuleInfo &hapModuleInfo) + const HapModuleInfo &hapModuleInfo, const std::shared_ptr &want) { BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); APP_LOGI("already create appRecord, just start ability"); @@ -936,7 +970,7 @@ void AppMgrServiceInner::StartAbility(const sptr &token, const sp } auto appInfo = std::make_shared(abilityInfo->applicationInfo); - appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, want); auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); if (!moduleRecord) { APP_LOGE("add moduleRecord failed"); @@ -1160,9 +1194,11 @@ void AppMgrServiceInner::OnAbilityStateChanged( void AppMgrServiceInner::StateChangedNotifyObserver(const AbilityStateData abilityStateData, bool isAbility) { std::lock_guard lockNotify(observerLock_); - APP_LOGD("bundle:%{public}s, ability:%{public}s, state:%{public}d, pid:%{public}d, uid:%{public}d", + APP_LOGD("bundle:%{public}s, ability:%{public}s, state:%{public}d, pid:%{public}d," + "uid:%{public}d, abilityType:%{public}d", abilityStateData.bundleName.c_str(), abilityStateData.abilityName.c_str(), - abilityStateData.abilityState, abilityStateData.pid, abilityStateData.uid); + abilityStateData.abilityState, abilityStateData.pid, abilityStateData.uid, + abilityStateData.abilityType); for (const auto &observer : appStateObservers_) { if (observer != nullptr) { if (isAbility) { @@ -1249,9 +1285,11 @@ void AppMgrServiceInner::StartProcess(const std::string &appName, const std::str startMsg.uid = (*bundleInfoIter).uid; startMsg.gid = (*bundleInfoIter).gid; startMsg.accessTokenId = (*bundleInfoIter).applicationInfo.accessTokenId; - startMsg.apl = bundleMgr_->GetAppPrivilegeLevel(bundleName); - APP_LOGD("StartProcess come, accessTokenId: %{public}d, apl: %{public}s", - startMsg.accessTokenId, startMsg.apl.c_str()); + startMsg.apl = (*bundleInfoIter).applicationInfo.appPrivilegeLevel; + startMsg.bundleName = bundleName; + startMsg.renderParam = RENDER_PARAM; + APP_LOGD("StartProcess come, accessTokenId: %{public}d, apl: %{public}s, bundleName: %{public}s", + startMsg.accessTokenId, startMsg.apl.c_str(), bundleName.c_str()); bundleMgrResult = bundleMgr_->GetBundleGidsByUid(bundleName, uid, startMsg.gids); if (!bundleMgrResult) { @@ -1272,6 +1310,7 @@ void AppMgrServiceInner::StartProcess(const std::string &appName, const std::str APP_LOGI("newPid:%{public}d uid:%{public}d", pid, startMsg.uid); appRecord->GetPriorityObject()->SetPid(pid); appRecord->SetUid(startMsg.uid); + appRecord->SetStartMsg(startMsg); OptimizerAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE); appRecord->SetAppMgrServiceInner(weak_from_this()); OnAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE); @@ -1340,11 +1379,23 @@ void AppMgrServiceInner::ClearRecentAppList() appProcessManager_->ClearRecentAppList(); } -void AppMgrServiceInner::OnRemoteDied(const wptr &remote) +void AppMgrServiceInner::OnRemoteDied(const wptr &remote, bool isRenderProcess) { APP_LOGE("On remote died."); + if (isRenderProcess) { + OnRenderRemoteDied(remote); + return; + } + auto appRecord = appRunningManager_->OnRemoteDied(remote); if (appRecord) { + // clear uri permission + auto upmClient = AAFwk::UriPermissionManagerClient::GetInstance(); + auto appInfo = appRecord->GetApplicationInfo(); + if (appInfo && upmClient) { + upmClient->RemoveUriPermission(appInfo->accessTokenId); + } + for (const auto &item : appRecord->GetAbilities()) { const auto &abilityRecord = item.second; OptimizerAbilityStateChanged(abilityRecord, AbilityState::ABILITY_STATE_TERMINATED); @@ -1354,6 +1405,13 @@ void AppMgrServiceInner::OnRemoteDied(const wptr &remote) OptimizerAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED); RemoveAppFromRecentListById(appRecord->GetRecordId()); OnProcessDied(appRecord); + + // kill render if exist. + auto renderRecord = appRecord->GetRenderRecord(); + if (renderRecord && renderRecord->GetPid() > 0) { + APP_LOGD("Kill render process when webviehost died."); + KillProcessByPid(renderRecord->GetPid()); + } } if (appRecord && appRecord->IsKeepAliveApp()) { @@ -1720,9 +1778,23 @@ void AppMgrServiceInner::StartResidentProcess(const std::vector &inf } for (auto &bundle : infos) { - auto processName = - bundle.applicationInfo.process.empty() ? bundle.applicationInfo.bundleName : bundle.applicationInfo.process; + auto processName = bundle.applicationInfo.process.empty() ? + bundle.applicationInfo.bundleName : bundle.applicationInfo.process; APP_LOGI("processName = [%{public}s]", processName.c_str()); + + bool allElementNameEmpty = true; + for (auto hapModuleInfo : bundle.hapModuleInfos) { + if (!hapModuleInfo.mainElementName.empty()) { + // already start main element and process, no need start process again + allElementNameEmpty = false; + break; + } + } + if (!allElementNameEmpty) { + APP_LOGW("processName [%{public}s] Already exists ", processName.c_str()); + continue; + } + // Inspection records auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist( bundle.applicationInfo.name, processName, bundle.applicationInfo.uid, bundle); @@ -2032,7 +2104,7 @@ void AppMgrServiceInner::StartSpecifiedAbility(const AAFwk::Want &want, const Ap APP_LOGE("abilityInfoPtr is nullptr."); return; } - MakeProcessName(processName, abilityInfoPtr, appInfo); + MakeProcessName(processName, abilityInfoPtr, appInfo, hapModuleInfo); std::vector hapModules; hapModules.emplace_back(hapModuleInfo); @@ -2125,11 +2197,146 @@ void AppMgrServiceInner::GetGlobalConfiguration() auto language = OHOS::Global::I18n::LocaleConfig::GetSystemLanguage(); APP_LOGI("current global language is : %{public}s", language.c_str()); configuration_->AddItem(GlobalConfigurationKey::SYSTEM_LANGUAGE, language); + + // Assign to default colormode "light" + APP_LOGI("current global colormode is : %{public}s", ConfigurationInner::COLOR_MODE_LIGHT.c_str()); + configuration_->AddItem(GlobalConfigurationKey::SYSTEM_COLORMODE, ConfigurationInner::COLOR_MODE_LIGHT); } std::shared_ptr AppMgrServiceInner::GetConfiguration() { return configuration_; } + +int AppMgrServiceInner::GetAbilityRecordsByProcessID(const int pid, std::vector> &tokens) +{ + auto appRecord = GetAppRunningRecordByPid(pid); + if (!appRecord) { + APP_LOGE("no such appRecord"); + return ERR_NAME_NOT_FOUND; + } + for (auto &item : appRecord->GetAbilities()) { + tokens.emplace_back(item.first); + } + + return ERR_OK; +} + +int AppMgrServiceInner::StartRenderProcess(const pid_t hostPid, const std::string &renderParam, + int32_t ipcFd, int32_t sharedFd, pid_t &renderPid) +{ + APP_LOGI("start render process, webview hostpid:%{public}d", hostPid); + if (hostPid <= 0 || renderParam.empty() || ipcFd <= 0 || sharedFd <= 0) { + APP_LOGE("invalid param, hostPid:%{public}d, renderParam:%{public}s, ipcFd:%{public}d, sharedFd:%{public}d", + hostPid, renderParam.c_str(), ipcFd, sharedFd); + return ERR_INVALID_VALUE; + } + + if (!appRunningManager_) { + APP_LOGE("appRunningManager_ is , not start render process"); + return ERR_INVALID_VALUE; + } + + auto appRecord = GetAppRunningRecordByPid(hostPid); + if (!appRecord) { + APP_LOGE("no such appRecord, hostpid:%{public}d", hostPid); + return ERR_INVALID_VALUE; + } + + auto renderRecord = appRecord->GetRenderRecord(); + if (renderRecord) { + APP_LOGW("already exit render process,do not request again, renderPid:%{public}d", renderRecord->GetPid()); + renderPid = renderRecord->GetPid(); + return ERR_ALREADY_EXIST_RENDER; + } + + renderRecord = RenderRecord::CreateRenderRecord(hostPid, renderParam, ipcFd, sharedFd, appRecord); + if (!renderRecord) { + APP_LOGE("create render record failed, hostpid:%{public}d", hostPid); + return ERR_INVALID_VALUE; + } + + return StartRenderProcessImpl(renderRecord, appRecord, renderPid); +} + +void AppMgrServiceInner::AttachRenderProcess(const pid_t pid, const sptr &scheduler) +{ + APP_LOGD("attach render process start"); + if (pid <= 0) { + APP_LOGE("invalid render process pid:%{public}d", pid); + return; + } + if (!scheduler) { + APP_LOGE("render scheduler is null"); + return; + } + + if (!appRunningManager_) { + APP_LOGE("appRunningManager_ is null"); + return; + } + + APP_LOGI("attach render process pid:%{public}d", pid); + auto appRecord = appRunningManager_->GetAppRunningRecordByRenderPid(pid); + if (!appRecord) { + APP_LOGE("no such app Record, pid:%{public}d", pid); + return; + } + + auto renderRecord = appRecord->GetRenderRecord(); + if (!renderRecord) { + APP_LOGE("no such render Record, pid:%{public}d", pid); + return; + } + + sptr appDeathRecipient = new AppDeathRecipient(); + appDeathRecipient->SetEventHandler(eventHandler_); + appDeathRecipient->SetAppMgrServiceInner(shared_from_this()); + appDeathRecipient->SetIsRenderProcess(true); + renderRecord->SetScheduler(scheduler); + renderRecord->SetDeathRecipient(appDeathRecipient); + renderRecord->RegisterDeathRecipient(); + + // notify fd to render process + scheduler->NotifyBrowserFd(renderRecord->GetIpcFd(), renderRecord->GetSharedFd()); +} + +int AppMgrServiceInner::StartRenderProcessImpl(const std::shared_ptr &renderRecord, + const std::shared_ptr appRecord, pid_t &renderPid) +{ + if (!renderRecord || !appRecord) { + APP_LOGE("renderRecord or appRecord is nullptr."); + return ERR_INVALID_VALUE; + } + + auto webviewSpawnClient = remoteClientManager_->GetWebviewSpawnClient(); + if (!webviewSpawnClient) { + APP_LOGE("webviewSpawnClient is null"); + return ERR_INVALID_VALUE; + } + + AppSpawnStartMsg startMsg = appRecord->GetStartMsg(); + startMsg.renderParam = renderRecord->GetRenderParam(); + pid_t pid = 0; + ErrCode errCode = webviewSpawnClient->StartProcess(startMsg, pid); + if (FAILED(errCode)) { + APP_LOGE("failed to spawn new render process, errCode: %{public}08x", errCode); + return ERR_INVALID_VALUE; + } + renderPid = pid; + appRecord->SetRenderRecord(renderRecord); + renderRecord->SetPid(pid); + APP_LOGI("start render process successed, hostPid:%{public}d, pid:%{public}d uid:%{public}d", + renderRecord->GetHostPid(), pid, startMsg.uid); + return 0; +} + +void AppMgrServiceInner::OnRenderRemoteDied(const wptr &remote) +{ + APP_LOGE("On render remote died."); + if (appRunningManager_) { + appRunningManager_->OnRemoteRenderDied(remote); + } +} } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/app_running_manager.cpp b/services/appmgr/src/app_running_manager.cpp index db78229fbcebcf538aaf86d07c1ab8a593253b9c..3b0bc1dd4cc3e08029b08bb583a6f5b5e78c6a2f 100644 --- a/services/appmgr/src/app_running_manager.cpp +++ b/services/appmgr/src/app_running_manager.cpp @@ -86,8 +86,8 @@ std::shared_ptr AppRunningManager::CheckAppRunningRecordIsExis if (jointUserId.empty()) { for (const auto &item : appRunningRecordMap_) { const auto &appRecord = item.second; - APP_LOGI("appRecord->GetProcessName() : %{public}s", appRecord->GetProcessName().c_str()); if (appRecord && appRecord->GetProcessName() == processName && !(appRecord->IsTerminating())) { + APP_LOGI("appRecord->GetProcessName() : %{public}s", appRecord->GetProcessName().c_str()); auto appInfoList = appRecord->GetAppInfoList(); APP_LOGI("appInfoList : %{public}zu", appInfoList.size()); auto isExist = [&appName, &uid](const std::shared_ptr &appInfo) { @@ -217,15 +217,16 @@ std::shared_ptr AppRunningManager::OnRemoteDied(const wptrsecond; + if (iter == appRunningRecordMap_.end()) { + APP_LOGE("remote is not exist in the map."); + return nullptr; + } + auto appRecord = iter->second; + if (appRecord != nullptr) { appRecord->SetApplicationClient(nullptr); - appRunningRecordMap_.erase(iter); - if (appRecord) { - return appRecord; - } } - return nullptr; + appRunningRecordMap_.erase(iter); + return appRecord; } const std::map> &AppRunningManager::GetAppRunningRecordMap() @@ -461,5 +462,48 @@ void AppRunningManager::UpdateConfiguration(const Configuration &config) } } } + +std::shared_ptr AppRunningManager::GetAppRunningRecordByRenderPid(const pid_t pid) +{ + std::lock_guard guard(lock_); + auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&pid](const auto &pair) { + auto renderRecord = pair.second->GetRenderRecord(); + return renderRecord && renderRecord->GetPid() == pid; + }); + return ((iter == appRunningRecordMap_.end()) ? nullptr : iter->second); +} + +void AppRunningManager::OnRemoteRenderDied(const wptr &remote) +{ + std::lock_guard guard(lock_); + if (remote == nullptr) { + APP_LOGE("remote is null"); + return; + } + sptr object = remote.promote(); + if (!object) { + APP_LOGE("promote failed."); + return; + } + + const auto &it = + std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&object](const auto &pair) { + if (!pair.second) { + return false; + } + + auto renderRecord = pair.second->GetRenderRecord(); + if (!renderRecord) { + return false; + } + + auto scheduler = renderRecord->GetScheduler(); + return scheduler && scheduler->AsObject() == object; + }); + if (it != appRunningRecordMap_.end()) { + auto appRecord = it->second; + appRecord->SetRenderRecord(nullptr); + } +} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/src/app_running_record.cpp b/services/appmgr/src/app_running_record.cpp index 0d03d9c331d9554fc996f0112d96e2cb5c0251c2..fceaaec9b47925c303199407a050c3c41721238e 100644 --- a/services/appmgr/src/app_running_record.cpp +++ b/services/appmgr/src/app_running_record.cpp @@ -21,11 +21,97 @@ namespace OHOS { namespace AppExecFwk { int64_t AppRunningRecord::appEventId_ = 0; + +RenderRecord::RenderRecord(pid_t hostPid, const std::string& renderParam, + int32_t ipcFd, int32_t sharedFd, const std::shared_ptr &host) + : hostPid_(hostPid), renderParam_(renderParam), ipcFd_(ipcFd), sharedFd_(sharedFd), host_(host) +{} + +RenderRecord::~RenderRecord() +{} + +std::shared_ptr RenderRecord::CreateRenderRecord(pid_t hostPid, const std::string& renderParam, + int32_t ipcFd, int32_t sharedFd, const std::shared_ptr &host) +{ + if (hostPid <= 0 || renderParam.empty() || ipcFd <= 0 || sharedFd <= 0 || !host) { + return nullptr; + } + + auto renderRecord = std::make_shared(hostPid, renderParam, ipcFd, sharedFd, host); + if (!renderRecord) { + APP_LOGE("create render record failed, hostPid:%{public}d.", hostPid); + return nullptr; + } + + return renderRecord; +} + +void RenderRecord::SetPid(pid_t pid) +{ + pid_ = pid; +} + +pid_t RenderRecord::GetPid() +{ + return pid_; +} + +pid_t RenderRecord::GetHostPid() +{ + return hostPid_; +} + +std::string RenderRecord::GetRenderParam() +{ + return renderParam_; +} + +int32_t RenderRecord::GetIpcFd() +{ + return ipcFd_; +} + +int32_t RenderRecord::GetSharedFd() +{ + return sharedFd_; +} + +std::shared_ptr RenderRecord::GetHostRecord() +{ + return host_.lock(); +} + +sptr RenderRecord::GetScheduler() +{ + return renderScheduler_; +} + +void RenderRecord::SetScheduler(const sptr &scheduler) +{ + renderScheduler_ = scheduler; +} + +void RenderRecord::SetDeathRecipient(const sptr recipient) +{ + deathRecipient_ = recipient; +} + +void RenderRecord::RegisterDeathRecipient() +{ + if (renderScheduler_ && deathRecipient_) { + auto obj = renderScheduler_->AsObject(); + if (obj) { + obj->AddDeathRecipient(deathRecipient_); + } + } +} + AppRunningRecord::AppRunningRecord( const std::shared_ptr &info, const int32_t recordId, const std::string &processName) : appRecordId_(recordId), processName_(processName) { if (info) { + appInfo_ = info; mainBundleName_ = info->bundleName; isLauncherApp_ = info->isLauncherApp; isClonedApp_ = info->isCloned; @@ -383,13 +469,13 @@ void AppRunningRecord::AddModules( } for (auto &iter : moduleInfos) { - AddModule(appInfo, nullptr, nullptr, iter); + AddModule(appInfo, nullptr, nullptr, iter, nullptr); } } void AppRunningRecord::AddModule(const std::shared_ptr &appInfo, const std::shared_ptr &abilityInfo, const sptr &token, - const HapModuleInfo &hapModuleInfo) + const HapModuleInfo &hapModuleInfo, const std::shared_ptr &want) { APP_LOGI("Add module."); @@ -427,7 +513,7 @@ void AppRunningRecord::AddModule(const std::shared_ptr &appInfo APP_LOGE("abilityinfo or token is nullptr"); return; } - moduleRecord->AddAbility(token, abilityInfo); + moduleRecord->AddAbility(token, abilityInfo, want); return; } @@ -462,6 +548,7 @@ void AppRunningRecord::StateChangedNotifyObserver( abilityStateData.abilityState = state; abilityStateData.uid = ability->GetAbilityInfo()->applicationInfo.uid; abilityStateData.token = ability->GetToken(); + abilityStateData.abilityType = static_cast(ability->GetAbilityInfo()->type); if (isAbility && ability->GetAbilityInfo() != nullptr && ability->GetAbilityInfo()->type == AbilityType::EXTENSION) { @@ -907,5 +994,25 @@ void AppRunningRecord::UpdateConfiguration(const Configuration &config) } appLifeCycleDeal_->UpdateConfiguration(config); } + +void AppRunningRecord::SetRenderRecord(const std::shared_ptr &record) +{ + renderRecord_ = record; +} + +std::shared_ptr AppRunningRecord::GetRenderRecord() +{ + return renderRecord_; +} + +void AppRunningRecord::SetStartMsg(const AppSpawnStartMsg &msg) +{ + startMsg_ = msg; +} + +AppSpawnStartMsg AppRunningRecord::GetStartMsg() +{ + return startMsg_; +} } // namespace AppExecFwk -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/src/app_spawn_client.cpp b/services/appmgr/src/app_spawn_client.cpp index 2229827afac0e8e054b1183e63dd9ab0e67671f6..521653972ab1f251bc01164d784f51acccfd81c8 100644 --- a/services/appmgr/src/app_spawn_client.cpp +++ b/services/appmgr/src/app_spawn_client.cpp @@ -25,9 +25,9 @@ const int32_t CONNECT_RETRY_DELAY = 200 * 1000; // 200ms const int32_t CONNECT_RETRY_MAX_TIMES = 15; } // namespace -AppSpawnClient::AppSpawnClient() +AppSpawnClient::AppSpawnClient(bool isWebViewSpawn) { - socket_ = std::make_shared(); + socket_ = std::make_shared(isWebViewSpawn); state_ = SpawnConnectionState::STATE_NOT_CONNECT; } diff --git a/services/appmgr/src/app_spawn_msg_wrapper.cpp b/services/appmgr/src/app_spawn_msg_wrapper.cpp index 0864799d66a1ae78765bbbfb06fb57c7dbb94e64..78a386cba28d0a6ec2a200f89fd64d4dbdcbeb54 100644 --- a/services/appmgr/src/app_spawn_msg_wrapper.cpp +++ b/services/appmgr/src/app_spawn_msg_wrapper.cpp @@ -61,6 +61,10 @@ bool AppSpawnMsgWrapper::AssembleMsg(const AppSpawnStartMsg &startMsg) APP_LOGE("failed to transform apl!"); return false; } + if (strcpy_s(msg_->bundleName, sizeof(msg_->bundleName), startMsg.bundleName.c_str()) != EOK) { + APP_LOGE("failed to transform bundleName!"); + return false; + } isValid_ = true; DumpMsg(); diff --git a/services/appmgr/src/app_spawn_socket.cpp b/services/appmgr/src/app_spawn_socket.cpp index 327b5255cee3cbc79a513c0b3027c839cc3fbb39..4714dd47d1e402dd881e170eb0eb97cd4836d674 100644 --- a/services/appmgr/src/app_spawn_socket.cpp +++ b/services/appmgr/src/app_spawn_socket.cpp @@ -19,11 +19,15 @@ namespace OHOS { namespace AppExecFwk { -// arg "AppSpawn" cannot be defined as string object since REGISTER_SYSTEM_ABILITY will +// arg "AppSpawn" or "WebViewSpawn" cannot be defined as string object since REGISTER_SYSTEM_ABILITY will // firstly start without init this string object, which leads to error. -AppSpawnSocket::AppSpawnSocket() : clientSocket_(std::make_unique("AppSpawn")) -{} +AppSpawnSocket::AppSpawnSocket(bool isWebViewSpawn) +{ + clientSocket_ = isWebViewSpawn ? + std::make_unique("/dev/unix/socket/WebViewSpawn") : + std::make_unique("AppSpawn"); +} AppSpawnSocket::~AppSpawnSocket() {} diff --git a/services/appmgr/src/module_running_record.cpp b/services/appmgr/src/module_running_record.cpp index 0c9e9b927bf5c322addea1be0f081399e305e5fd..ce9d15336af132b4a7faef33ba0dff6f09425b89 100644 --- a/services/appmgr/src/module_running_record.cpp +++ b/services/appmgr/src/module_running_record.cpp @@ -57,8 +57,8 @@ std::shared_ptr ModuleRunningRecord::GetAbilityRunningReco return nullptr; } -std::shared_ptr ModuleRunningRecord::AddAbility( - const sptr &token, const std::shared_ptr &abilityInfo) +std::shared_ptr ModuleRunningRecord::AddAbility(const sptr &token, + const std::shared_ptr &abilityInfo, const std::shared_ptr &want) { APP_LOGI("Add ability."); if (!token || !abilityInfo) { @@ -70,6 +70,7 @@ std::shared_ptr ModuleRunningRecord::AddAbility( return nullptr; } auto abilityRecord = std::make_shared(abilityInfo, token); + abilityRecord->SetWant(want); abilities_.emplace(token, abilityRecord); return abilityRecord; } diff --git a/services/appmgr/src/remote_client_manager.cpp b/services/appmgr/src/remote_client_manager.cpp index 711b395c0d57de2491df62c07cafaf88066a5ff5..8184aa67b9f0f65047e07308d11d6c209501ee1b 100644 --- a/services/appmgr/src/remote_client_manager.cpp +++ b/services/appmgr/src/remote_client_manager.cpp @@ -22,7 +22,8 @@ namespace OHOS { namespace AppExecFwk { -RemoteClientManager::RemoteClientManager() : appSpawnClient_(std::make_shared()) +RemoteClientManager::RemoteClientManager() + : appSpawnClient_(std::make_shared()), webviewSpawnClient_(std::make_shared(true)) {} RemoteClientManager::~RemoteClientManager() @@ -59,5 +60,10 @@ void RemoteClientManager::SetBundleManager(sptr bundleManager) { bundleManager_ = bundleManager; } + +std::shared_ptr RemoteClientManager::GetWebviewSpawnClient() +{ + return webviewSpawnClient_; +} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/test/BUILD.gn b/services/appmgr/test/BUILD.gn index 4da5d39b479fd84d3cb1c7f5785ad2d8f9080fbc..845e14df8fdd7ae77cc8ca7e7ddd927634baee5a 100644 --- a/services/appmgr/test/BUILD.gn +++ b/services/appmgr/test/BUILD.gn @@ -35,6 +35,7 @@ ohos_source_set("appmgr_test_source") { testonly = true sources = [ + "${aafwk_path}/frameworks/kits/content/cpp/src/ohos/aafwk/content/element_name.cpp", "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/app_launch_data.cpp", "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/app_mgr_proxy.cpp", "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/app_mgr_stub.cpp", @@ -48,15 +49,17 @@ ohos_source_set("appmgr_test_source") { "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp", "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/process_info.cpp", "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/profile.cpp", + "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/render_scheduler_host.cpp", + "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/render_scheduler_proxy.cpp", + "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/running_process_info.cpp", "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp", "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base/src/application_info.cpp", "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base/src/bundle_info.cpp", "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base/src/bundle_user_info.cpp", - "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base/src/element_name.cpp", - "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base/src/running_process_info.cpp", ] include_dirs = [ + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", "//third_party/json/include", "${aafwk_path}/services/appmgr/include/lmks", "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core/include", diff --git a/services/appmgr/test/mock/include/mock_ams_mgr_scheduler.h b/services/appmgr/test/mock/include/mock_ams_mgr_scheduler.h index c4082c886801cec9c20b425ad972af134506042d..b7d66d7b147215022fedf90340214b74408a58ac 100644 --- a/services/appmgr/test/mock/include/mock_ams_mgr_scheduler.h +++ b/services/appmgr/test/mock/include/mock_ams_mgr_scheduler.h @@ -23,9 +23,10 @@ namespace OHOS { namespace AppExecFwk { class MockAmsMgrScheduler : public AmsMgrStub { public: - MOCK_METHOD4(LoadAbility, + MOCK_METHOD5(LoadAbility, void(const sptr &token, const sptr &preToken, - const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo)); + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo, + const std::shared_ptr &want)); MOCK_METHOD5(AbilityBehaviorAnalysis, void(const sptr &token, const sptr &preToken, const int32_t visibility, const int32_t perceptibility, const int32_t connectionState)); @@ -49,7 +50,7 @@ public: MOCK_METHOD1(GetConfiguration, int(AppExecFwk::Configuration &)); MockAmsMgrScheduler() : AmsMgrStub() {}; - virtual ~MockAmsMgrScheduler(){}; + virtual ~MockAmsMgrScheduler() {}; virtual void RegisterAppStateCallback(const sptr &callback) override { callback->OnAbilityRequestDone(nullptr, AbilityState::ABILITY_STATE_BACKGROUND); diff --git a/services/appmgr/test/mock/include/mock_app_mgr_service.h b/services/appmgr/test/mock/include/mock_app_mgr_service.h index 7447c7551abc2593434e5ec6bc1af6ae090d515e..dbd56b7565bd12d64f920a83124a6a28269bcbfb 100644 --- a/services/appmgr/test/mock/include/mock_app_mgr_service.h +++ b/services/appmgr/test/mock/include/mock_app_mgr_service.h @@ -24,9 +24,10 @@ namespace OHOS { namespace AppExecFwk { class MockAppMgrService : public AppMgrStub { public: - MOCK_METHOD4(LoadAbility, + MOCK_METHOD5(LoadAbility, void(const sptr &token, const sptr &preToken, - const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo)); + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo, + const std::shared_ptr &want)); MOCK_METHOD1(TerminateAbility, void(const sptr &token)); MOCK_METHOD2(UpdateAbilityState, void(const sptr &token, const AbilityState state)); MOCK_METHOD1(AttachApplication, void(const sptr &app)); @@ -47,10 +48,13 @@ public: MOCK_METHOD2(GetSystemMemoryAttr, void(SystemMemoryAttr &memoryInfo, std::string &strConfig)); MOCK_METHOD0(StartupResidentProcess, void()); MOCK_METHOD1(AddAbilityStageDone, void(const int32_t recordId)); + MOCK_METHOD4(StartRenderProcess, int(const std::string&, int32_t, int32_t, pid_t&)); + MOCK_METHOD1(AttachRenderProcess, void(const sptr &renderScheduler)); MOCK_METHOD1(RegisterApplicationStateObserver, int32_t(const sptr &observer)); MOCK_METHOD1(UnregisterApplicationStateObserver, int32_t(const sptr &observer)); MOCK_METHOD3(ScheduleAcceptWantDone, void(const int32_t recordId, const AAFwk::Want &want, const std::string &flag)); + MOCK_METHOD2(GetAbilityRecordsByProcessID, int(const int pid, std::vector> &tokens)); virtual int StartUserTestProcess(const AAFwk::Want &want, const sptr &observer, const BundleInfo &bundleInfo) diff --git a/services/appmgr/test/mock/include/mock_app_mgr_service_inner.h b/services/appmgr/test/mock/include/mock_app_mgr_service_inner.h index 5b0ceb1b50b0174807e1aebc8929968dcfca069e..073ea769cdf527cff03c8f81e5953fac5303681c 100644 --- a/services/appmgr/test/mock/include/mock_app_mgr_service_inner.h +++ b/services/appmgr/test/mock/include/mock_app_mgr_service_inner.h @@ -30,9 +30,10 @@ public: virtual ~MockAppMgrServiceInner() {} - MOCK_METHOD4(LoadAbility, + MOCK_METHOD5(LoadAbility, void(const sptr &token, const sptr &preToken, - const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo)); + const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo, + const std::shared_ptr &want)); MOCK_METHOD2(AttachApplication, void(const pid_t pid, const sptr &app)); MOCK_METHOD1(ApplicationForegrounded, void(const int32_t recordId)); MOCK_METHOD1(ApplicationBackgrounded, void(const int32_t recordId)); diff --git a/services/appmgr/test/mock/include/mock_app_scheduler.h b/services/appmgr/test/mock/include/mock_app_scheduler.h index b3e90820909acd251eb12d2d96749d449009fe97..1b45cb5e14108ad9c3c51fd58684a4ddebb1ccef 100644 --- a/services/appmgr/test/mock/include/mock_app_scheduler.h +++ b/services/appmgr/test/mock/include/mock_app_scheduler.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_UNITEST_AMS_APP_LIFE_CYCLE_TEST_MOCK_APP_SCHEDULER_H -#define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_UNITEST_AMS_APP_LIFE_CYCLE_TEST_MOCK_APP_SCHEDULER_H +#ifndef FOUNDATION_APPEXECFWK_TEST_UNITEST_APP_LIFE_CYCLE_TEST_MOCK_APP_SCHEDULER_H +#define FOUNDATION_APPEXECFWK_TEST_UNITEST_APP_LIFE_CYCLE_TEST_MOCK_APP_SCHEDULER_H #include "gmock/gmock.h" #include "refbase.h" @@ -32,7 +32,8 @@ public: MOCK_METHOD0(ScheduleBackgroundApplication, void()); MOCK_METHOD0(ScheduleTerminateApplication, void()); MOCK_METHOD2(ScheduleLaunchApplication, void(const AppLaunchData &, const Configuration &config)); - MOCK_METHOD2(ScheduleLaunchAbility, void(const AbilityInfo &, const sptr &)); + MOCK_METHOD3(ScheduleLaunchAbility, void(const AbilityInfo &, const sptr &, + const std::shared_ptr &)); MOCK_METHOD1(ScheduleCleanAbility, void(const sptr &)); MOCK_METHOD1(ScheduleProfileChanged, void(const Profile &)); MOCK_METHOD1(ScheduleConfigurationUpdated, void(const Configuration &config)); @@ -44,4 +45,4 @@ public: }; } // namespace AppExecFwk } // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_UNITEST_AMS_APP_LIFE_CYCLE_TEST_MOCK_APP_SCHEDULER_CLIENT_H +#endif // FOUNDATION_APPEXECFWK_TEST_UNITEST_APP_LIFE_CYCLE_TEST_MOCK_APP_SCHEDULER_H diff --git a/services/appmgr/test/mock/include/mock_app_spawn_socket.h b/services/appmgr/test/mock/include/mock_app_spawn_socket.h index 4a14ec5ee108c0857ada0934989c1e03131a748a..ea102b63e8e27c3e4a782bfe91be40040c876766 100644 --- a/services/appmgr/test/mock/include/mock_app_spawn_socket.h +++ b/services/appmgr/test/mock/include/mock_app_spawn_socket.h @@ -26,7 +26,7 @@ namespace OHOS { namespace AppExecFwk { class MockAppSpawnSocket : public AppSpawnSocket { public: - MockAppSpawnSocket() = default; + MockAppSpawnSocket() : AppSpawnSocket(false) {} virtual ~MockAppSpawnSocket() = default; MOCK_METHOD0(OpenAppSpawnConnection, ErrCode()); diff --git a/services/appmgr/test/mock/include/mock_application.h b/services/appmgr/test/mock/include/mock_application.h index eae33a3870ac6f31f3d764340d1019b132a680d9..b537cb26e262e83e83d2a983c260b41a6a5dc800 100644 --- a/services/appmgr/test/mock/include/mock_application.h +++ b/services/appmgr/test/mock/include/mock_application.h @@ -29,7 +29,8 @@ public: MOCK_METHOD1(ScheduleShrinkMemory, void(const int)); MOCK_METHOD0(ScheduleLowMemory, void()); MOCK_METHOD2(ScheduleLaunchApplication, void(const AppLaunchData &, const Configuration &config)); - MOCK_METHOD2(ScheduleLaunchAbility, void(const AbilityInfo &, const sptr &)); + MOCK_METHOD3(ScheduleLaunchAbility, void(const AbilityInfo &, const sptr &, + const std::shared_ptr &)); MOCK_METHOD1(ScheduleCleanAbility, void(const sptr &)); MOCK_METHOD1(ScheduleProfileChanged, void(const Profile &)); MOCK_METHOD1(ScheduleConfigurationUpdated, void(const Configuration &)); diff --git a/services/appmgr/test/mock/include/mock_bundle_manager.h b/services/appmgr/test/mock/include/mock_bundle_manager.h index 8a12f9ad9ab41ae72f8d92f04902220038b4af49..0ffda0cf9d4dcb35969c67a21916e634b08e6151 100755 --- a/services/appmgr/test/mock/include/mock_bundle_manager.h +++ b/services/appmgr/test/mock/include/mock_bundle_manager.h @@ -44,7 +44,6 @@ public: bool(const std::string &bundleName, const std::string &permission, const int userId)); MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); - MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); @@ -175,12 +174,6 @@ public: { return true; }; - // clears cache data of a specified application. - virtual bool CleanBundleCacheFiles( - const std::string &bundleName, const sptr &cleanCacheCallback) override - { - return true; - }; virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0) override { return true; @@ -237,7 +230,6 @@ public: class BundleMgrStub : public IRemoteStub { public: - DECLARE_INTERFACE_DESCRIPTOR(u"IBundleMgr"); virtual int OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; }; @@ -254,7 +246,6 @@ public: bool(const std::string &bundleName, const std::string &permission, const int userId)); MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); - MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); @@ -349,12 +340,6 @@ public: { return true; }; - // clears cache data of a specified application. - virtual bool CleanBundleCacheFiles( - const std::string &bundleName, const sptr &cleanCacheCallback) override - { - return true; - }; virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override { @@ -390,10 +375,6 @@ public: { return true; }; - virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override - { - return true; - }; virtual bool GetAllFormsInfo(std::vector &formInfos) override { return true; @@ -422,7 +403,8 @@ public: return true; } virtual bool NotifyAbilityLifeStatus( - const std::string &bundleName, const std::string &abilityName, const int64_t launchTime, const int uid = 0) override + const std::string &bundleName, const std::string &abilityName, + const int64_t launchTime, const int uid = 0) override { return true; } diff --git a/services/appmgr/test/mock/src/mock_bundle_manager.cpp b/services/appmgr/test/mock/src/mock_bundle_manager.cpp index 562ad2b5c03a7068f6f2e11662a4e38e7b508365..ca3ec28c311c6baa4388604409ed6cb968bbdbc5 100644 --- a/services/appmgr/test/mock/src/mock_bundle_manager.cpp +++ b/services/appmgr/test/mock/src/mock_bundle_manager.cpp @@ -52,7 +52,6 @@ bool BundleMgrProxy::GetApplicationInfo( std::string BundleMgrProxy::GetAppType(const std::string &bundleName) { - GTEST_LOG_(INFO) << " BundleMgrProxy::GetAppTyp"; return "system"; } @@ -105,20 +104,17 @@ bool BundleMgrService::GetApplicationInfo( std::string BundleMgrService::GetAppType(const std::string &bundleName) { - GTEST_LOG_(INFO) << " BundleMgrService::GetAppType"; return "system"; } bool BundleMgrService::GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) { - GTEST_LOG_(INFO) << " BundleMgrService::GetHapModuleInfo"; hapModuleInfo.name = "Captain"; return true; } bool BundleMgrProxy::GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) { - GTEST_LOG_(INFO) << " BundleMgrService::GetHapModuleInfo"; hapModuleInfo.name = "Captain"; return true; } diff --git a/services/appmgr/test/unittest/ams_ability_running_record_test/BUILD.gn b/services/appmgr/test/unittest/ams_ability_running_record_test/BUILD.gn index 75e91bb61b607923d1d5cbe9c76f1a51edfe197c..f127a431a31988038533377c962cd64b49bc1fc8 100644 --- a/services/appmgr/test/unittest/ams_ability_running_record_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_ability_running_record_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -34,6 +34,7 @@ ohos_unittest("AmsAbilityRunningRecordTest") { sources = [ "${services_path}/appmgr/src/ability_running_record.cpp", + "${services_path}/appmgr/src/app_death_recipient.cpp", "${services_path}/appmgr/src/app_mgr_service_inner.cpp", "${services_path}/appmgr/src/app_running_record.cpp", "${services_path}/appmgr/src/app_spawn_client.cpp", @@ -53,6 +54,7 @@ ohos_unittest("AmsAbilityRunningRecordTest") { } deps = [ "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${innerkits_path}/uri_permission:uri_permission_mgr", "${services_path}/appmgr/test:appmgr_test_source", "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", diff --git a/services/appmgr/test/unittest/ams_ability_running_record_test/ams_ability_running_record_test.cpp b/services/appmgr/test/unittest/ams_ability_running_record_test/ams_ability_running_record_test.cpp index 632838ca199e3e02d8fbb734a60f11afe05ff666..5a94e32d6b4832cba5bcd0402fcb12b7f862c7aa 100644 --- a/services/appmgr/test/unittest/ams_ability_running_record_test/ams_ability_running_record_test.cpp +++ b/services/appmgr/test/unittest/ams_ability_running_record_test/ams_ability_running_record_test.cpp @@ -122,7 +122,7 @@ HWTEST_F(AmsAbilityRunningRecordTest, CreateAbilityRunningRecord_001, TestSize.L auto appInfo = std::make_shared(); appInfo->name = GetTestAppName(); - appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); @@ -151,7 +151,7 @@ HWTEST_F(AmsAbilityRunningRecordTest, CreateAbilityRunningRecord_002, TestSize.L auto appInfo = std::make_shared(); appInfo->name = GetTestAppName(); - appRunningRecord->AddModule(appInfo, nullptr, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, nullptr, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); @@ -181,14 +181,14 @@ HWTEST_F(AmsAbilityRunningRecordTest, CreateAbilityRunningRecord_003, TestSize.L auto appInfo = std::make_shared(); appInfo->name = GetTestAppName(); - appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto abilityRunningRecordFirst = moduleRecord->GetAbilityRunningRecordByToken(token); EXPECT_TRUE(abilityRunningRecordFirst != nullptr); EXPECT_EQ(abilityRunningRecordFirst, appRunningRecord->GetAbilityRunningRecordByToken(token)); - appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, nullptr); moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto abilityRunningRecordSecond = moduleRecord->GetAbilityRunningRecordByToken(token); @@ -217,7 +217,7 @@ HWTEST_F(AmsAbilityRunningRecordTest, UpdateAbilityRunningRecord_001, TestSize.L auto appInfo = std::make_shared(); appInfo->name = GetTestAppName(); - appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); @@ -260,7 +260,7 @@ HWTEST_F(AmsAbilityRunningRecordTest, UpdateAbilityRunningRecord_002, TestSize.L auto appInfo = std::make_shared(); appInfo->name = GetTestAppName(); - appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); @@ -294,7 +294,7 @@ HWTEST_F(AmsAbilityRunningRecordTest, UpdateAbilityRunningRecord_003, TestSize.L auto appInfo = std::make_shared(); appInfo->name = GetTestAppName(); - appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); @@ -334,7 +334,7 @@ HWTEST_F(AmsAbilityRunningRecordTest, UpdateAbilityRunningRecord_004, TestSize.L auto appInfo = std::make_shared(); appInfo->name = GetTestAppName(); - appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); @@ -373,12 +373,12 @@ HWTEST_F(AmsAbilityRunningRecordTest, UpdateAbilityRunningRecord_005, TestSize.L auto appInfo = std::make_shared(); appInfo->name = GetTestAppName(); - appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); - appRunningRecord->AddModule(appInfo, anotherAbilityInfo, anotherToken, hapModuleInfo); + appRunningRecord->AddModule(appInfo, anotherAbilityInfo, anotherToken, hapModuleInfo, nullptr); moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto anotherAbilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(anotherToken); @@ -418,12 +418,12 @@ HWTEST_F(AmsAbilityRunningRecordTest, UpdateAbilityRunningRecord_006, TestSize.L auto appInfo = std::make_shared(); appInfo->name = GetTestAppName(); - appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); - appRunningRecord->AddModule(appInfo, anotherAbilityInfo, anotherToken, hapModuleInfo); + appRunningRecord->AddModule(appInfo, anotherAbilityInfo, anotherToken, hapModuleInfo, nullptr); moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto anotherAbilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(anotherToken); @@ -468,12 +468,12 @@ HWTEST_F(AmsAbilityRunningRecordTest, UpdateAbilityRunningRecord_007, TestSize.L auto appInfo = std::make_shared(); appInfo->name = GetTestAppName(); - appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); - appRunningRecord->AddModule(appInfo, anotherAbilityInfo, anotherToken, hapModuleInfo); + appRunningRecord->AddModule(appInfo, anotherAbilityInfo, anotherToken, hapModuleInfo, nullptr); moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto anotherAbilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(anotherToken); @@ -514,7 +514,7 @@ HWTEST_F(AmsAbilityRunningRecordTest, DeleteAbilityRunningRecord_001, TestSize.L auto appInfo = std::make_shared(); appInfo->name = GetTestAppName(); - appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); @@ -548,7 +548,7 @@ HWTEST_F(AmsAbilityRunningRecordTest, DeleteAbilityRunningRecord_002, TestSize.L auto appInfo = std::make_shared(); appInfo->name = GetTestAppName(); - appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); @@ -585,12 +585,12 @@ HWTEST_F(AmsAbilityRunningRecordTest, DeleteAbilityRunningRecord_003, TestSize.L auto appInfo = std::make_shared(); appInfo->name = GetTestAppName(); - appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); - appRunningRecord->AddModule(appInfo, anotherAbilityInfo, anotherToken, hapModuleInfo); + appRunningRecord->AddModule(appInfo, anotherAbilityInfo, anotherToken, hapModuleInfo, nullptr); moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto anotherAbilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(anotherToken); @@ -657,7 +657,7 @@ HWTEST_F(AmsAbilityRunningRecordTest, SetGetAbilityRecord_001, TestSize.Level1) auto appInfo = std::make_shared(); appInfo->name = GetTestAppName(); - appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); diff --git a/services/appmgr/test/unittest/ams_app_death_recipient_test/BUILD.gn b/services/appmgr/test/unittest/ams_app_death_recipient_test/BUILD.gn index 359b7c19aad4a9d033416efa86bce9c170e73dcc..d405e30a4a4f3536600f929a5f36a1c000c0251b 100644 --- a/services/appmgr/test/unittest/ams_app_death_recipient_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_app_death_recipient_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -57,6 +57,7 @@ ohos_unittest("AppDeathRecipientTest") { deps = [ "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${innerkits_path}/uri_permission:uri_permission_mgr", "${services_path}/appmgr/test:appmgr_test_source", "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", diff --git a/services/appmgr/test/unittest/ams_app_death_recipient_test/ams_app_death_recipient_test.cpp b/services/appmgr/test/unittest/ams_app_death_recipient_test/ams_app_death_recipient_test.cpp index d87a6d53b79f04fb4a6683060f739e00993ecb61..ebdea2b92f030d9dd5aa624cb44ebc97e7538b40 100644 --- a/services/appmgr/test/unittest/ams_app_death_recipient_test/ams_app_death_recipient_test.cpp +++ b/services/appmgr/test/unittest/ams_app_death_recipient_test/ams_app_death_recipient_test.cpp @@ -141,7 +141,7 @@ sptr AppDeathRecipientTest::GetApp(int32_t pid, int size) std::shared_ptr mockClientstr(mockClientPtr); appMgrServiceInner_->SetAppSpawnClient(mockClientstr); - appMgrServiceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + appMgrServiceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); auto appRecord = GetAppRunningRecordByIndex(pid); diff --git a/services/appmgr/test/unittest/ams_app_life_cycle_test/BUILD.gn b/services/appmgr/test/unittest/ams_app_life_cycle_test/BUILD.gn index ba84cbcf5290ada75854d19490d8eb59f5da69b0..ed68460f4d3c6dae33951e1642fcf8fb5a08a4af 100644 --- a/services/appmgr/test/unittest/ams_app_life_cycle_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_app_life_cycle_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -28,6 +28,7 @@ ohos_unittest("AmsAppLifeCycleTest") { sources = [ "${services_path}/appmgr/src/ability_running_record.cpp", + "${services_path}/appmgr/src/app_death_recipient.cpp", "${services_path}/appmgr/src/app_lifecycle_deal.cpp", "${services_path}/appmgr/src/app_mgr_service_event_handler.cpp", "${services_path}/appmgr/src/app_mgr_service_inner.cpp", @@ -56,6 +57,7 @@ ohos_unittest("AmsAppLifeCycleTest") { deps = [ "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${innerkits_path}/uri_permission:uri_permission_mgr", "${services_path}/appmgr/test:appmgr_test_source", "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", diff --git a/services/appmgr/test/unittest/ams_app_life_cycle_test/ams_app_life_cycle_test.cpp b/services/appmgr/test/unittest/ams_app_life_cycle_test/ams_app_life_cycle_test.cpp index 2b4ebe05821c043a7d64bb327103a09bc60bf6a5..cafc0b13ea63d5cf19b0b2942014e2d906894b96 100644 --- a/services/appmgr/test/unittest/ams_app_life_cycle_test/ams_app_life_cycle_test.cpp +++ b/services/appmgr/test/unittest/ams_app_life_cycle_test/ams_app_life_cycle_test.cpp @@ -86,6 +86,7 @@ protected: std::shared_ptr serviceInner_; sptr mock_token_ = nullptr; sptr mockBundleMgr = nullptr; + std::shared_ptr runner_ = nullptr; std::shared_ptr handler_ = nullptr; sptr mockAppStateCallbackStub_ = nullptr; }; @@ -103,13 +104,17 @@ void AmsAppLifeCycleTest::SetUp() mockBundleMgr = new (std::nothrow) BundleMgrService(); serviceInner_->SetBundleManager(mockBundleMgr); - auto runner = EventRunner::Create("AmsAppLifeCycleTest"); - handler_ = std::make_shared(runner, serviceInner_); + runner_ = EventRunner::Create("AmsAppLifeCycleTest"); + handler_ = std::make_shared(runner_, serviceInner_); serviceInner_->SetEventHandler(handler_); } void AmsAppLifeCycleTest::TearDown() -{} +{ + serviceInner_ = nullptr; + handler_ = nullptr; + runner_.reset(); +} std::shared_ptr AmsAppLifeCycleTest::StartProcessAndLoadAbility(const sptr &token, const sptr &preToken, const std::shared_ptr &abilityInfo, @@ -120,7 +125,7 @@ std::shared_ptr AmsAppLifeCycleTest::StartProcessAndLoadAbilit serviceInner_->SetAppSpawnClient(mockClientPtr); - serviceInner_->LoadAbility(token, preToken, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, preToken, abilityInfo, appInfo, nullptr); BundleInfo bundleInfo; bundleInfo.appId = "com.ohos.test.helloworld_code123"; auto record = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist( @@ -186,7 +191,7 @@ TestApplicationPreRecord AmsAppLifeCycleTest::CreateTestApplicationRecord( bundleInfo.appId = "com.ohos.test.helloworld_code123"; std::shared_ptr appRecord = serviceInner_->CreateAppRunningRecord( - token, nullptr, appInfo, abilityInfo, "com.ohos.test.helloworld", bundleInfo, hapModuleInfo); + token, nullptr, appInfo, abilityInfo, "com.ohos.test.helloworld", bundleInfo, hapModuleInfo, nullptr); appRecord->SetEventHandler(handler_); EXPECT_NE(appRecord, nullptr); @@ -213,7 +218,7 @@ std::shared_ptr AmsAppLifeCycleTest::CreateTestApplicationAndS bundleInfo.appId = "com.ohos.test.helloworld_code123"; std::shared_ptr appRecord = serviceInner_->CreateAppRunningRecord( - token, nullptr, appInfo, abilityInfo, "AmsAppLifeCycleTest", bundleInfo, hapModuleInfo); + token, nullptr, appInfo, abilityInfo, "AmsAppLifeCycleTest", bundleInfo, hapModuleInfo, nullptr); EXPECT_NE(appRecord, nullptr); appRecord->SetEventHandler(handler_); @@ -282,7 +287,7 @@ std::shared_ptr AmsAppLifeCycleTest::AddNewAbility( { auto newAbilityInfo = GetAbilityInfoByIndex(index); sptr newToken = new (std::nothrow) MockAbilityToken(); - serviceInner_->LoadAbility(newToken, nullptr, newAbilityInfo, GetApplication()); + serviceInner_->LoadAbility(newToken, nullptr, newAbilityInfo, GetApplication(), nullptr); auto newAbilityRecord = appRecord->GetAbilityRunningRecordByToken(newToken); EXPECT_NE(newAbilityRecord, nullptr); return newAbilityRecord; @@ -296,7 +301,7 @@ std::shared_ptr AmsAppLifeCycleTest::AddNewAbility( auto app = GetApplication(); app->uid = uid; sptr newToken = new (std::nothrow) MockAbilityToken(); - serviceInner_->LoadAbility(newToken, nullptr, newAbilityInfo, app); + serviceInner_->LoadAbility(newToken, nullptr, newAbilityInfo, app, nullptr); auto newAbilityRecord = appRecord->GetAbilityRunningRecordByToken(newToken); EXPECT_NE(newAbilityRecord, nullptr); return newAbilityRecord; @@ -378,7 +383,7 @@ HWTEST_F(AmsAppLifeCycleTest, Init_001, TestSize.Level1) sptr mockAppScheduler = new MockAppScheduler(); sptr client = iface_cast(mockAppScheduler.GetRefPtr()); EXPECT_CALL(*mockAppScheduler, ScheduleLaunchApplication(_, _)).Times(1); - EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _, _)).Times(1); serviceInner_->AttachApplication(NEW_PID, client); EXPECT_NE(record->GetApplicationClient(), nullptr); @@ -405,7 +410,7 @@ HWTEST_F(AmsAppLifeCycleTest, Schedule_001, TestSize.Level1) AbilityState abilityState = abilityRecord->GetState(); ApplicationState appState = appRecord->GetState(); - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); EXPECT_EQ(abilityState, abilityRecord->GetState()); EXPECT_EQ(appState, appRecord->GetState()); } @@ -431,7 +436,7 @@ HWTEST_F(AmsAppLifeCycleTest, Schedule_002, TestSize.Level1) sptr client = iface_cast(mockAppScheduler.GetRefPtr()); EXPECT_CALL(*mockAppScheduler, ScheduleLaunchApplication(_, _)).Times(1); - EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _, _)).Times(1); serviceInner_->AttachApplication(NEW_PID, client); EXPECT_EQ(AbilityState::ABILITY_STATE_READY, abilityRecord->GetState()); @@ -465,7 +470,7 @@ HWTEST_F(AmsAppLifeCycleTest, Schedule_004, TestSize.Level1) { TestApplicationPreRecord testAppRecord = PrepareLoadTestAbilityAndApp(ApplicationState::APP_STATE_READY); testAppRecord.appRecord_->LaunchPendingAbilities(); - EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _, _)).Times(1); auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1"); EXPECT_EQ(AbilityState::ABILITY_STATE_READY, newAbilityRecord->GetState()); EXPECT_EQ(ApplicationState::APP_STATE_READY, testAppRecord.appRecord_->GetState()); @@ -482,7 +487,7 @@ HWTEST_F(AmsAppLifeCycleTest, Schedule_005, TestSize.Level1) { TestApplicationPreRecord testAppRecord = PrepareLoadTestAbilityAndApp(ApplicationState::APP_STATE_FOREGROUND); testAppRecord.appRecord_->LaunchPendingAbilities(); - EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _, _)).Times(1); auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1"); EXPECT_EQ(AbilityState::ABILITY_STATE_READY, newAbilityRecord->GetState()); EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppRecord.appRecord_->GetState()); @@ -499,7 +504,7 @@ HWTEST_F(AmsAppLifeCycleTest, Schedule_006, TestSize.Level1) { TestApplicationPreRecord testAppRecord = PrepareLoadTestAbilityAndApp(ApplicationState::APP_STATE_BACKGROUND); testAppRecord.appRecord_->LaunchPendingAbilities(); - EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _, _)).Times(1); auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1"); EXPECT_EQ(AbilityState::ABILITY_STATE_READY, newAbilityRecord->GetState()); EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, testAppRecord.appRecord_->GetState()); @@ -516,7 +521,7 @@ HWTEST_F(AmsAppLifeCycleTest, Schedule_007, TestSize.Level1) { TestApplicationPreRecord testAppRecord = PrepareLoadTestAbilityAndApp(ApplicationState::APP_STATE_SUSPENDED); testAppRecord.appRecord_->LaunchPendingAbilities(); - EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _, _)).Times(1); auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1"); EXPECT_EQ(AbilityState::ABILITY_STATE_READY, newAbilityRecord->GetState()); EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, testAppRecord.appRecord_->GetState()); @@ -849,7 +854,7 @@ HWTEST_F(AmsAppLifeCycleTest, Schedule_029, TestSize.Level1) auto appInfo = GetApplication(); HapModuleInfo hapModuleInfo; hapModuleInfo.moduleName = "module789"; - testAppPreRecord.appRecord_->AddModule(appInfo, newAbilityInfo, newToken, hapModuleInfo); + testAppPreRecord.appRecord_->AddModule(appInfo, newAbilityInfo, newToken, hapModuleInfo, nullptr); auto moduleRecord = testAppPreRecord.appRecord_->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); @@ -1028,7 +1033,7 @@ HWTEST_F(AmsAppLifeCycleTest, Schedule_042, TestSize.Level1) auto testAppRecord = CreateTestApplicationRecord(AbilityState::ABILITY_STATE_FOREGROUND, ApplicationState::APP_STATE_FOREGROUND); testAppRecord.appRecord_->LaunchPendingAbilities(); - EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _, _)).Times(1); auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1", -1); newAbilityRecord->SetState(AbilityState::ABILITY_STATE_BACKGROUND); @@ -1080,7 +1085,7 @@ HWTEST_F(AmsAppLifeCycleTest, Schedule_044, TestSize.Level1) auto testAppRecord = CreateTestApplicationRecord(AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); testAppRecord.appRecord_->LaunchPendingAbilities(); - EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _, _)).Times(1); auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1", -1); newAbilityRecord->SetState(AbilityState::ABILITY_STATE_BACKGROUND); @@ -1133,7 +1138,7 @@ HWTEST_F(AmsAppLifeCycleTest, Schedule_046, TestSize.Level1) auto testAppRecord = CreateTestApplicationRecord(AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_SUSPENDED); testAppRecord.appRecord_->LaunchPendingAbilities(); - EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _, _)).Times(1); auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1", -1); newAbilityRecord->SetState(AbilityState::ABILITY_STATE_BACKGROUND); testAppRecord.appRecord_->SetState(ApplicationState::APP_STATE_SUSPENDED); @@ -1382,7 +1387,7 @@ HWTEST_F(AmsAppLifeCycleTest, Stop_001, TestSize.Level1) EXPECT_NE(abilityRecord, nullptr); AbilityState abilityState = abilityRecord->GetState(); ApplicationState appState = appRecord->GetState(); - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); EXPECT_EQ(abilityState, abilityRecord->GetState()); EXPECT_EQ(appState, appRecord->GetState()); @@ -1441,7 +1446,7 @@ HWTEST_F(AmsAppLifeCycleTest, Stop_003, TestSize.Level1) EXPECT_NE(abilityRecord, nullptr); AbilityState abilityState = abilityRecord->GetState(); ApplicationState appState = appRecord->GetState(); - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); EXPECT_EQ(abilityState, abilityRecord->GetState()); EXPECT_EQ(appState, appRecord->GetState()); @@ -1481,7 +1486,6 @@ HWTEST_F(AmsAppLifeCycleTest, KillApplication_001, TestSize.Level1) * Function: AppLifeCycle * SubFunction: Schedule * FunctionPoints: Kill application - * CaseDescription: Verify if AppMgrService Kill by appname successfully. */ HWTEST_F(AmsAppLifeCycleTest, KillApplication_002, TestSize.Level1) { @@ -1495,7 +1499,7 @@ HWTEST_F(AmsAppLifeCycleTest, KillApplication_002, TestSize.Level1) serviceInner_->SetAppSpawnClient(mockClientPtr); - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); BundleInfo bundleInfo; bundleInfo.appId = "com.ohos.test.helloworld_code123"; auto appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist( @@ -1718,7 +1722,7 @@ HWTEST_F(AmsAppLifeCycleTest, Unsuspend_001, TestSize.Level1) { TestApplicationPreRecord testAppRecord = PrepareLoadTestAbilityAndApp(ApplicationState::APP_STATE_FOREGROUND); testAppRecord.appRecord_->LaunchPendingAbilities(); - EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _, _)).Times(1); auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1"); EXPECT_EQ(AbilityState::ABILITY_STATE_READY, newAbilityRecord->GetState()); EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppRecord.appRecord_->GetState()); @@ -1741,7 +1745,7 @@ HWTEST_F(AmsAppLifeCycleTest, Unsuspend_002, TestSize.Level1) { TestApplicationPreRecord testAppRecord = PrepareLoadTestAbilityAndApp(ApplicationState::APP_STATE_FOREGROUND); testAppRecord.appRecord_->LaunchPendingAbilities(); - EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _, _)).Times(1); auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1"); EXPECT_EQ(AbilityState::ABILITY_STATE_READY, newAbilityRecord->GetState()); EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppRecord.appRecord_->GetState()); @@ -1764,7 +1768,7 @@ HWTEST_F(AmsAppLifeCycleTest, Suspend_001, TestSize.Level1) { TestApplicationPreRecord testAppRecord = PrepareLoadTestAbilityAndApp(ApplicationState::APP_STATE_FOREGROUND); testAppRecord.appRecord_->LaunchPendingAbilities(); - EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _, _)).Times(1); auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1"); EXPECT_EQ(AbilityState::ABILITY_STATE_READY, newAbilityRecord->GetState()); EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppRecord.appRecord_->GetState()); @@ -1785,7 +1789,7 @@ HWTEST_F(AmsAppLifeCycleTest, Suspend_002, TestSize.Level1) { TestApplicationPreRecord testAppRecord = PrepareLoadTestAbilityAndApp(ApplicationState::APP_STATE_FOREGROUND); testAppRecord.appRecord_->LaunchPendingAbilities(); - EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*(testAppRecord.mockAppScheduler_), ScheduleLaunchAbility(_, _, _)).Times(1); auto newAbilityRecord = AddNewAbility(testAppRecord.appRecord_, "1"); EXPECT_EQ(AbilityState::ABILITY_STATE_READY, newAbilityRecord->GetState()); EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppRecord.appRecord_->GetState()); @@ -1894,33 +1898,6 @@ HWTEST_F(AmsAppLifeCycleTest, ClearUpApplicationData_001, TestSize.Level1) serviceInner_->ClearUpApplicationData(appRecord->GetBundleName(), appRecord->GetUid(), NEW_PID); } -/* - * Feature: AMS - * Function: AppLifeCycle - * SubFunction: ClearUpApplicationData - * FunctionPoints: UnsuspendApplication - * CaseDescription: test application state is APP_STATE_BACKGROUND(apprecord is nullptr) - */ -HWTEST_F(AmsAppLifeCycleTest, ClearUpApplicationData_002, TestSize.Level1) -{ - auto abilityInfo = GetAbilityInfoByIndex("110"); - auto appInfo = GetApplication(); - sptr token = GetMockToken(); - - int32_t pid = fork(); - - if (pid > 0) { - auto appRecord = StartProcessAndLoadAbility(token, nullptr, abilityInfo, appInfo, pid); - - EXPECT_CALL(*mockBundleMgr, CleanBundleDataFiles(_, _)).Times(1).WillOnce(Return(101)); - appRecord->SetUid(101); - sptr mockAppScheduler = new MockAppScheduler(); - sptr client = iface_cast(mockAppScheduler.GetRefPtr()); - appRecord->SetApplicationClient(client); - serviceInner_->ClearUpApplicationData(appRecord->GetBundleName(), appRecord->GetUid(), pid); - } -} - /* * Feature: AMS * Function: AppLifeCycle::IsBackgroundRunningRestricted @@ -1955,16 +1932,16 @@ HWTEST_F(AmsAppLifeCycleTest, CreateAppRunningRecord_001, TestSize.Level1) bundleInfo.appId = "com.ohos.test.helloworld_code123"; std::shared_ptr appRecord = serviceInner_->CreateAppRunningRecord( - nullptr, nullptr, appInfo, abilityInfo, "test_app", bundleInfo, hapModuleInfo); + nullptr, nullptr, appInfo, abilityInfo, "test_app", bundleInfo, hapModuleInfo, nullptr); EXPECT_TRUE(appRecord); appRecord = serviceInner_->CreateAppRunningRecord( - token, nullptr, nullptr, abilityInfo, "test_app", bundleInfo, hapModuleInfo); + token, nullptr, nullptr, abilityInfo, "test_app", bundleInfo, hapModuleInfo, nullptr); EXPECT_FALSE(appRecord); - appRecord = - serviceInner_->CreateAppRunningRecord(token, nullptr, appInfo, nullptr, "test_app", bundleInfo, hapModuleInfo); + appRecord = serviceInner_->CreateAppRunningRecord(token, nullptr, appInfo, nullptr, "test_app", bundleInfo, + hapModuleInfo, nullptr); EXPECT_TRUE(appRecord); - appRecord = - serviceInner_->CreateAppRunningRecord(token, nullptr, appInfo, abilityInfo, "", bundleInfo, hapModuleInfo); + appRecord = serviceInner_->CreateAppRunningRecord(token, nullptr, appInfo, abilityInfo, "", bundleInfo, + hapModuleInfo, nullptr); EXPECT_FALSE(appRecord); } @@ -1987,7 +1964,7 @@ HWTEST_F(AmsAppLifeCycleTest, CheckAppRunningRecordIsExist_001, TestSize.Level1) bundleInfo.appId = "com.ohos.test.helloworld_code123"; std::shared_ptr appRecord = serviceInner_->CreateAppRunningRecord( - token, nullptr, appInfo, abilityInfo, appInfo->name, bundleInfo, hapModuleInfo); + token, nullptr, appInfo, abilityInfo, appInfo->name, bundleInfo, hapModuleInfo, nullptr); EXPECT_TRUE(appRecord); auto appRecordProc = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist( diff --git a/services/appmgr/test/unittest/ams_app_mgr_client_test/ams_app_mgr_client_test.cpp b/services/appmgr/test/unittest/ams_app_mgr_client_test/ams_app_mgr_client_test.cpp index 048ec60c7404422eda0fe5093123b0cff0b2c293..6b5595f19fd473bbe2446f3502f3a0e73f4a3235 100644 --- a/services/appmgr/test/unittest/ams_app_mgr_client_test/ams_app_mgr_client_test.cpp +++ b/services/appmgr/test/unittest/ams_app_mgr_client_test/ams_app_mgr_client_test.cpp @@ -81,16 +81,18 @@ HWTEST_F(AmsAppMgrClientTest, AppMgrClient_001, TestSize.Level1) AbilityInfo abilityInfo; ApplicationInfo appInfo; + Want want; sptr amsMgrScheduler(new MockAmsMgrScheduler()); - EXPECT_CALL(*(static_cast(amsMgrScheduler.GetRefPtr())), LoadAbility(_, _, _, _)).Times(1); + EXPECT_CALL(*(static_cast(amsMgrScheduler.GetRefPtr())), + LoadAbility(_, _, _, _, _)).Times(1); EXPECT_CALL(*(static_cast(client_->remote_.GetRefPtr())), GetAmsMgr()) .Times(1) .WillOnce(Return(amsMgrScheduler)); - EXPECT_EQ(AppMgrResultCode::RESULT_OK, client_->LoadAbility(token_, preToken_, abilityInfo, appInfo)); + EXPECT_EQ(AppMgrResultCode::RESULT_OK, client_->LoadAbility(token_, preToken_, abilityInfo, appInfo, want)); APP_LOGI("ams_app_mgr_client_test_001 end"); } @@ -107,8 +109,10 @@ HWTEST_F(AmsAppMgrClientTest, AppMgrClient_002, TestSize.Level1) APP_LOGI("ams_app_mgr_client_test_002 start"); AbilityInfo abilityInfo; ApplicationInfo appInfo; + Want want; EXPECT_EQ( - AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED, client_->LoadAbility(token_, preToken_, abilityInfo, appInfo)); + AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED, client_->LoadAbility(token_, preToken_, abilityInfo, + appInfo, want)); APP_LOGI("ams_app_mgr_client_test_002 end"); } diff --git a/services/appmgr/test/unittest/ams_app_running_record_test/BUILD.gn b/services/appmgr/test/unittest/ams_app_running_record_test/BUILD.gn index 6e6552887d6f3a3f1f85dc12b0e52929932cd4ae..00f095ed376234c4da48517463d951941e96a0f6 100644 --- a/services/appmgr/test/unittest/ams_app_running_record_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_app_running_record_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -33,6 +33,7 @@ ohos_unittest("AmsAppRunningRecordTest") { sources = [ "${services_path}/appmgr/src/ability_running_record.cpp", + "${services_path}/appmgr/src/app_death_recipient.cpp", "${services_path}/appmgr/src/app_mgr_service_inner.cpp", "${services_path}/appmgr/src/app_running_record.cpp", "${services_path}/appmgr/src/app_spawn_client.cpp", @@ -51,6 +52,7 @@ ohos_unittest("AmsAppRunningRecordTest") { deps = [ "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${innerkits_path}/uri_permission:uri_permission_mgr", "${services_path}/appmgr/test:appmgr_test_source", "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//foundation/aafwk/standard/services/appmgr:libams", diff --git a/services/appmgr/test/unittest/ams_app_running_record_test/ams_app_running_record_test.cpp b/services/appmgr/test/unittest/ams_app_running_record_test/ams_app_running_record_test.cpp index 514a4c646e667b2f1649ead84a27b359490990f9..5cd8f60743f1004546d2d30b68f69b3e52a0b343 100644 --- a/services/appmgr/test/unittest/ams_app_running_record_test/ams_app_running_record_test.cpp +++ b/services/appmgr/test/unittest/ams_app_running_record_test/ams_app_running_record_test.cpp @@ -136,7 +136,7 @@ std::shared_ptr AmsAppRunningRecordTest::StartLoadAbility(cons service_->SetAppSpawnClient(mockClientPtr); EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(newPid), Return(ERR_OK))); - service_->LoadAbility(token, nullptr, abilityInfo, appInfo); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); BundleInfo bundleInfo; bundleInfo.appId = "com.ohos.test.helloworld_code123"; @@ -173,7 +173,7 @@ HWTEST_F(AmsAppRunningRecordTest, CreateAppRunningRecord_001, TestSize.Level1) hapModuleInfo.moduleName = "module789"; EXPECT_TRUE(service_ != nullptr); auto record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); EXPECT_TRUE(record != nullptr); EXPECT_EQ(record->GetName(), GetTestAppName()); @@ -208,12 +208,12 @@ HWTEST_F(AmsAppRunningRecordTest, CreateAppRunningRecord_002, TestSize.Level1) EXPECT_TRUE(service_ != nullptr); // Create sptr token = GetMockToken(); - auto record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + auto record = service_->CreateAppRunningRecord(GetMockToken(), nullptr, appInfo, abilityInfo, + GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); record->SetUid(1010); // Get - auto record1 = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + auto record1 = service_->CreateAppRunningRecord(GetMockToken(), nullptr, appInfo, abilityInfo, + GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); EXPECT_TRUE(record1 != nullptr); EXPECT_EQ(record1->GetName(), GetTestAppName()); EXPECT_EQ(record1->GetProcessName(), GetTestProcessName()); @@ -242,16 +242,16 @@ HWTEST_F(AmsAppRunningRecordTest, CreateAppRunningRecord_003, TestSize.Level1) HapModuleInfo hapModuleInfo; hapModuleInfo.moduleName = "module789"; EXPECT_TRUE(service_ != nullptr); - auto record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + auto record = service_->CreateAppRunningRecord(GetMockToken(), nullptr, appInfo, abilityInfo, + GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); record->SetUid(1010); auto anotherAbilityInfo = std::make_shared(); anotherAbilityInfo->name = "Another_ability"; anotherAbilityInfo->applicationInfo.uid = 1010; sptr anotherToken = new (std::nothrow) MockAbilityToken(); - auto record1 = service_->CreateAppRunningRecord( - GetMockToken(), anotherToken, appInfo, anotherAbilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + auto record1 = service_->CreateAppRunningRecord(GetMockToken(), anotherToken, appInfo, anotherAbilityInfo, + GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); EXPECT_EQ(record1->GetName(), GetTestAppName()); EXPECT_EQ(record1->GetProcessName(), GetTestProcessName()); @@ -280,8 +280,8 @@ HWTEST_F(AmsAppRunningRecordTest, CreateAppRunningRecord_004, TestSize.Level1) hapModuleInfo.moduleName = "module789"; EXPECT_TRUE(service_ != nullptr); // Create - auto record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, nullptr, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + auto record = service_->CreateAppRunningRecord(GetMockToken(), nullptr, nullptr, abilityInfo, + GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); EXPECT_TRUE(record == nullptr); } @@ -305,7 +305,7 @@ HWTEST_F(AmsAppRunningRecordTest, CreateAppRunningRecord_005, TestSize.Level1) EXPECT_TRUE(service_ != nullptr); // Create auto record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, nullptr, GetTestProcessName(), bundleInfo, hapModuleInfo); + GetMockToken(), nullptr, appInfo, nullptr, GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); EXPECT_TRUE(record != nullptr); } @@ -341,12 +341,12 @@ HWTEST_F(AmsAppRunningRecordTest, LaunchAbility_001, TestSize.Level1) hapModuleInfo.moduleName = "module789"; auto record = GetTestAppRunningRecord(); EXPECT_TRUE(record); - record->AddModule(appInfo, nullptr, GetMockToken(), hapModuleInfo); + record->AddModule(appInfo, nullptr, GetMockToken(), hapModuleInfo, nullptr); auto moduleRecord = record->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto abilityRecord = moduleRecord->GetAbilityRunningRecordByToken(GetMockToken()); EXPECT_EQ(nullptr, abilityRecord); - EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(0); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _, _)).Times(0); record->LaunchAbility(abilityRecord); } @@ -367,13 +367,13 @@ HWTEST_F(AmsAppRunningRecordTest, LaunchAbility_002, TestSize.Level1) HapModuleInfo hapModuleInfo; hapModuleInfo.moduleName = "module789"; auto record = GetTestAppRunningRecord(); - record->AddModule(appInfo, abilityInfo, GetMockToken(), hapModuleInfo); + record->AddModule(appInfo, abilityInfo, GetMockToken(), hapModuleInfo, nullptr); auto moduleRecord = record->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto abilityRecord = moduleRecord->GetAbilityRunningRecordByToken(GetMockToken()); EXPECT_TRUE(abilityRecord); - EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _, _)).Times(1); record->LaunchAbility(abilityRecord); @@ -511,7 +511,7 @@ HWTEST_F(AmsAppRunningRecordTest, DeleteAppRunningRecord_001, TestSize.Level1) hapModuleInfo.moduleName = "module789"; EXPECT_TRUE(service_ != nullptr); auto record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); EXPECT_TRUE(record != nullptr); record->SetState(ApplicationState::APP_STATE_BACKGROUND); record->SetApplicationClient(GetMockedAppSchedulerClient()); @@ -546,7 +546,7 @@ HWTEST_F(AmsAppRunningRecordTest, AttachApplication_001, TestSize.Level1) auto record = StartLoadAbility(token, abilityInfo, appInfo, newPid); EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(1); - EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _, _)).Times(1); service_->AttachApplication(newPid, mockAppSchedulerClient_); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_READY); APP_LOGI("AmsAppRunningRecordTest AttachApplication_001 end"); @@ -670,7 +670,7 @@ HWTEST_F(AmsAppRunningRecordTest, AttachApplication_005, TestSize.Level1) auto record = StartLoadAbility(token, abilityInfo, appInfo, newPid); EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(1); - EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _, _)).Times(1); service_->AttachApplication(newPid, GetMockedAppSchedulerClient()); EXPECT_NE(record->GetApplicationClient(), nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_READY); @@ -720,13 +720,13 @@ HWTEST_F(AmsAppRunningRecordTest, AttachApplication_006, TestSize.Level1) auto record = StartLoadAbility(token, abilityInfo, appInfo, PID); sptr token2 = new (std::nothrow) MockAbilityToken(); - service_->LoadAbility(token2, nullptr, abilityInfo2, appInfo); + service_->LoadAbility(token2, nullptr, abilityInfo2, appInfo, nullptr); sptr token3 = new (std::nothrow) MockAbilityToken(); - service_->LoadAbility(token3, nullptr, abilityInfo3, appInfo); + service_->LoadAbility(token3, nullptr, abilityInfo3, appInfo, nullptr); EXPECT_EQ(record->GetAbilities().size(), EXPECT_RECORD_SIZE); EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(1); - EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(EXPECT_ABILITY_LAUNCH_TIME); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _, _)).Times(EXPECT_ABILITY_LAUNCH_TIME); service_->AttachApplication(PID, mockAppSchedulerClient_); EXPECT_NE(record->GetApplicationClient(), nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_READY); @@ -759,12 +759,12 @@ HWTEST_F(AmsAppRunningRecordTest, LaunchAbilityForApp_001, TestSize.Level1) EXPECT_TRUE(service_ != nullptr); std::shared_ptr record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); auto abilityRecord = record->GetAbilityRunningRecord(GetTestAbilityName()); EXPECT_TRUE(abilityRecord != nullptr); EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(1); - EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _, _)).Times(1); record->SetApplicationClient(GetMockedAppSchedulerClient()); service_->LaunchApplication(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_READY); @@ -801,27 +801,27 @@ HWTEST_F(AmsAppRunningRecordTest, LaunchAbilityForApp_002, TestSize.Level1) const int EXPECT_ABILITY_LAUNCH_TIME = 3; EXPECT_TRUE(service_ != nullptr); - std::shared_ptr record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + std::shared_ptr record = service_->CreateAppRunningRecord(GetMockToken(), nullptr, appInfo, + abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); auto abilityRecord = record->GetAbilityRunningRecord(GetTestAbilityName()); EXPECT_TRUE(abilityRecord != nullptr); sptr token2 = new (std::nothrow) MockAbilityToken(); - record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo); + record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo, nullptr); auto moduleRecord = record->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); auto abilityRecord2 = moduleRecord->GetAbilityRunningRecordByToken(token2); EXPECT_TRUE(abilityRecord2 != nullptr); sptr token3 = new (std::nothrow) MockAbilityToken(); - record->AddModule(appInfo, abilityInfo3, token3, hapModuleInfo); + record->AddModule(appInfo, abilityInfo3, token3, hapModuleInfo, nullptr); auto moduleRecord3 = record->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord3); auto abilityRecord3 = moduleRecord3->GetAbilityRunningRecordByToken(token3); EXPECT_TRUE(abilityRecord3 != nullptr); EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(1); - EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(EXPECT_ABILITY_LAUNCH_TIME); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _, _)).Times(EXPECT_ABILITY_LAUNCH_TIME); record->SetApplicationClient(GetMockedAppSchedulerClient()); service_->LaunchApplication(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_READY); @@ -851,15 +851,15 @@ HWTEST_F(AmsAppRunningRecordTest, LaunchAbilityForApp_003, TestSize.Level1) hapModuleInfo.moduleName = "module789"; EXPECT_TRUE(service_ != nullptr); - std::shared_ptr record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + std::shared_ptr record = service_->CreateAppRunningRecord(GetMockToken(), nullptr, appInfo, + abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); record->SetState(ApplicationState::APP_STATE_READY); record->SetApplicationClient(GetMockedAppSchedulerClient()); auto abilityRecord = record->GetAbilityRunningRecord(GetTestAbilityName()); EXPECT_TRUE(abilityRecord != nullptr); EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(0); - EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(0); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _, _)).Times(0); service_->LaunchApplication(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_READY); APP_LOGI("AmsAppRunningRecordTest LaunchAbilityForApp_003 end"); @@ -897,21 +897,21 @@ HWTEST_F(AmsAppRunningRecordTest, LaunchAbilityForApp_004, TestSize.Level1) hapModuleInfo.moduleName = "module789"; EXPECT_TRUE(service_ != nullptr); - std::shared_ptr record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + std::shared_ptr record = service_->CreateAppRunningRecord(GetMockToken(), nullptr, appInfo, + abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); auto abilityRecord = record->GetAbilityRunningRecord(GetTestAbilityName()); EXPECT_TRUE(abilityRecord != nullptr); EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(1); - EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _, _)).Times(1); record->SetApplicationClient(GetMockedAppSchedulerClient()); service_->LaunchApplication(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_READY); EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(0); - EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _, _)).Times(1); sptr token2 = new (std::nothrow) MockAbilityToken(); - service_->LoadAbility(token2, nullptr, abilityInfo2, appInfo); + service_->LoadAbility(token2, nullptr, abilityInfo2, appInfo, nullptr); APP_LOGI("AmsAppRunningRecordTest LaunchAbilityForApp_004 end"); } @@ -945,26 +945,26 @@ HWTEST_F(AmsAppRunningRecordTest, LaunchAbilityForApp_005, TestSize.Level1) const int EXPECT_ABILITY_LAUNCH_TIME = 2; EXPECT_TRUE(service_ != nullptr); - std::shared_ptr record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + std::shared_ptr record = service_->CreateAppRunningRecord(GetMockToken(), nullptr, appInfo, + abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); auto abilityRecord = record->GetAbilityRunningRecord(GetTestAbilityName()); EXPECT_TRUE(abilityRecord != nullptr); sptr token2 = new (std::nothrow) MockAbilityToken(); - record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo); + record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo, nullptr); auto moduleRecord2 = record->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord2); auto abilityRecord2 = moduleRecord2->GetAbilityRunningRecordByToken(token2); abilityRecord2->SetState(AbilityState::ABILITY_STATE_READY); sptr token3 = new (std::nothrow) MockAbilityToken(); - record->AddModule(appInfo, abilityInfo3, token3, hapModuleInfo); + record->AddModule(appInfo, abilityInfo3, token3, hapModuleInfo, nullptr); auto moduleRecord3 = record->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord3); auto abilityRecord3 = moduleRecord3->GetAbilityRunningRecordByToken(token3); EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(1); - EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _)).Times(EXPECT_ABILITY_LAUNCH_TIME); + EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchAbility(_, _, _)).Times(EXPECT_ABILITY_LAUNCH_TIME); record->SetApplicationClient(GetMockedAppSchedulerClient()); service_->LaunchApplication(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_READY); @@ -1014,8 +1014,8 @@ HWTEST_F(AmsAppRunningRecordTest, TerminateAbility_002, TestSize.Level1) appInfo->name = GetTestAppName(); appInfo->bundleName = GetTestAppName(); - std::shared_ptr record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + std::shared_ptr record = service_->CreateAppRunningRecord(GetMockToken(), nullptr, appInfo, + abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); auto abilityRecord = record->GetAbilityRunningRecord(GetTestAbilityName()); EXPECT_TRUE(abilityRecord != nullptr); @@ -1067,8 +1067,8 @@ HWTEST_F(AmsAppRunningRecordTest, GetAbilityRunningRecord_001, TestSize.Level1) appInfo->name = GetTestAppName(); appInfo->bundleName = GetTestAppName(); - std::shared_ptr record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + std::shared_ptr record = service_->CreateAppRunningRecord(GetMockToken(), nullptr, appInfo, + abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); auto abilityRecord = record->GetAbilityRunningRecord(GetTestAbilityName()); EXPECT_TRUE(abilityRecord != nullptr); @@ -1118,8 +1118,8 @@ HWTEST_F(AmsAppRunningRecordTest, SetUid_GetUid_001, TestSize.Level1) HapModuleInfo hapModuleInfo; hapModuleInfo.moduleName = "module789"; EXPECT_TRUE(service_ != nullptr); - auto record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + auto record = service_->CreateAppRunningRecord(GetMockToken(), nullptr, appInfo, abilityInfo, + GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); EXPECT_TRUE(record != nullptr); record->SetUid(102); @@ -1153,8 +1153,8 @@ HWTEST_F(AmsAppRunningRecordTest, OnAbilityStateChanged_001, TestSize.Level1) HapModuleInfo hapModuleInfo; hapModuleInfo.moduleName = "module789"; - std::shared_ptr record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + std::shared_ptr record = service_->CreateAppRunningRecord(GetMockToken(), nullptr, appInfo, + abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); auto moduleRecord = record->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord != nullptr); auto abilityRecord = record->GetAbilityRunningRecord(GetTestAbilityName()); @@ -1204,7 +1204,7 @@ HWTEST_F(AmsAppRunningRecordTest, AddModule_001, TestSize.Level1) hapModuleInfo.moduleName = "module789"; EXPECT_TRUE(service_ != nullptr); auto record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); EXPECT_TRUE(record != nullptr); @@ -1217,7 +1217,7 @@ HWTEST_F(AmsAppRunningRecordTest, AddModule_001, TestSize.Level1) HapModuleInfo hapModuleInfo1; hapModuleInfo1.moduleName = "module123"; sptr token2 = new (std::nothrow) MockAbilityToken(); - record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo1); + record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo1, nullptr); moduleRecordList = record->GetAllModuleRecord(); EXPECT_TRUE(moduleRecordList.size() == 2); @@ -1245,7 +1245,7 @@ HWTEST_F(AmsAppRunningRecordTest, AddModule_002, TestSize.Level1) hapModuleInfo.moduleName = "module789"; EXPECT_TRUE(service_ != nullptr); auto record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); EXPECT_TRUE(record != nullptr); @@ -1256,7 +1256,7 @@ HWTEST_F(AmsAppRunningRecordTest, AddModule_002, TestSize.Level1) abilityInfo2->name = GetTestAbilityName() + "_1"; abilityInfo2->applicationName = GetTestAppName(); sptr token2 = new (std::nothrow) MockAbilityToken(); - record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo); + record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo, nullptr); moduleRecordList = record->GetAllModuleRecord(); EXPECT_TRUE(moduleRecordList.size() == 1); @@ -1285,7 +1285,7 @@ HWTEST_F(AmsAppRunningRecordTest, GetModuleRecordByModuleName_001, TestSize.Leve hapModuleInfo.moduleName = "module789"; EXPECT_TRUE(service_ != nullptr); auto record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); EXPECT_TRUE(record != nullptr); @@ -1295,7 +1295,7 @@ HWTEST_F(AmsAppRunningRecordTest, GetModuleRecordByModuleName_001, TestSize.Leve HapModuleInfo hapModuleInfo1; hapModuleInfo1.moduleName = "module123"; sptr token2 = new (std::nothrow) MockAbilityToken(); - record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo1); + record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo1, nullptr); auto moduleRecord = record->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); @@ -1323,7 +1323,7 @@ HWTEST_F(AmsAppRunningRecordTest, GetAbilities_001, TestSize.Level1) hapModuleInfo.moduleName = "module789"; EXPECT_TRUE(service_ != nullptr); auto record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); EXPECT_TRUE(record != nullptr); @@ -1331,7 +1331,7 @@ HWTEST_F(AmsAppRunningRecordTest, GetAbilities_001, TestSize.Level1) abilityInfo2->name = GetTestAbilityName() + "_1"; abilityInfo2->applicationName = GetTestAppName(); sptr token2 = new (std::nothrow) MockAbilityToken(); - record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo); + record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo, nullptr); auto abilities = record->GetAbilities(); EXPECT_TRUE(abilities.size() == 2); @@ -1359,7 +1359,7 @@ HWTEST_F(AmsAppRunningRecordTest, GetAbilities_002, TestSize.Level1) hapModuleInfo.moduleName = "module789"; EXPECT_TRUE(service_ != nullptr); auto record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); EXPECT_TRUE(record != nullptr); @@ -1369,7 +1369,7 @@ HWTEST_F(AmsAppRunningRecordTest, GetAbilities_002, TestSize.Level1) HapModuleInfo hapModuleInfo1; hapModuleInfo1.moduleName = "module123"; sptr token2 = new (std::nothrow) MockAbilityToken(); - record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo1); + record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo1, nullptr); auto abilities = record->GetAbilities(); EXPECT_TRUE(abilities.size() == 2); @@ -1398,7 +1398,7 @@ HWTEST_F(AmsAppRunningRecordTest, RemoveModuleRecord_001, TestSize.Level1) hapModuleInfo.moduleName = "module789"; EXPECT_TRUE(service_ != nullptr); auto record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo); + GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr); EXPECT_TRUE(record != nullptr); @@ -1408,7 +1408,7 @@ HWTEST_F(AmsAppRunningRecordTest, RemoveModuleRecord_001, TestSize.Level1) HapModuleInfo hapModuleInfo1; hapModuleInfo1.moduleName = "module123"; sptr token2 = new (std::nothrow) MockAbilityToken(); - record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo1); + record->AddModule(appInfo, abilityInfo2, token2, hapModuleInfo1, nullptr); auto moduleRecord = record->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); EXPECT_TRUE(moduleRecord); diff --git a/services/appmgr/test/unittest/ams_app_workflow_test/BUILD.gn b/services/appmgr/test/unittest/ams_app_workflow_test/BUILD.gn index a8a0c8d1f3e98ce470ff850b4163c0b3939b7664..9cee8a201d718e28f6261ea6d598e0da70655952 100644 --- a/services/appmgr/test/unittest/ams_app_workflow_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_app_workflow_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -29,6 +29,7 @@ ohos_unittest("AmsWorkFlowTest") { sources = [ "${services_path}/appmgr/src/ability_running_record.cpp", + "${services_path}/appmgr/src/app_death_recipient.cpp", "${services_path}/appmgr/src/app_lifecycle_deal.cpp", "${services_path}/appmgr/src/app_mgr_service_event_handler.cpp", "${services_path}/appmgr/src/app_mgr_service_inner.cpp", @@ -54,6 +55,7 @@ ohos_unittest("AmsWorkFlowTest") { "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${innerkits_path}/uri_permission:uri_permission_mgr", "${services_path}/appmgr/test:appmgr_test_source", "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/base:base", diff --git a/services/appmgr/test/unittest/ams_app_workflow_test/ams_workflow_test.cpp b/services/appmgr/test/unittest/ams_app_workflow_test/ams_workflow_test.cpp index a2de9fbac7a50b682653d3da83df16d36fb7bbf0..bac6b929be57aad981a714f5bb839ded06cffddd 100644 --- a/services/appmgr/test/unittest/ams_app_workflow_test/ams_workflow_test.cpp +++ b/services/appmgr/test/unittest/ams_app_workflow_test/ams_workflow_test.cpp @@ -140,14 +140,14 @@ TestApplicationPreRecord AmsWorkFlowTest::CreateTestApplicationRecord(const std: appInfo->name, appInfo->name, appInfo->uid, bundleInfo); if (!appRecord) { appRecord = serviceInner_->CreateAppRunningRecord( - token, nullptr, appInfo, abilityInfo, appInfo->name, bundleInfo, hapModuleInfo); + token, nullptr, appInfo, abilityInfo, appInfo->name, bundleInfo, hapModuleInfo, nullptr); serviceInner_->StartProcess(abilityInfo->applicationName, appInfo->name, appRecord, abilityInfo->applicationInfo.uid, abilityInfo->applicationInfo.bundleName); } else { - appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo); + appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, nullptr); } EXPECT_NE(appRecord, nullptr); diff --git a/services/appmgr/test/unittest/ams_ipc_interface_test/ams_ipc_appscheduler_interface_test.cpp b/services/appmgr/test/unittest/ams_ipc_interface_test/ams_ipc_appscheduler_interface_test.cpp index 62e9c315074addcfd72f4edfc7cb030642a921f5..b8a470c22b49f9206450cd9e9b8da7c59c2b2e28 100644 --- a/services/appmgr/test/unittest/ams_ipc_interface_test/ams_ipc_appscheduler_interface_test.cpp +++ b/services/appmgr/test/unittest/ams_ipc_interface_test/ams_ipc_appscheduler_interface_test.cpp @@ -210,34 +210,6 @@ HWTEST_F(AmsIpcAppSchedulerInterfaceTest, Interface_006, TestSize.Level1) APP_LOGD("AppSchedulerInterfaceTest_006 end"); } -/* - * Feature: AppScheduler ZIDL interface - * Function: ScheduleLaunchAbility - * SubFunction: NA - * FunctionPoints: scheduleLaunchAbility interface - * EnvConditions: Application already running - * CaseDescription: Test the interface ScheduleLaunchAbility of AppScheduler - */ -HWTEST_F(AmsIpcAppSchedulerInterfaceTest, Interface_007, TestSize.Level1) -{ - APP_LOGD("AppSchedulerInterfaceTest_007 start"); - sptr mockApplication(new MockApplication()); - sptr client = iface_cast(mockApplication); - std::string abilityName("mockAbilityInfo"); - AbilityInfo info; - info.name = abilityName; - - EXPECT_CALL(*mockApplication, ScheduleLaunchAbility(_, _)) - .Times(1) - .WillOnce(Invoke(mockApplication.GetRefPtr(), &MockApplication::LaunchAbility)); - client->ScheduleLaunchAbility(info, GetMockToken()); - mockApplication->Wait(); - - bool isEqual = mockApplication->CompareAbilityInfo(info); - EXPECT_EQ(true, isEqual); - APP_LOGD("AppSchedulerInterfaceTest_007 end"); -} - /* * Feature: AppScheduler ZIDL interface * Function: ScheduleCleanAbility diff --git a/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp b/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp index 6734c2ef1319131bb2e9c1c6a80b85d710ea1f83..85f35cacbda5657d235f2faef365745ce7d58a1d 100644 --- a/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp +++ b/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp @@ -114,9 +114,9 @@ HWTEST_F(AmsMgrSchedulerTest, AmsMgrScheduler_001, TestSize.Level1) std::shared_ptr applicationInfo = std::make_shared(); applicationInfo->name = GetTestAppName(); - EXPECT_CALL(*mockAppMgrServiceInner, LoadAbility(_, _, _, _)) + EXPECT_CALL(*mockAppMgrServiceInner, LoadAbility(_, _, _, _, _)) .WillOnce(InvokeWithoutArgs(mockAppMgrServiceInner.get(), &MockAppMgrServiceInner::Post)); - amsMgrScheduler->LoadAbility(token, preToken, abilityInfo, applicationInfo); + amsMgrScheduler->LoadAbility(token, preToken, abilityInfo, applicationInfo, nullptr); mockAppMgrServiceInner->Wait(); APP_LOGD("AmsMgrScheduler_001 end."); @@ -148,12 +148,12 @@ HWTEST_F(AmsMgrSchedulerTest, AmsMgrScheduler_002, TestSize.Level1) applicationInfo->name = GetTestAppName(); // check token parameter - EXPECT_CALL(*mockAppMgrServiceInner, LoadAbility(_, _, _, _)).Times(0); - amsMgrScheduler->LoadAbility(token, preToken, nullptr, applicationInfo); + EXPECT_CALL(*mockAppMgrServiceInner, LoadAbility(_, _, _, _, _)).Times(0); + amsMgrScheduler->LoadAbility(token, preToken, nullptr, applicationInfo, nullptr); // check pretoken parameter - EXPECT_CALL(*mockAppMgrServiceInner, LoadAbility(_, _, _, _)).Times(0); - amsMgrScheduler->LoadAbility(token, preToken, abilityInfo, nullptr); + EXPECT_CALL(*mockAppMgrServiceInner, LoadAbility(_, _, _, _, _)).Times(0); + amsMgrScheduler->LoadAbility(token, preToken, abilityInfo, nullptr, nullptr); APP_LOGD("AmsMgrScheduler_002 end."); } diff --git a/services/appmgr/test/unittest/ams_recent_app_list_test/BUILD.gn b/services/appmgr/test/unittest/ams_recent_app_list_test/BUILD.gn index a17a31a6b851f928f0b64745e64952f5aeb72f85..03038b0f69c326df1deefd9a0c773c2413839803 100644 --- a/services/appmgr/test/unittest/ams_recent_app_list_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_recent_app_list_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -27,6 +27,7 @@ ohos_unittest("AmsRecentAppListTest") { sources = [ "${services_path}/appmgr/src/ability_running_record.cpp", + "${services_path}/appmgr/src/app_death_recipient.cpp", "${services_path}/appmgr/src/app_lifecycle_deal.cpp", "${services_path}/appmgr/src/app_mgr_service_inner.cpp", "${services_path}/appmgr/src/app_process_manager.cpp", @@ -54,6 +55,7 @@ ohos_unittest("AmsRecentAppListTest") { deps = [ "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${innerkits_path}/uri_permission:uri_permission_mgr", "${services_path}/appmgr/test:appmgr_test_source", "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", diff --git a/services/appmgr/test/unittest/ams_recent_app_list_test/ams_recent_app_list_test.cpp b/services/appmgr/test/unittest/ams_recent_app_list_test/ams_recent_app_list_test.cpp index fda095275ba9996b2923ee44bfaf40d380ca9e48..232f33406499d081b191695bdb1eef564f688ff4 100644 --- a/services/appmgr/test/unittest/ams_recent_app_list_test/ams_recent_app_list_test.cpp +++ b/services/appmgr/test/unittest/ams_recent_app_list_test/ams_recent_app_list_test.cpp @@ -116,7 +116,7 @@ void AmsRecentAppListTest::StartProcessSuccess(const int32_t index) const EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); serviceInner_->SetAppSpawnClient(std::unique_ptr(mockClientPtr)); - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); return; } @@ -160,7 +160,7 @@ HWTEST_F(AmsRecentAppListTest, Create_002, TestSize.Level1) EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).WillOnce(Return(ERR_APPEXECFWK_ASSEMBLE_START_MSG_FAILED)); serviceInner_->SetAppSpawnClient(std::unique_ptr(mockClientPtr)); - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); } @@ -187,11 +187,11 @@ HWTEST_F(AmsRecentAppListTest, Create_003, TestSize.Level1) EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); serviceInner_->SetAppSpawnClient(std::unique_ptr(mockClientPtr)); - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); EXPECT_EQ(INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); // Load ability1, start process 1 again. - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); EXPECT_EQ(INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); } @@ -381,7 +381,7 @@ HWTEST_F(AmsRecentAppListTest, RecentAppList_001, TestSize.Level1) EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); serviceInner_->SetAppSpawnClient(std::unique_ptr(mockClientPtr)); - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); EXPECT_EQ(INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); auto appRecord = GetAppRunningRecordByIndex(INDEX_NUM_1); serviceInner_->AddAppDeathRecipient(pid, nullptr); @@ -409,7 +409,7 @@ HWTEST_F(AmsRecentAppListTest, PushAppFront_001, TestSize.Level1) EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); serviceInner_->SetAppSpawnClient(std::unique_ptr(mockClientPtr)); - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); EXPECT_EQ(INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); auto appRecord = GetAppRunningRecordByIndex(INDEX_NUM_1); serviceInner_->PushAppFront(appRecord->GetRecordId()); diff --git a/services/appmgr/test/unittest/ams_service_app_spawn_client_test/BUILD.gn b/services/appmgr/test/unittest/ams_service_app_spawn_client_test/BUILD.gn index 48bbb035ac3a00f4ed7bb5e97252d64ac118b46a..c09f3a61dceb8045687ede9be4f64908a08f4121 100644 --- a/services/appmgr/test/unittest/ams_service_app_spawn_client_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_service_app_spawn_client_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -52,6 +52,7 @@ ohos_unittest("AmsServiceAppSpawnClientTest") { deps = [ "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${innerkits_path}/uri_permission:uri_permission_mgr", "${services_path}/appmgr/test:appmgr_test_source", "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/base:base", diff --git a/services/appmgr/test/unittest/ams_service_event_drive_test/BUILD.gn b/services/appmgr/test/unittest/ams_service_event_drive_test/BUILD.gn index a6d93271e42fbe7e8e0d69a0963afd268f5b5975..48fba9708ff1a7b7ddc6110f66a11ae3aac66996 100644 --- a/services/appmgr/test/unittest/ams_service_event_drive_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_service_event_drive_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -32,6 +32,7 @@ ohos_unittest("AmsServiceEventDriveTest") { ] sources = [ + "${aafwk_path}/interfaces/innerkits/app_manager/src/appmgr/system_memory_attr.cpp", "${services_path}/appmgr/src/ability_running_record.cpp", "${services_path}/appmgr/src/app_death_recipient.cpp", "${services_path}/appmgr/src/app_mgr_service.cpp", @@ -41,7 +42,6 @@ ohos_unittest("AmsServiceEventDriveTest") { "${services_path}/appmgr/src/app_spawn_client.cpp", "${services_path}/appmgr/src/app_spawn_msg_wrapper.cpp", "${services_path}/appmgr/src/app_spawn_socket.cpp", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/src/system_memory_attr.cpp", ] sources += [ "ams_service_event_drive_test.cpp" ] @@ -54,6 +54,7 @@ ohos_unittest("AmsServiceEventDriveTest") { deps = [ "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${innerkits_path}/uri_permission:uri_permission_mgr", "${services_path}/appmgr/test:appmgr_test_source", "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/base:base", diff --git a/services/appmgr/test/unittest/ams_service_event_drive_test/ams_service_event_drive_test.cpp b/services/appmgr/test/unittest/ams_service_event_drive_test/ams_service_event_drive_test.cpp index 093b1e7ccb936ef01098e9ff1492f75bf713b2ad..f17bbdbe68929302eb15f30b31a88f0c67a71447 100644 --- a/services/appmgr/test/unittest/ams_service_event_drive_test/ams_service_event_drive_test.cpp +++ b/services/appmgr/test/unittest/ams_service_event_drive_test/ams_service_event_drive_test.cpp @@ -47,7 +47,7 @@ public: std::shared_ptr GetAmsEventHandler(); protected: - std::shared_ptr appMgrService_; + std::shared_ptr appMgrService_ = std::make_shared(); }; void AmsServiceEventDriveTest::SetUpTestCase() @@ -58,11 +58,13 @@ void AmsServiceEventDriveTest::TearDownTestCase() void AmsServiceEventDriveTest::SetUp() { - appMgrService_ = std::make_shared(); + appMgrService_->OnStart(); } void AmsServiceEventDriveTest::TearDown() -{} +{ + appMgrService_->OnStop(); +} /* * Feature: AppMgrService @@ -284,6 +286,7 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_009, TestSize.Level1) { APP_LOGI("ams_service_event_drive_test_009 start"); + appMgrService_->OnStop(); std::shared_ptr innerService = std::make_shared(); appMgrService_->SetInnerService(innerService); @@ -307,6 +310,7 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_010, TestSize.Level1) { APP_LOGI("ams_service_event_drive_test_010 start"); + appMgrService_->OnStop(); std::shared_ptr innerService = std::make_shared(); appMgrService_->SetInnerService(innerService); @@ -330,6 +334,7 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_011, TestSize.Level1) { APP_LOGI("ams_service_event_drive_test_011 start"); + appMgrService_->OnStop(); std::shared_ptr innerService = std::make_shared(); appMgrService_->SetInnerService(innerService); @@ -353,6 +358,7 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_012, TestSize.Level1) { APP_LOGI("ams_service_event_drive_test_012 start"); + appMgrService_->OnStop(); std::shared_ptr innerService = std::make_shared(); appMgrService_->SetInnerService(innerService); @@ -376,6 +382,7 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_013, TestSize.Level1) { APP_LOGI("ams_service_event_drive_test_013 start"); + appMgrService_->OnStop(); std::shared_ptr innerService = std::make_shared(); appMgrService_->SetInnerService(innerService); @@ -399,6 +406,7 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_014, TestSize.Level1) { APP_LOGI("ams_service_event_drive_test_014 start"); + appMgrService_->OnStop(); std::shared_ptr innerService = std::make_shared(); appMgrService_->SetInnerService(innerService); @@ -422,6 +430,7 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_015, TestSize.Level1) { APP_LOGI("ams_service_event_drive_test_015 start"); + appMgrService_->OnStop(); std::shared_ptr innerService = std::make_shared(); appMgrService_->SetInnerService(innerService); @@ -443,6 +452,7 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_016, TestSize.Level1) { APP_LOGI("ams_service_event_drive_test_016 start"); + appMgrService_->OnStop(); std::shared_ptr innerService = std::make_shared(); appMgrService_->SetInnerService(innerService); @@ -856,6 +866,7 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_035, TestSize.Level1) { APP_LOGI("ams_service_event_drive_test_035 start"); + appMgrService_->OnStop(); std::shared_ptr innerService = std::make_shared(); appMgrService_->SetInnerService(innerService); @@ -928,6 +939,7 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_038, TestSize.Level1) { APP_LOGI("ams_service_event_drive_test_038 start"); + appMgrService_->OnStop(); std::shared_ptr innerService = std::make_shared(); appMgrService_->SetInnerService(innerService); @@ -970,7 +982,6 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_039, TestSize.Level1) * EnvConditions: Mobile that can run ohos test framework * CaseDescription: Verify if QueryServiceState act normal after AppMgrService stopped */ -/* HWTEST_F(AmsServiceEventDriveTest, EventDrive_040, TestSize.Level1) { APP_LOGI("AppMgrService::EventDrive_040 start 1"); @@ -990,7 +1001,6 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_040, TestSize.Level1) APP_LOGI("AppMgrService::EventDrive_040 end"); } -*/ /* * Feature: AppMgrService diff --git a/services/appmgr/test/unittest/ams_service_load_ability_process_test/BUILD.gn b/services/appmgr/test/unittest/ams_service_load_ability_process_test/BUILD.gn index 23f0b68234b8c9d7e3b645b967985730cf4fbee9..f64176faabb1358e71e8870de76bcd85f04a14bc 100644 --- a/services/appmgr/test/unittest/ams_service_load_ability_process_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_service_load_ability_process_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -27,6 +27,7 @@ ohos_unittest("AmsServiceLoadAbilityProcessTest") { sources = [ "${services_path}/appmgr/src/ability_running_record.cpp", + "${services_path}/appmgr/src/app_death_recipient.cpp", "${services_path}/appmgr/src/app_lifecycle_deal.cpp", "${services_path}/appmgr/src/app_mgr_service_inner.cpp", "${services_path}/appmgr/src/app_process_manager.cpp", @@ -58,6 +59,7 @@ ohos_unittest("AmsServiceLoadAbilityProcessTest") { "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${innerkits_path}/uri_permission:uri_permission_mgr", "${services_path}/appmgr/test:appmgr_test_source", "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/base:base", diff --git a/services/appmgr/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp b/services/appmgr/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp index 21b40a10e95fdc5fb213b5df5c9080f36dcc3f07..8311995abc185cfad07972283e3964d6a2ddac8b 100644 --- a/services/appmgr/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp +++ b/services/appmgr/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp @@ -103,7 +103,7 @@ std::shared_ptr AmsServiceLoadAbilityProcessTest::StartLoadAbi EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(newPid), Return(ERR_OK))); service_->SetAppSpawnClient(mockClientPtr); - service_->LoadAbility(token, preToken, abilityInfo, appInfo); + service_->LoadAbility(token, preToken, abilityInfo, appInfo, nullptr); BundleInfo bundleInfo; bundleInfo.appId = "com.ohos.test.helloworld_code123"; @@ -264,7 +264,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_003, TestSize.Level1) EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(0); service_->SetAppSpawnClient(mockClientPtr); - service_->LoadAbility(nullptr, nullptr, abilityInfo, appInfo); + service_->LoadAbility(nullptr, nullptr, abilityInfo, appInfo, nullptr); const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)0); @@ -296,7 +296,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_004, TestSize.Level1) EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(0); service_->SetAppSpawnClient(mockClientPtr); - service_->LoadAbility(token, nullptr, abilityInfo, appInfo); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)0); APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_004 end"); @@ -326,7 +326,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_005, TestSize.Level1) EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(0); service_->SetAppSpawnClient(mockClientPtr); - service_->LoadAbility(token, nullptr, abilityInfo, appInfo); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)0); APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_005 end"); @@ -357,7 +357,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_006, TestSize.Level1) EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(0); service_->SetAppSpawnClient(mockClientPtr); - service_->LoadAbility(token, nullptr, abilityInfo, appInfo); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)0); APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_006 end"); @@ -407,7 +407,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_007, TestSize.Level1) EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(0); service_->SetAppSpawnClient(mockClientPtr); - service_->LoadAbility(token, nullptr, abilityInfo, appInfo); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record2 = service_->appRunningManager_->CheckAppRunningRecordIsExist( @@ -469,7 +469,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_008, TestSize.Level1) EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(0); service_->SetAppSpawnClient(mockClientPtr); - service_->LoadAbility(token2, preToken, abilityInfo2, appInfo); + service_->LoadAbility(token2, preToken, abilityInfo2, appInfo, nullptr); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record2 = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); @@ -511,7 +511,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, RequestProcess_001, TestSize.Level1) EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(PID), Return(ERR_OK))); service_->SetAppSpawnClient(mockClientPtr); - service_->LoadAbility(token, nullptr, abilityInfo, appInfo); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); @@ -553,7 +553,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, RequestProcess_002, TestSize.Level1) EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(Return(ERR_APPEXECFWK_INVALID_PID)); service_->SetAppSpawnClient(mockClientPtr); - service_->LoadAbility(token, nullptr, abilityInfo, appInfo); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)0); @@ -587,7 +587,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, SavePid_001, TestSize.Level1) EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(PID), Return(ERR_OK))); service_->SetAppSpawnClient(mockClientPtr); - service_->LoadAbility(token, nullptr, abilityInfo, appInfo); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); BundleInfo bundleInfo; bundleInfo.appId = "com.ohos.test.helloworld_code123"; @@ -622,7 +622,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, SavePid_002, TestSize.Level1) EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(Return(ERR_APPEXECFWK_INVALID_PID)); service_->SetAppSpawnClient(mockClientPtr); - service_->LoadAbility(token, nullptr, abilityInfo, appInfo); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); BundleInfo bundleInfo; bundleInfo.appId = "com.ohos.test.helloworld_code123"; @@ -722,7 +722,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LaunchMode_002, TestSize.Level1) sptr token2 = new MockAbilityToken(); sptr preToken = token; service_->SetAppSpawnClient(mockClientPtr); - service_->LoadAbility(token2, preToken, abilityInfo, appInfo); + service_->LoadAbility(token2, preToken, abilityInfo, appInfo, nullptr); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record2 = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); @@ -783,11 +783,11 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_001, TestSize.Level1) sptr mockAppScheduler = new MockAppScheduler(); sptr client = iface_cast(mockAppScheduler.GetRefPtr()); record->SetApplicationClient(client); - EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _, _)).Times(1); HapModuleInfo hapModuleInfo; hapModuleInfo.moduleName = "module789"; - service_->StartAbility(token2, token, abilityInfo2, record, hapModuleInfo); + service_->StartAbility(token2, token, abilityInfo2, record, hapModuleInfo, nullptr); auto record1 = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); const auto &abilityMap1 = record1->GetAbilities(); @@ -849,11 +849,11 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_002, TestSize.Level1) sptr mockAppScheduler = new MockAppScheduler(); sptr client = iface_cast(mockAppScheduler.GetRefPtr()); record->SetApplicationClient(client); - EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _)).Times(0); + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _, _)).Times(0); HapModuleInfo hapModuleInfo; hapModuleInfo.moduleName = "module789"; - service_->StartAbility(token2, token, abilityInfo2, nullptr, hapModuleInfo); + service_->StartAbility(token2, token, abilityInfo2, nullptr, hapModuleInfo, nullptr); auto record1 = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); const auto &abilityMap1 = record1->GetAbilities(); @@ -916,10 +916,10 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_003, TestSize.Level1) sptr mockAppScheduler = new MockAppScheduler(); sptr client = iface_cast(mockAppScheduler.GetRefPtr()); record->SetApplicationClient(client); - EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _)).Times(0); + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _, _)).Times(0); HapModuleInfo hapModuleInfo; hapModuleInfo.moduleName = "module789"; - service_->StartAbility(token2, token, abilityInfo2, nullptr, hapModuleInfo); + service_->StartAbility(token2, token, abilityInfo2, nullptr, hapModuleInfo, nullptr); auto record1 = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); const auto &abilityMap1 = record1->GetAbilities(); @@ -975,10 +975,10 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_004, TestSize.Level1) sptr mockAppScheduler = new MockAppScheduler(); sptr client = iface_cast(mockAppScheduler.GetRefPtr()); record->SetApplicationClient(client); - EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _)).Times(0); + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _, _)).Times(0); HapModuleInfo hapModuleInfo; hapModuleInfo.moduleName = "module789"; - service_->StartAbility(nullptr, token, abilityInfo2, nullptr, hapModuleInfo); + service_->StartAbility(nullptr, token, abilityInfo2, nullptr, hapModuleInfo, nullptr); auto record1 = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); @@ -1038,10 +1038,10 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_005, TestSize.Level1) sptr mockAppScheduler = new MockAppScheduler(); sptr client = iface_cast(mockAppScheduler.GetRefPtr()); record->SetApplicationClient(client); - EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _, _)).Times(1); HapModuleInfo hapModuleInfo; hapModuleInfo.moduleName = "module789"; - service_->StartAbility(token2, nullptr, abilityInfo2, record, hapModuleInfo); + service_->StartAbility(token2, nullptr, abilityInfo2, record, hapModuleInfo, nullptr); auto record1 = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); const auto &abilityMap1 = record1->GetAbilities(); @@ -1100,10 +1100,10 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_006, TestSize.Level1) sptr mockAppScheduler = new MockAppScheduler(); sptr client = iface_cast(mockAppScheduler.GetRefPtr()); record->SetApplicationClient(client); - EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _)).Times(0); + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _, _)).Times(0); HapModuleInfo hapModuleInfo; hapModuleInfo.moduleName = "module789"; - service_->StartAbility(nullptr, token, abilityInfo2, nullptr, hapModuleInfo); + service_->StartAbility(nullptr, token, abilityInfo2, nullptr, hapModuleInfo, nullptr); auto record1 = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); const auto &abilityMap1 = record1->GetAbilities(); @@ -1143,7 +1143,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartProcess001, TestSize.Level1) hapModuleInfo.moduleName = "module789"; std::shared_ptr record = service_->CreateAppRunningRecord( - token, nullptr, appInfo, abilityInfo, GetTestAppName(), bundleInfo, hapModuleInfo); + token, nullptr, appInfo, abilityInfo, GetTestAppName(), bundleInfo, hapModuleInfo, nullptr); service_->StartProcess(abilityInfo->applicationName, GetTestAppName(), @@ -1193,7 +1193,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartProcess002, TestSize.Level1) hapModuleInfo.moduleName = "module789"; std::shared_ptr record = service_->CreateAppRunningRecord( - token, nullptr, appInfo, abilityInfo, GetTestAppName(), bundleInfo, hapModuleInfo); + token, nullptr, appInfo, abilityInfo, GetTestAppName(), bundleInfo, hapModuleInfo, nullptr); service_->SetAppSpawnClient(nullptr); service_->StartProcess(abilityInfo->applicationName, @@ -1238,7 +1238,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartProcess003, TestSize.Level1) hapModuleInfo.moduleName = "module789"; std::shared_ptr record = service_->CreateAppRunningRecord( - token, nullptr, appInfo, abilityInfo, GetTestAppName(), bundleInfo, hapModuleInfo); + token, nullptr, appInfo, abilityInfo, GetTestAppName(), bundleInfo, hapModuleInfo, nullptr); service_->StartProcess(abilityInfo->applicationName, GetTestAppName(), @@ -1289,7 +1289,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartProcess004, TestSize.Level1) hapModuleInfo.moduleName = "module789"; std::shared_ptr record = service_->CreateAppRunningRecord( - token, nullptr, appInfo, abilityInfo, GetTestAppName(), bundleInfo, hapModuleInfo); + token, nullptr, appInfo, abilityInfo, GetTestAppName(), bundleInfo, hapModuleInfo, nullptr); EXPECT_NE(record, nullptr); CHECK_POINTER_IS_NULLPTR(record); diff --git a/services/appmgr/test/unittest/ams_service_startup_test/BUILD.gn b/services/appmgr/test/unittest/ams_service_startup_test/BUILD.gn index 55ea371d65101d6666cae789e65217a51396d3b0..fc65f97e04a52510e423ec3d043abae212601e59 100644 --- a/services/appmgr/test/unittest/ams_service_startup_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_service_startup_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -49,6 +49,7 @@ ohos_unittest("AmsServiceStartupTest") { } deps = [ "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${innerkits_path}/uri_permission:uri_permission_mgr", "${services_path}/appmgr/test:appmgr_test_source", "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", diff --git a/services/appmgr/test/unittest/app_mgr_service_event_handler_test/BUILD.gn b/services/appmgr/test/unittest/app_mgr_service_event_handler_test/BUILD.gn index 4e64ee9e19f45f6b7a59424d5859e3eba4f75120..914c579d6186bbda652c61031d89d18ca76dfbcf 100644 --- a/services/appmgr/test/unittest/app_mgr_service_event_handler_test/BUILD.gn +++ b/services/appmgr/test/unittest/app_mgr_service_event_handler_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -57,6 +57,7 @@ ohos_unittest("AMSEventHandlerTest") { deps = [ "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${innerkits_path}/uri_permission:uri_permission_mgr", "${services_path}/appmgr/test:appmgr_test_source", "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", diff --git a/services/formmgr/BUILD.gn b/services/formmgr/BUILD.gn index 7f7bbfc2a83904207b57d6ecd9bfdba809d95a9a..cc0963ffc1e427bb8ccac55e80f9face31284da3 100644 --- a/services/formmgr/BUILD.gn +++ b/services/formmgr/BUILD.gn @@ -91,8 +91,8 @@ ohos_shared_library("libfms") { "${appexecfwk_path}/common:libappexecfwk_common", "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", "//base/miscservices/time/services:time_service", - "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", "//utils/native/base:utils", @@ -101,9 +101,9 @@ ohos_shared_library("libfms") { ] external_deps = [ + "ability_base:base", + "ability_base:want", "ability_runtime:app_manager", - "ability_runtime:base", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", diff --git a/services/formmgr/bundle.json b/services/formmgr/bundle.json index 801f14db7b9bd31e77204b01183eacd83b48b98b..fb7f7e2d69316604164c5584a0ba888d6e3fbb0d 100644 --- a/services/formmgr/bundle.json +++ b/services/formmgr/bundle.json @@ -23,13 +23,13 @@ "components": [ "ability_runtime", "ans_standard", - "appexecfwk_standard", + "bundle_framework", "ces_standard", "hiviewdfx_hilog_native", "ipc", "napi", "native_appdatamgr", - "miscservices_time", + "time_native", "os_account_standard", "permission_standard", "power_manager_native", diff --git a/services/formmgr/include/form_timer_mgr.h b/services/formmgr/include/form_timer_mgr.h index 23e9cf5da7878c83c7c3c9ea05277f8eb1ba93a2..510f2ba4d118d674306850c373ad27da788d196b 100644 --- a/services/formmgr/include/form_timer_mgr.h +++ b/services/formmgr/include/form_timer_mgr.h @@ -39,7 +39,7 @@ namespace OHOS { namespace AppExecFwk { -using namespace OHOS::Notification::WantAgent; +using namespace OHOS::AbilityRuntime::WantAgent; /** * @class FormTimerMgr * form timer task manager. diff --git a/services/formmgr/include/form_timer_option.h b/services/formmgr/include/form_timer_option.h index 661eb03253609a6a662c0628fc3f51cbe6486ccd..3572f638de66efd37a1ee0eda43ddbbabab64897 100644 --- a/services/formmgr/include/form_timer_option.h +++ b/services/formmgr/include/form_timer_option.h @@ -32,7 +32,7 @@ public: virtual void SetType(const int &type) override; virtual void SetRepeat(bool repeat) override; virtual void SetInterval(const uint64_t &interval) override; - virtual void SetWantAgent(std::shared_ptr wantAgent) override; + virtual void SetWantAgent(std::shared_ptr wantAgent) override; void SetCallbackInfo(std::function callBack); private: @@ -74,7 +74,7 @@ void FormTimerOption::SetInterval(const uint64_t &interval) this->interval = interval; } -void FormTimerOption::SetWantAgent(std::shared_ptr wantAgent) +void FormTimerOption::SetWantAgent(std::shared_ptr wantAgent) { this->wantAgent = wantAgent; } diff --git a/services/formmgr/src/form_mgr_adapter.cpp b/services/formmgr/src/form_mgr_adapter.cpp index 3d9477f1af05bd5bb62a0b8b7ba48d2ca8b1ee4e..1534979cd2131dc40c14b5f792d255acf0d2d35c 100644 --- a/services/formmgr/src/form_mgr_adapter.cpp +++ b/services/formmgr/src/form_mgr_adapter.cpp @@ -14,6 +14,7 @@ */ #include +#include #include "appexecfwk_errors.h" #include "app_log_wrapper.h" @@ -779,7 +780,7 @@ ErrCode FormMgrAdapter::AllotFormById(const FormItemInfo &info, // find in db but not in cache FormRecord dbRecord; ErrCode getDbRet = FormDbCache::GetInstance().GetDBRecord(formId, dbRecord); - if (getDbRet == ERR_OK && (record.userId == currentUserId + if (getDbRet == ERR_OK && (dbRecord.userId == currentUserId || FormDataMgr::GetInstance().IsCallingUidValid(dbRecord.formUserUids))) { return AddNewFormRecord(info, formId, callerToken, wantParams, formInfo); } @@ -1209,7 +1210,9 @@ ErrCode FormMgrAdapter::CreateFormItemInfo(const BundleInfo &bundleInfo, if (formInfo.moduleName == item.moduleName) { itemInfo.AddHapSourceDirs(item.moduleSourceDir); } - itemInfo.AddModuleInfo(item.moduleName, item.moduleSourceDir); + auto moduleSourceDir = std::regex_replace(item.moduleSourceDir, std::regex(Constants::ABS_CODE_PATH), + Constants::LOCAL_BUNDLES); + itemInfo.AddModuleInfo(item.moduleName, moduleSourceDir); } return ERR_OK; } @@ -1247,7 +1250,7 @@ int FormMgrAdapter::SetNextRefreshTime(const int64_t formId, const int64_t nextT APP_LOGE("%{public}s, not self form:%{public}" PRId64 "", __func__, formId); return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; } - + // check bundleName if (bundleName != formRecord.bundleName) { APP_LOGE("%{public}s, not match bundleName:%{public}s", __func__, bundleName.c_str()); diff --git a/services/formmgr/src/form_mgr_service.cpp b/services/formmgr/src/form_mgr_service.cpp index 7eff4a62a66e85c7ae3767620e5c01cd9d6045fb..e61d0f15ae9d196a1fb8cd2b51d183ee3be95871 100644 --- a/services/formmgr/src/form_mgr_service.cpp +++ b/services/formmgr/src/form_mgr_service.cpp @@ -61,8 +61,10 @@ FormMgrService::FormMgrService() FormMgrService::~FormMgrService() { - EventFwk::CommonEventManager::UnSubscribeCommonEvent(formSysEventReceiver_); - formSysEventReceiver_ = nullptr; + if (formSysEventReceiver_ != nullptr) { + EventFwk::CommonEventManager::UnSubscribeCommonEvent(formSysEventReceiver_); + formSysEventReceiver_ = nullptr; + } } bool FormMgrService::IsReady() const diff --git a/services/formmgr/src/form_provider_mgr.cpp b/services/formmgr/src/form_provider_mgr.cpp index dd5655852c6209e4dc0358d3c788e7345d8b2662..a48a5d4b45faf1f5d747270d7915c1aca30213f7 100644 --- a/services/formmgr/src/form_provider_mgr.cpp +++ b/services/formmgr/src/form_provider_mgr.cpp @@ -285,14 +285,18 @@ ErrCode FormProviderMgr::UpdateForm(const int64_t formId, const FormProviderInfo ErrCode FormProviderMgr::UpdateForm(const int64_t formId, FormRecord &formRecord, const FormProviderData &formProviderData) { - APP_LOGI("%{public}s start", __func__); - + APP_LOGI("%{public}s start, imageDateState is %{public}d", __func__, formProviderData.GetImageDataState()); if (formRecord.versionUpgrade) { formRecord.formProviderInfo.SetFormData(formProviderData); formRecord.formProviderInfo.SetUpgradeFlg(true); } else { nlohmann::json addJsonData = formProviderData.GetData(); formRecord.formProviderInfo.MergeData(addJsonData); + // merge image + auto formData = formRecord.formProviderInfo.GetFormData(); + formData.SetImageDataState(formProviderData.GetImageDataState()); + formData.SetImageDataMap(formProviderData.GetImageDataMap()); + formRecord.formProviderInfo.SetFormData(formData); } // formRecord init diff --git a/services/formmgr/src/form_timer_mgr.cpp b/services/formmgr/src/form_timer_mgr.cpp index 87afae21727d63f52d70bc07d8f4703f514bd1d4..6ad670ee25c3fcff56624b2f0969b807c5951fd3 100644 --- a/services/formmgr/src/form_timer_mgr.cpp +++ b/services/formmgr/src/form_timer_mgr.cpp @@ -1143,8 +1143,8 @@ void FormTimerMgr::EnsureInitIntervalTimer() APP_LOGI("%{public}s, init base timer task", __func__); auto timerOption = std::make_shared(); timerOption->SetType(TIMER_TYPE_ELAPSED_REALTIME); - timerOption->SetRepeat(false); - timerOption->SetInterval(0); + timerOption->SetRepeat(true); + timerOption->SetInterval(static_cast(Constants::MIN_PERIOD)); timerOption->SetWantAgent(nullptr); timerOption->SetCallbackInfo([]() { FormTimerMgr::GetInstance().OnIntervalTimeOut(); }); diff --git a/services/formmgr/src/form_util.cpp b/services/formmgr/src/form_util.cpp index e3ae26a8152e4d996e55f44ccde7dcf3184aade6..24a818a65cfdf385ff40e48cb6f202b509c682df 100644 --- a/services/formmgr/src/form_util.cpp +++ b/services/formmgr/src/form_util.cpp @@ -20,6 +20,7 @@ #include #include "app_log_wrapper.h" +#include "bundle_constants.h" #include "form_constants.h" #include "form_util.h" #include "ohos_account_kits.h" @@ -190,25 +191,19 @@ std::vector FormUtil::StringSplit(const std::string &in, const std: */ int FormUtil::GetCurrentAccountId() { - std::vector osAccountInfos; - ErrCode ret = AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(osAccountInfos); + std::vector osActiveAccountIds; + ErrCode ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(osActiveAccountIds); if (ret != ERR_OK) { - APP_LOGE("QueryAllCreatedOsAccounts failed."); - return 0; + APP_LOGE("QueryActiveOsAccountIds failed."); + return Constants::ANY_USERID; } - if (osAccountInfos.empty()) { - APP_LOGE("osAccountInfos is empty, no accounts."); - return 0; + if (osActiveAccountIds.empty()) { + APP_LOGE("QueryActiveOsAccountIds is empty, no accounts."); + return Constants::ANY_USERID; } - for (const auto& account : osAccountInfos) { - if (account.GetIsActived()) { - return account.GetLocalId(); - } - } - APP_LOGE("GetCurrentAccountId failed, no Actived now."); - return 0; + return osActiveAccountIds.front(); } } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/test/mock/include/mock_ability_manager.h b/services/formmgr/test/mock/include/mock_ability_manager.h index 1471e06786061003bfaac3306805a6f80642e335..6edb24db9ccbb685277549e7dc31f1a185897342 100644 --- a/services/formmgr/test/mock/include/mock_ability_manager.h +++ b/services/formmgr/test/mock/include/mock_ability_manager.h @@ -268,7 +268,7 @@ public: { return 0; } - int NotifyContinuationResult(int32_t missionId, const int32_t result) override + int NotifyContinuationResult(int32_t missionId, int32_t result) override { return 0; } @@ -329,7 +329,10 @@ public: { return 0; } - + virtual int MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) override + { + return 0; + } virtual int SetMissionLabel(const sptr &token, const std::string &lable) override { @@ -430,6 +433,11 @@ public: { return 0; } + virtual int CloseAbility(const sptr &token, int resultCode = DEFAULT_INVAL_VALUE, + const Want *resultWant = nullptr) override + { + return 0; + } virtual int MinimizeAbility(const sptr &token, bool fromUser) override { return 0; @@ -709,7 +717,7 @@ public: { return 0; } - int NotifyContinuationResult(int32_t missionId, const int32_t result) override + int NotifyContinuationResult(int32_t missionId, int32_t result) override { return 0; } @@ -798,6 +806,10 @@ public: { return 0; } + virtual int MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) override + { + return 0; + } virtual int StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag) override { return 0; @@ -853,9 +865,9 @@ public: { return 0; } - virtual bool SendANRProcessID(int pid) + virtual int SendANRProcessID(int pid) { - return true; + return 0; } virtual int StartAbilityByCall( const Want &want, const sptr &connect, const sptr &callerToken) override diff --git a/services/formmgr/test/mock/include/mock_bundle_manager.h b/services/formmgr/test/mock/include/mock_bundle_manager.h index a4db213117d6cb997f5197a357ebbe0b2cc52082..b833123f9a4b78e6f411569c1652e57871bb78a6 100755 --- a/services/formmgr/test/mock/include/mock_bundle_manager.h +++ b/services/formmgr/test/mock/include/mock_bundle_manager.h @@ -40,7 +40,6 @@ public: bool(const std::string &bundleName, const std::string &permission, const int userId)); MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); - MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); MOCK_METHOD2(RegisterPermissionsChanged, @@ -158,12 +157,6 @@ public: { return true; } - // clears cache data of a specified application. - virtual bool CleanBundleCacheFiles( - const std::string &bundleName, const sptr &cleanCacheCallback) override - { - return true; - } virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0) override { return true; @@ -240,10 +233,6 @@ public: { return true; } - virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override - { - return true; - } virtual bool GetBundleInfo( const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) override; @@ -255,7 +244,6 @@ public: class BundleMgrStub : public IRemoteStub { public: - DECLARE_INTERFACE_DESCRIPTOR(u"IBundleMgr"); virtual int OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; }; @@ -271,7 +259,6 @@ public: bool(const std::string &bundleName, const std::string &permission, const int userId)); MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); - MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); MOCK_METHOD2(RegisterPermissionsChanged, @@ -364,12 +351,6 @@ public: { return true; }; - // clears cache data of a specified application. - virtual bool CleanBundleCacheFiles( - const std::string &bundleName, const sptr &cleanCacheCallback) override - { - return true; - }; virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override { @@ -409,10 +390,6 @@ public: return true; }; - virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override - { - return true; - }; virtual bool GetBundleGidsByUid(const std::string &bundleName, const int &uid, std::vector &gids) override { return true; @@ -485,7 +462,8 @@ public: return true; } virtual bool NotifyAbilityLifeStatus( - const std::string &bundleName, const std::string &abilityName, const int64_t launchTime, const int uid = 0) override + const std::string &bundleName, const std::string &abilityName, + const int64_t launchTime, const int uid = 0) override { return true; } diff --git a/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp b/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp index 2b29e51a9f858eec7b2c2ec176467de61ad1a13b..2388329a8ad8024337b0521f529a4ea82cd2147a 100644 --- a/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp +++ b/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp @@ -67,13 +67,13 @@ public: protected: sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); - - sptr mockBundleMgr_; - sptr mockAbilityMgrServ_; }; void FmsFormHostRecordTest::SetUpTestCase() -{} +{ + FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); + FormAmsHelper::GetInstance().SetAbilityManager(new MockAbilityMgrService()); +} void FmsFormHostRecordTest::TearDownTestCase() {} @@ -81,14 +81,6 @@ void FmsFormHostRecordTest::TearDownTestCase() void FmsFormHostRecordTest::SetUp() { formyMgrServ_->OnStart(); - - mockBundleMgr_ = new (std::nothrow) BundleMgrService(); - EXPECT_TRUE(mockBundleMgr_ != nullptr); - FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); - - mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); - FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); - token_ = new (std::nothrow) MockFormHostClient(); // Permission install diff --git a/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp index e6cad4e0edc7752ef33a9b13b06a592dae3d3e5f..7e7d4e26407a8762694a498b2e27858c1efe0c3e 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp @@ -23,6 +23,8 @@ #include "form_host_interface.h" #define private public #include "form_mgr.h" +#include "form_info.h" +#include "form_info_mgr.h" #undef private #include "form_mgr_service.h" #include "if_system_ability_manager.h" @@ -71,30 +73,20 @@ public: protected: sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); - - sptr mockBundleMgr_; - sptr mockAbilityMgrServ_; }; void FmsFormMgrAddFormTest::SetUpTestCase() -{} +{ + FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); + FormAmsHelper::GetInstance().SetAbilityManager(new MockAbilityMgrService()); +} void FmsFormMgrAddFormTest::TearDownTestCase() {} void FmsFormMgrAddFormTest::SetUp() { - // APP_LOGI("fms_form_mgr_client_test_001 setup"); formyMgrServ_->OnStart(); - - mockBundleMgr_ = new (std::nothrow) BundleMgrService(); - EXPECT_TRUE(mockBundleMgr_ != nullptr); - FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); - - mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); - FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); - - // APP_LOGI("fms_form_mgr_client_test_001 FormMgrService started"); token_ = new (std::nothrow) MockFormHostClient(); // Permission install @@ -116,7 +108,9 @@ void FmsFormMgrAddFormTest::SetUp() } void FmsFormMgrAddFormTest::TearDown() -{} +{ + formyMgrServ_->OnStop(); +} /* * Feature: FormMgrService @@ -554,4 +548,108 @@ HWTEST_F(FmsFormMgrAddFormTest, AddForm_008, TestSize.Level0) } GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_008 end"; } + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: AddForm Function + * FunctionPoints: FormMgr AddForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Add form with cache info. + */ +HWTEST_F(FmsFormMgrAddFormTest, AddForm_009, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_009 start"; + + int64_t formId = 0x0abcdabc00000000; + int callingUid {0}; + // Set cache + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record1.SetModuleName(PARAM_PROVIDER_MODULE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetFormName(PARAM_FORM_NAME); + record1.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); + record1.SetTemporaryFlag(false); + + FormInfoMgr::GetInstance().GetOrCreateBundleFromInfo(FORM_PROVIDER_BUNDLE_NAME); + FormInfo formInfo1; + formInfo1.moduleName = PARAM_PROVIDER_MODULE_NAME; + formInfo1.name = PARAM_FORM_NAME; + formInfo1.abilityName = FORM_PROVIDER_ABILITY_NAME; + formInfo1.bundleName = FORM_PROVIDER_BUNDLE_NAME; + formInfo1.supportDimensions.push_back(PARAM_FORM_DIMENSION_VALUE); + FormInfoMgr::GetInstance().bundleFormInfoMap_[FORM_PROVIDER_BUNDLE_NAME]->formInfos_.push_back(formInfo1); + + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + retFormRec.updateAtHour = 1; + retFormRec.updateAtMin = 1; + FormDataMgr::GetInstance().UpdateFormRecord(formId, retFormRec); + // Set database info + FormDBInfo formDBInfo(formId, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set form host record + FormDataMgr::GetInstance().AllotFormHostRecord(record1, token_, formId, callingUid); + + FormJsInfo formJsInfo; + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, PARAM_FORM_DIMENSION_VALUE); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, false); + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + + GTEST_LOG_(INFO) << "formId :"<Wait(); + + size_t dataCnt {1}; + size_t formUserUidCnt {1}; + size_t zero {0}; + // Cache params updated. + FormRecord formInfo; + bool ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_TRUE(ret); + EXPECT_EQ(formUserUidCnt, formInfo.formUserUids.size()); + // database info updated. + std::vector formDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + FormDBInfo dbInfo {formDBInfos[0]}; + EXPECT_EQ(formId, dbInfo.formId); + EXPECT_EQ(formUserUidCnt, dbInfo.formUserUids.size()); + // Form host record not changed. + FormDataMgr::GetInstance().ClearFormRecords(); + FormRecord formInfo2; + ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo2); + EXPECT_FALSE(ret); + EXPECT_EQ(zero, formInfo2.formUserUids.size()); + formDBInfos.clear(); + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + dbInfo = formDBInfos[0]; + EXPECT_EQ(formId, dbInfo.formId); + EXPECT_EQ(formUserUidCnt, dbInfo.formUserUids.size()); + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().AddForm(formId, want, token_, formJsInfo)); + token_->Wait(); + FormRecord formInfo3; + ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo3); + EXPECT_TRUE(ret); + EXPECT_EQ(formUserUidCnt, formInfo3.formUserUids.size()); + formDBInfos.clear(); + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + dbInfo = formDBInfos[0]; + EXPECT_EQ(formId, dbInfo.formId); + EXPECT_EQ(formUserUidCnt, dbInfo.formUserUids.size()); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_009 end"; +} } \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_mgr_cast_temp_form_test/fms_form_mgr_cast_temp_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_cast_temp_form_test/fms_form_mgr_cast_temp_form_test.cpp index 9dd4306f69d7445d388caaf6e90e1718683d47c5..cd116a163b87249677aa54f07fa8f49e62ab70bf 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_cast_temp_form_test/fms_form_mgr_cast_temp_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_cast_temp_form_test/fms_form_mgr_cast_temp_form_test.cpp @@ -70,13 +70,13 @@ public: protected: sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); - - sptr mockBundleMgr_; - sptr mockAbilityMgrServ_; }; void FmsFormMgrCastTempFormTest::SetUpTestCase() -{} +{ + FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); + FormAmsHelper::GetInstance().SetAbilityManager(new MockAbilityMgrService()); +} void FmsFormMgrCastTempFormTest::TearDownTestCase() {} @@ -84,14 +84,6 @@ void FmsFormMgrCastTempFormTest::TearDownTestCase() void FmsFormMgrCastTempFormTest::SetUp() { formyMgrServ_->OnStart(); - - mockBundleMgr_ = new (std::nothrow) BundleMgrService(); - ASSERT_TRUE(mockBundleMgr_ != nullptr); - FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); - - mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); - FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); - token_ = new (std::nothrow) MockFormHostClient(); // Permission install diff --git a/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/fms_form_mgr_death_callback_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/fms_form_mgr_death_callback_test.cpp index f9b45712fd4874fd9d63f026fffb4bbe1efa2395..a28dee10fdda2ff2ab35cffa6acdf77eec105f0a 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/fms_form_mgr_death_callback_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/fms_form_mgr_death_callback_test.cpp @@ -72,30 +72,20 @@ public: protected: sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); - - sptr mockBundleMgr_; - sptr mockAbilityMgrServ_; }; void FmsFormMgrDeathCallbackTest::SetUpTestCase() -{} +{ + FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); + FormAmsHelper::GetInstance().SetAbilityManager(new MockAbilityMgrService()); +} void FmsFormMgrDeathCallbackTest::TearDownTestCase() {} void FmsFormMgrDeathCallbackTest::SetUp() { - // APP_LOGI("fms_form_mgr_client_test_001 setup"); formyMgrServ_->OnStart(); - - mockBundleMgr_ = new (std::nothrow) BundleMgrService(); - EXPECT_TRUE(mockBundleMgr_ != nullptr); - FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); - - mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); - FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); - - // APP_LOGI("fms_form_mgr_client_test_001 FormMgrService started"); token_ = new (std::nothrow) MockFormHostClient(); // Permission install diff --git a/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/fms_form_mgr_delete_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/fms_form_mgr_delete_form_test.cpp index d0ec63205f1c316a60b86966b7a773454f64bf51..0f35979671fdb3f3bba40f9d009b301bb124e74c 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/fms_form_mgr_delete_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/fms_form_mgr_delete_form_test.cpp @@ -67,13 +67,13 @@ public: protected: sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); - - sptr mockBundleMgr_; - sptr mockAbilityMgrServ_; }; void FmsFormMgrDeleteFormTest::SetUpTestCase() -{} +{ + FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); + FormAmsHelper::GetInstance().SetAbilityManager(new MockAbilityMgrService()); +} void FmsFormMgrDeleteFormTest::TearDownTestCase() {} @@ -81,14 +81,6 @@ void FmsFormMgrDeleteFormTest::TearDownTestCase() void FmsFormMgrDeleteFormTest::SetUp() { formyMgrServ_->OnStart(); - - mockBundleMgr_ = new (std::nothrow) BundleMgrService(); - EXPECT_TRUE(mockBundleMgr_ != nullptr); - FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); - - mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); - FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); - token_ = new (std::nothrow) MockFormHostClient(); // Permission install diff --git a/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp index 045433d88f0cb1d388eb92f59bd8a9e875694873..1718061927e7b57c7bf0375a7bc6085d8506d452 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp @@ -56,27 +56,22 @@ public: void InitFormItemInfo(int64_t formId, FormItemInfo &formItemInfo) const; protected: - sptr mockBundleMgr_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); sptr token_; }; void FmsFormMgrLifecycleUpdateTest::SetUpTestCase() -{} +{ + FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); +} void FmsFormMgrLifecycleUpdateTest::TearDownTestCase() {} void FmsFormMgrLifecycleUpdateTest::SetUp() { - // APP_LOGI("fms_form_mgr_enable_update_test_001 setup"); formyMgrServ_->OnStart(); - // mock BundleMgr - mockBundleMgr_ = new (std::nothrow) BundleMgrService(); - ASSERT_TRUE(mockBundleMgr_ != nullptr); - FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); - // token token_ = new (std::nothrow) MockFormHostClient(); diff --git a/services/formmgr/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp index efa7bc176640925699a4dbb43db945464055118c..cc7870b1dcf6641b1715459f74dd2e714c7ed8f3 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp @@ -69,13 +69,13 @@ public: protected: sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); - - sptr mockBundleMgr_; - sptr mockAbilityMgrServ_; }; void FmsFormMgrMessageEventTest::SetUpTestCase() -{} +{ + FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); + FormAmsHelper::GetInstance().SetAbilityManager(new MockAbilityMgrService()); +} void FmsFormMgrMessageEventTest::TearDownTestCase() {} @@ -83,14 +83,6 @@ void FmsFormMgrMessageEventTest::TearDownTestCase() void FmsFormMgrMessageEventTest::SetUp() { formyMgrServ_->OnStart(); - - mockBundleMgr_ = new (std::nothrow) BundleMgrService(); - EXPECT_TRUE(mockBundleMgr_ != nullptr); - FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); - - mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); - FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); - token_ = new (std::nothrow) MockFormHostClient(); // Permission install diff --git a/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/fms_form_mgr_notify_invisible_forms_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/fms_form_mgr_notify_invisible_forms_test.cpp index 4f5adb323644a65f7abc2b66fd7eccaee70487dc..bb38d6a70fd7392108626bd9879b8335d02f9482 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/fms_form_mgr_notify_invisible_forms_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/fms_form_mgr_notify_invisible_forms_test.cpp @@ -45,36 +45,27 @@ const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; class FmsFormMgrNotifyInvisibleFormsTest : public testing::Test { public: - FmsFormMgrNotifyInvisibleFormsTest() : formMgrService_(nullptr) - {} - ~FmsFormMgrNotifyInvisibleFormsTest() - {} static void SetUpTestCase(void); static void TearDownTestCase(void); void SetUp(); void TearDown(); protected: sptr token_; - sptr mockBundleMgr_; - std::shared_ptr formMgrService_ = DelayedSingleton::GetInstance(); + std::shared_ptr formMgrService_; }; void FmsFormMgrNotifyInvisibleFormsTest::SetUpTestCase(void) -{} +{ + FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); +} void FmsFormMgrNotifyInvisibleFormsTest::TearDownTestCase(void) {} void FmsFormMgrNotifyInvisibleFormsTest::SetUp(void) { - formMgrService_ = std::make_shared(); - + formMgrService_ = DelayedSingleton::GetInstance(); formMgrService_->OnStart(); - // mock BundleMgr - mockBundleMgr_ = new (std::nothrow) BundleMgrService(); - ASSERT_TRUE(mockBundleMgr_ != nullptr); - FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); - // token token_ = new (std::nothrow) OHOS::AppExecFwk::MockFormHostClient(); @@ -100,7 +91,10 @@ void FmsFormMgrNotifyInvisibleFormsTest::SetUp(void) } void FmsFormMgrNotifyInvisibleFormsTest::TearDown(void) -{} +{ + formMgrService_->OnStop(); + token_ = nullptr; +} /** * @tc.number: FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_002 diff --git a/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp index 843686dbc7cd3893bd5961fd19b5246e3031f542..a5d4d7f233e7e2d088ae013a98c6ec08fd4bd382 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp @@ -56,23 +56,20 @@ public: void TearDown(); protected: sptr token_; - sptr mockBundleMgr_; - std::shared_ptr formMgrService_ = DelayedSingleton::GetInstance(); + std::shared_ptr formMgrService_; }; void FmsFormMgrNotifyVisibleFormsTest::SetUpTestCase(void) -{} +{ + FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); +} void FmsFormMgrNotifyVisibleFormsTest::TearDownTestCase(void) {} void FmsFormMgrNotifyVisibleFormsTest::SetUp(void) { - formMgrService_ = std::make_shared(); + formMgrService_ = DelayedSingleton::GetInstance(); formMgrService_->OnStart(); - - mockBundleMgr_ = new (std::nothrow) BundleMgrService(); - ASSERT_TRUE(mockBundleMgr_ != nullptr); - FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); token_ = new (std::nothrow) MockFormHostClient(); // Permission install diff --git a/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp index ca8bdd6c2a42ae9d79bf821fd2790dd5aaed9b13..d8122862fcb50fc75c600dbe4be1a70d4539cef7 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp @@ -62,11 +62,12 @@ public: protected: sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); - sptr mockBundleMgr_; }; void FmsFormMgrReleaseFormTest::SetUpTestCase() -{} +{ + FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); +} void FmsFormMgrReleaseFormTest::TearDownTestCase() {} @@ -74,9 +75,6 @@ void FmsFormMgrReleaseFormTest::TearDownTestCase() void FmsFormMgrReleaseFormTest::SetUp() { formyMgrServ_->OnStart(); - mockBundleMgr_ = new (std::nothrow) BundleMgrService(); - ASSERT_TRUE(mockBundleMgr_ != nullptr); - FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); token_ = new (std::nothrow) MockFormHostClient(); // Permission install diff --git a/services/formmgr/test/unittest/fms_form_mgr_request_form_test/fms_form_mgr_request_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_request_form_test/fms_form_mgr_request_form_test.cpp index feaecd160542faf7eb4113b37f862ba5294ad14a..08af6003557e775003a456ff6ca32665cf8f3c8b 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_request_form_test/fms_form_mgr_request_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_request_form_test/fms_form_mgr_request_form_test.cpp @@ -57,14 +57,15 @@ public: void TearDown(); protected: - sptr mockAbilityMgrServ_; - sptr mockBundleMgr_; sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); }; void FmsFormMgrRequestFormTest::SetUpTestCase() -{} +{ + FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); + FormAmsHelper::GetInstance().SetAbilityManager(new MockAbilityMgrService()); +} void FmsFormMgrRequestFormTest::TearDownTestCase() {} @@ -72,15 +73,8 @@ void FmsFormMgrRequestFormTest::TearDownTestCase() void FmsFormMgrRequestFormTest::SetUp() { formyMgrServ_->OnStart(); - token_ = new (std::nothrow) MockFormHostClient(); - mockBundleMgr_ = new (std::nothrow) BundleMgrService(); - ASSERT_TRUE(mockBundleMgr_ != nullptr); - FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); - - mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); - FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); // Permission install std::vector permList; Permission::PermissionDef permDef; diff --git a/services/formmgr/test/unittest/fms_form_mgr_update_form_test/fms_form_mgr_update_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_update_form_test/fms_form_mgr_update_form_test.cpp index 559958c4f72d4edba4e72370eaa70fceb3052a70..311ee272f6fe04bc3677a9026490d01ec52476ac 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_update_form_test/fms_form_mgr_update_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_update_form_test/fms_form_mgr_update_form_test.cpp @@ -63,13 +63,13 @@ public: protected: sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); - - sptr mockBundleMgr_; - sptr mockAbilityMgrServ_; }; void FmsFormMgrUpdateFormTest::SetUpTestCase() -{} +{ + FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); + FormAmsHelper::GetInstance().SetAbilityManager(new MockAbilityMgrService()); +} void FmsFormMgrUpdateFormTest::TearDownTestCase() {} @@ -77,16 +77,7 @@ void FmsFormMgrUpdateFormTest::TearDownTestCase() void FmsFormMgrUpdateFormTest::SetUp() { APP_LOGI("fms_form_mgr_client_updateForm_test_001 setup"); - formyMgrServ_->OnStart(); - - mockBundleMgr_ = new (std::nothrow) BundleMgrService(); - ASSERT_TRUE(mockBundleMgr_ != nullptr); - FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); - - mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); - FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); - token_ = new (std::nothrow) MockFormHostClient(); // Permission install diff --git a/services/formmgr/test/unittest/fms_form_provider_mgr_test/fms_form_provider_mgr_test.cpp b/services/formmgr/test/unittest/fms_form_provider_mgr_test/fms_form_provider_mgr_test.cpp index cec93e35f57136a431338a6ed079da5aa2f2359a..a7ccb2ab73e8b038321645ce00b51c8a9ae78ada 100644 --- a/services/formmgr/test/unittest/fms_form_provider_mgr_test/fms_form_provider_mgr_test.cpp +++ b/services/formmgr/test/unittest/fms_form_provider_mgr_test/fms_form_provider_mgr_test.cpp @@ -68,30 +68,20 @@ public: protected: sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); - - sptr mockBundleMgr_; - sptr mockAbilityMgrServ_; }; void FmsFormProviderMgrTest::SetUpTestCase() -{} +{ + FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); + FormAmsHelper::GetInstance().SetAbilityManager(new MockAbilityMgrService()); +} void FmsFormProviderMgrTest::TearDownTestCase() {} void FmsFormProviderMgrTest::SetUp() { - // APP_LOGI("fms_form_mgr_client_test_001 setup"); formyMgrServ_->OnStart(); - - mockBundleMgr_ = new (std::nothrow) BundleMgrService(); - EXPECT_TRUE(mockBundleMgr_ != nullptr); - FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); - - mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); - FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); - - // APP_LOGI("fms_form_mgr_client_test_001 FormMgrService started"); token_ = new (std::nothrow) MockFormHostClient(); // Permission install diff --git a/services/formmgr/test/unittest/fms_form_set_next_refresh_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/BUILD.gn index 4c5aa8506d649f3309c82609f124c0975dc1877e..363a26ca4ab6bcbe10c87dcc74c5b8c198681811 100644 --- a/services/formmgr/test/unittest/fms_form_set_next_refresh_test/BUILD.gn +++ b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/BUILD.gn @@ -61,8 +61,8 @@ ohos_unittest("FmsFormSetNextRefreshTest") { "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${services_path}/formmgr:fms_target", "//base/miscservices/time/services:time_service", - "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", #"${libs_path}/libeventhandler:libeventhandler_target", diff --git a/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp index c363f16e3a2b47b72c509f68f05106fe8876a3d3..7d18793db1e47d023bc416d3c57b93e9cba33465 100644 --- a/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp +++ b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp @@ -49,35 +49,32 @@ public: {} ~FmsFormSetNextRefreshTest() {} - std::shared_ptr formSetNextRefresh_ = DelayedSingleton::GetInstance(); static void SetUpTestCase(void); static void TearDownTestCase(void); void SetUp(); void TearDown(); protected: - sptr mockBundleMgr_; + std::shared_ptr formSetNextRefresh_; }; + void FmsFormSetNextRefreshTest::SetUpTestCase(void) -{} +{ + FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); +} void FmsFormSetNextRefreshTest::TearDownTestCase(void) {} void FmsFormSetNextRefreshTest::SetUp(void) { - formSetNextRefresh_ = std::make_shared(); - + formSetNextRefresh_ = DelayedSingleton::GetInstance(); formSetNextRefresh_->OnStart(); - - // mock BundleMgr - mockBundleMgr_ = new (std::nothrow) BundleMgrService(); - ASSERT_TRUE(mockBundleMgr_ != nullptr); - FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); } void FmsFormSetNextRefreshTest::TearDown(void) -{} - +{ + formSetNextRefresh_->OnStop(); +} /** * @tc.number: FmsFormSetNextRefreshTest_SetNextRefreshTime_001 diff --git a/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/BUILD.gn index e0bbbf6854d11781fe899d59fa651be34ff12f54..da54f852aee343033bfac8a98526a645591e5b3b 100644 --- a/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/BUILD.gn +++ b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/BUILD.gn @@ -62,8 +62,8 @@ ohos_unittest("FmsFormSysEventReceiverTest") { "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", "${services_path}/formmgr:fms_target", "//base/miscservices/time/services:time_service", - "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/want:want", diff --git a/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp index ada590a92a1c663f0f32c6b9cd07cdec0bbff63e..15ec57859335cf3ebf0f4409d858cde6dc3c103e 100644 --- a/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp +++ b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp @@ -82,30 +82,20 @@ public: protected: sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); - - sptr mockBundleMgr_; - sptr mockAbilityMgrServ_; }; void FmsFormSysEventReceiverTest::SetUpTestCase() -{} +{ + FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); + FormAmsHelper::GetInstance().SetAbilityManager(new MockAbilityMgrService()); +} void FmsFormSysEventReceiverTest::TearDownTestCase() {} void FmsFormSysEventReceiverTest::SetUp() { - // APP_LOGI("fms_form_mgr_client_test_001 setup"); formyMgrServ_->OnStart(); - - mockBundleMgr_ = new (std::nothrow) BundleMgrService(); - EXPECT_TRUE(mockBundleMgr_ != nullptr); - FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); - - mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); - FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); - - // APP_LOGI("fms_form_mgr_client_test_001 FormMgrService started"); token_ = new (std::nothrow) MockFormHostClient(); // Permission install diff --git a/services/formmgr/test/unittest/fms_form_timer_mgr_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_timer_mgr_test/BUILD.gn index 2dded5ef49f7735f9645e19bcf57aaecd71d6d0a..be9e602488df0033635733bfd91e579242fab7a0 100644 --- a/services/formmgr/test/unittest/fms_form_timer_mgr_test/BUILD.gn +++ b/services/formmgr/test/unittest/fms_form_timer_mgr_test/BUILD.gn @@ -39,17 +39,17 @@ ohos_unittest("FmsFormTimerMgrTest") { "${appexecfwk_path}/common:libappexecfwk_common", "${services_path}/formmgr:fms_target", "//base/miscservices/time/services:time_service", - "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", "//base/notification/ces_standard/frameworks/common:libevent_common", + "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", "//third_party/googletest:gmock_main", "//utils/native/base:utils", ] external_deps = [ + "ability_base:base", + "ability_base:want", "ability_runtime:app_manager", - "ability_runtime:base", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", diff --git a/services/formmgr/test/unittest/fms_form_timer_mgr_test/fms_form_timer_mgr_test.cpp b/services/formmgr/test/unittest/fms_form_timer_mgr_test/fms_form_timer_mgr_test.cpp index e41de5bc00a17ef34651ae5448d870d61e196bd8..0e1a0d43edcbdb8a9e5753b29128d2c20e41e4be 100644 --- a/services/formmgr/test/unittest/fms_form_timer_mgr_test/fms_form_timer_mgr_test.cpp +++ b/services/formmgr/test/unittest/fms_form_timer_mgr_test/fms_form_timer_mgr_test.cpp @@ -539,9 +539,6 @@ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0027, Function | MediumTest | Lev GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0027 start"; bool isAddOk4 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_6, 10, 30, 0); EXPECT_EQ(isAddOk4, true); - - std::this_thread::sleep_for(std::chrono::milliseconds(Constants::MIN_PERIOD)); - GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0027 end"; } } 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 3707f0dd010db4a3ecf8779b84293192b1f3c6e5..68b2e0fe79c634a9f6363c5747b34f58d60d1c48 100644 --- a/services/test/mock/include/appmgr/mock_ability_mgr_host.h +++ b/services/test/mock/include/appmgr/mock_ability_mgr_host.h @@ -55,6 +55,11 @@ public: { return 0; } + virtual int CloseAbility(const sptr &token, int resultCode = DEFAULT_INVAL_VALUE, + const Want *resultWant = nullptr) override + { + return 0; + } virtual int MinimizeAbility(const sptr &token, bool fromUser) override { return 0; @@ -313,7 +318,7 @@ public: { return 0; } - int NotifyContinuationResult(int32_t missionId, const int32_t result) override + int NotifyContinuationResult(int32_t missionId, int32_t result) override { return 0; } @@ -375,6 +380,10 @@ public: { return 0; } + virtual int MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) override + { + return 0; + } virtual int StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag) override { return 0; diff --git a/services/test/mock/include/mock_ability_mgr_service.h b/services/test/mock/include/mock_ability_mgr_service.h index 83fe2e1c4b33e5532f2c4b05e6fbde0fff269861..4a7448c6c713f233b4f92c5c60d53ccaf893ec2a 100644 --- a/services/test/mock/include/mock_ability_mgr_service.h +++ b/services/test/mock/include/mock_ability_mgr_service.h @@ -29,6 +29,12 @@ public: int32_t userId, int requestCode)); MOCK_METHOD2(TerminateAbilityByCaller, int(const sptr &callerToken, int requestCode)); MOCK_METHOD3(TerminateAbility, int(const sptr &token, int resultCode, const Want *resultWant)); + virtual int CloseAbility(const sptr &token, int resultCode = DEFAULT_INVAL_VALUE, + const Want *resultWant = nullptr) override + { + return 0; + } + virtual int MinimizeAbility(const sptr &token, bool fromUser = false) override { return 0; @@ -96,7 +102,7 @@ public: MOCK_METHOD1(SetShowOnLockScreen, int(bool isAllow)); MOCK_METHOD1(GetSystemMemoryAttr, void(AppExecFwk::SystemMemoryAttr &memoryInfo)); MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); - MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result)); + MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, int32_t result)); MOCK_METHOD5(ContinueMission, int(const std::string &srcDeviceId, const std::string &dstDeviceId, int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams)); MOCK_METHOD2(ContinueAbility, int(const std::string &deviceId, int32_t missionId)); @@ -112,6 +118,7 @@ public: MOCK_METHOD1(CleanMission, int(int32_t missionId)); MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); + MOCK_METHOD2(MoveMissionToFront, int(int32_t missionId, const StartOptions &startOptions)); MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD1(ClearUpApplicationData, int(const std::string &)); @@ -185,9 +192,9 @@ public: return true; } - virtual bool SendANRProcessID(int pid) override + virtual int SendANRProcessID(int pid) override { - return true; + return 0; } virtual int StartUserTest(const Want &want, const sptr &observer) override diff --git a/services/test/mock/include/mock_ability_scheduler.h b/services/test/mock/include/mock_ability_scheduler.h index b4afe3f78cca5d9149c8dbcc8ee1c7682e2af15a..a5ab5274fef0fa390b0291b97ecb6d5a65caf1b4 100755 --- a/services/test/mock/include/mock_ability_scheduler.h +++ b/services/test/mock/include/mock_ability_scheduler.h @@ -42,9 +42,9 @@ public: ScheduleUnregisterObserver, bool(const Uri &uri, const sptr &dataObserver)); MOCK_METHOD1(ScheduleNotifyChange, bool(const Uri &uri)); MOCK_METHOD1(ExecuteBatch, std::vector>(const std::vector> &operations)); - MOCK_METHOD1(NotifyContinuationResult, void(const int32_t result)); + MOCK_METHOD1(NotifyContinuationResult, void(int32_t result)); MOCK_METHOD1(ContinueAbility, void(const std::string& deviceId)); - MOCK_METHOD1(DumpAbilityInfo, void(std::vector &info)); + MOCK_METHOD2(DumpAbilityInfo, void(const std::vector ¶ms, std::vector &info)); std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) { std::vector types; diff --git a/services/test/mock/include/mock_ability_scheduler_stub.h b/services/test/mock/include/mock_ability_scheduler_stub.h index 1913d5afb088e839c3f1d10432e28b0e698e94af..5e36df317adb91c9d33653e3639f2a032a2f9b15 100755 --- a/services/test/mock/include/mock_ability_scheduler_stub.h +++ b/services/test/mock/include/mock_ability_scheduler_stub.h @@ -51,9 +51,9 @@ public: MOCK_METHOD1(ScheduleNotifyChange, bool(const Uri &uri)); MOCK_METHOD1(ExecuteBatch, std::vector>( const std::vector> &operations)); - MOCK_METHOD1(NotifyContinuationResult, void(const int32_t result)); + MOCK_METHOD1(NotifyContinuationResult, void(int32_t result)); MOCK_METHOD1(ContinueAbility, void(const std::string& deviceId)); - MOCK_METHOD1(DumpAbilityInfo, void(std::vector &info)); + MOCK_METHOD2(DumpAbilityInfo, void(const std::vector ¶ms, std::vector &info)); virtual sptr CallRequest() { diff --git a/services/test/mock/include/mock_app_mgr_client.h b/services/test/mock/include/mock_app_mgr_client.h index fd8b3a43e60d4fdc14b7659c410cce110c92076e..c7ba6fdf679d031afd6861a0110726d3114f2a19 100644 --- a/services/test/mock/include/mock_app_mgr_client.h +++ b/services/test/mock/include/mock_app_mgr_client.h @@ -25,8 +25,8 @@ class MockAppMgrClient : public AppMgrClient { public: MockAppMgrClient(); ~MockAppMgrClient(); - MOCK_METHOD4(LoadAbility, AppMgrResultCode(const sptr &, const sptr &, - const AbilityInfo &, const ApplicationInfo &)); + MOCK_METHOD5(LoadAbility, AppMgrResultCode(const sptr &, const sptr &, + const AbilityInfo &, const ApplicationInfo &, const AAFwk::Want &)); MOCK_METHOD1(TerminateAbility, AppMgrResultCode(const sptr &)); MOCK_METHOD2(UpdateAbilityState, AppMgrResultCode(const sptr &token, const AbilityState state)); MOCK_METHOD1(KillApplication, AppMgrResultCode(const std::string &)); diff --git a/services/test/mock/include/mock_app_scheduler.h b/services/test/mock/include/mock_app_scheduler.h index 1deff873f8eed0b28bc83c82cb9c9dd3e4680325..df33e11b7a97692839d60f704c59abae761e4ea8 100644 --- a/services/test/mock/include/mock_app_scheduler.h +++ b/services/test/mock/include/mock_app_scheduler.h @@ -34,7 +34,8 @@ public: MOCK_METHOD0(ScheduleBackgroundApplication, void()); MOCK_METHOD0(ScheduleTerminateApplication, void()); MOCK_METHOD2(ScheduleLaunchApplication, void(const AppExecFwk::AppLaunchData &, const Configuration &config)); - MOCK_METHOD2(ScheduleLaunchAbility, void(const AppExecFwk::AbilityInfo &, const sptr &)); + MOCK_METHOD3(ScheduleLaunchAbility, void(const AppExecFwk::AbilityInfo &, const sptr &, + const std::shared_ptr &)); MOCK_METHOD1(ScheduleCleanAbility, void(const sptr &)); MOCK_METHOD1(ScheduleProfileChanged, void(const AppExecFwk::Profile &)); MOCK_METHOD1(ScheduleConfigurationUpdated, void(const AppExecFwk::Configuration &config)); diff --git a/services/test/mock/include/mock_bundle_mgr.h b/services/test/mock/include/mock_bundle_mgr.h index 127a7b8be033a05f7c0cece161fca71127ad0e6a..7d6a92b32791d90bce78916e273d087a64367519 100644 --- a/services/test/mock/include/mock_bundle_mgr.h +++ b/services/test/mock/include/mock_bundle_mgr.h @@ -229,8 +229,6 @@ public: MOCK_METHOD1(HasSystemCapability, bool(const std::string &capName)); MOCK_METHOD1(GetSystemAvailableCapabilities, bool(std::vector &systemCaps)); MOCK_METHOD0(IsSafeMode, bool()); - MOCK_METHOD2(CleanBundleCacheFiles, - bool(const std::string &bundleName, const sptr &cleanCacheCallback)); MOCK_METHOD2(CleanBundleDataFiles, bool(const std::string &bundleName, const int userId)); MOCK_METHOD1(RegisterBundleStatusCallback, bool(const sptr &bundleStatusCallback)); MOCK_METHOD1(ClearBundleStatusCallback, bool(const sptr &bundleStatusCallback)); @@ -238,12 +236,10 @@ public: MOCK_METHOD4( DumpInfos, bool(const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result)); MOCK_METHOD1(IsApplicationEnabled, bool(const std::string &bundleName)); - MOCK_METHOD2(SetApplicationEnabled, bool(const std::string &bundleName, bool isEnable)); MOCK_METHOD0(GetBundleInstaller, sptr()); MOCK_METHOD0(GetBundleUserMgr, sptr()); MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); - MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); @@ -264,7 +260,6 @@ public: class BundleMgrStub : public IRemoteStub { public: - DECLARE_INTERFACE_DESCRIPTOR(u"IBundleMgr"); virtual int OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; }; @@ -295,8 +290,6 @@ public: MOCK_METHOD1(HasSystemCapability, bool(const std::string &capName)); MOCK_METHOD1(GetSystemAvailableCapabilities, bool(std::vector &systemCaps)); MOCK_METHOD0(IsSafeMode, bool()); - MOCK_METHOD2(CleanBundleCacheFiles, - bool(const std::string &bundleName, const sptr &cleanCacheCallback)); MOCK_METHOD2(CleanBundleDataFiles, bool(const std::string &bundleName, const int userId)); MOCK_METHOD1(RegisterBundleStatusCallback, bool(const sptr &bundleStatusCallback)); MOCK_METHOD1(ClearBundleStatusCallback, bool(const sptr &bundleStatusCallback)); @@ -304,7 +297,6 @@ public: MOCK_METHOD4( DumpInfos, bool(const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result)); MOCK_METHOD1(IsApplicationEnabled, bool(const std::string &bundleName)); - MOCK_METHOD2(SetApplicationEnabled, bool(const std::string &bundleName, bool isEnable)); MOCK_METHOD0(GetBundleInstaller, sptr()); MOCK_METHOD0(GetBundleUserMgr, sptr()); MOCK_METHOD3( @@ -313,7 +305,6 @@ public: bool(const std::string &bundleName, const std::string &permission, const int userId)); MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); - MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); @@ -342,8 +333,8 @@ public: }; bool GetApplicationInfo( const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override; - bool NotifyAbilityLifeStatus( - const std::string &bundleName, const std::string &abilityName, const int64_t launchTime, const int uid) override; + bool NotifyAbilityLifeStatus(const std::string &bundleName, const std::string &abilityName, + const int64_t launchTime, const int uid) override; virtual bool CheckIsSystemAppByUid(const int uid) override; virtual bool GetBundleGidsByUid(const std::string &bundleName, const int &uid, std::vector &gids) override { diff --git a/services/test/mock/include/mock_compled_callback.h b/services/test/mock/include/mock_compled_callback.h index 803a3c83d56f16eb4b40736559248a10df8b9c24..ba1ec2b3c53a4f760ea8698d810585ca548a2221 100644 --- a/services/test/mock/include/mock_compled_callback.h +++ b/services/test/mock/include/mock_compled_callback.h @@ -19,11 +19,11 @@ #include "gmock/gmock.h" #include "completed_callback.h" -namespace OHOS::Notification::WantAgent { +namespace OHOS::AbilityRuntime::WantAgent { class MockCompletedCallback : public CompletedCallback { public: MOCK_METHOD4(OnSendFinished, void(const AAFwk::Want &want, int resultCode, const std::string &resultData, const AAFwk::WantParams &resultExtras)); }; -} // namespace OHOS::Notification::WantAgent +} // namespace OHOS::WantAgent #endif \ No newline at end of file diff --git a/services/test/mock/include/mock_want_receiver.h b/services/test/mock/include/mock_want_receiver.h index 17b528b56b4839661d290e14057b72d719101691..997383cc30c93ddd450ea5743060d65dc5b2fc77 100644 --- a/services/test/mock/include/mock_want_receiver.h +++ b/services/test/mock/include/mock_want_receiver.h @@ -27,7 +27,7 @@ public: const WantParams &extras, bool serialized, bool sticky, int sendingUser)); }; -class MockCancelListener : public Notification::WantAgent::CancelListener { +class MockCancelListener : public AbilityRuntime::WantAgent::CancelListener { public: MOCK_METHOD1(OnCancelled, void(int resultCode)); }; diff --git a/services/test/mock/src/mock_bundle_mgr.cpp b/services/test/mock/src/mock_bundle_mgr.cpp index d6927e35ade9e3284f8d390a602ad7e533ba290c..390ba3a2a7162e4a321cfa32128c8e99738d1e5d 100644 --- a/services/test/mock/src/mock_bundle_mgr.cpp +++ b/services/test/mock/src/mock_bundle_mgr.cpp @@ -131,9 +131,8 @@ bool BundleMgrService::QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &ab bool BundleMgrService::GetApplicationInfo( const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) { - if (appName.empty()) { - return false; - } + appInfo.name = "test_app"; + appInfo.bundleName = "com.ix.hiMusic"; return true; } diff --git a/services/test/moduletest/ability_mgr_service_test/BUILD.gn b/services/test/moduletest/ability_mgr_service_test/BUILD.gn index beb1a9a0f44f6f387d268bf2fdff260ae1bafb3d..7114e02f0f5adefb6775bfa4383513d9c4d5abeb 100644 --- a/services/test/moduletest/ability_mgr_service_test/BUILD.gn +++ b/services/test/moduletest/ability_mgr_service_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -69,7 +69,6 @@ ohos_moduletest("ability_mgr_module_test") { "//foundation/aafwk/standard/services/abilitymgr/src/want_sender_info.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/want_sender_stub.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/wants_info.cpp", - "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp", "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/sa_mgr/src/sa_mgr_client_mock.cpp", "//foundation/aafwk/standard/services/test/mock/src/mock_app_mgr_client.cpp", "//foundation/aafwk/standard/services/test/mock/src/mock_bundle_mgr.cpp", @@ -88,6 +87,7 @@ ohos_moduletest("ability_mgr_module_test") { } deps = [ "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", + "${innerkits_path}/uri_permission:uri_permission_mgr", "${innerkits_path}/want:want", "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//base/global/i18n_standard/frameworks/intl:intl_util", @@ -110,6 +110,7 @@ ohos_moduletest("ability_mgr_module_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "bytrace_standard:bytrace_core", "ces_standard:cesfwk_core", "ces_standard:cesfwk_innerkits", diff --git a/services/test/moduletest/ability_mgr_service_test/ability_mgr_module_test.cpp b/services/test/moduletest/ability_mgr_service_test/ability_mgr_module_test.cpp index 1c49229fb3f9eb24ba7555f6ae9512b3e4add2b3..c6e97ec55511bb5477e7982d0f7bca3833966702 100644 --- a/services/test/moduletest/ability_mgr_service_test/ability_mgr_module_test.cpp +++ b/services/test/moduletest/ability_mgr_service_test/ability_mgr_module_test.cpp @@ -160,15 +160,16 @@ static void OnStartAms() if (AbilityMgrModuleTest::abilityMgrServ_->state_ == ServiceRunningState::STATE_RUNNING) { return; } - AbilityMgrModuleTest::abilityMgrServ_->state_ = ServiceRunningState::STATE_RUNNING; AbilityMgrModuleTest::abilityMgrServ_->eventLoop_ = AppExecFwk::EventRunner::Create(AbilityConfig::NAME_ABILITY_MGR_SERVICE); EXPECT_TRUE(AbilityMgrModuleTest::abilityMgrServ_->eventLoop_); - AbilityMgrModuleTest::abilityMgrServ_->handler_ = - std::make_shared(AbilityMgrModuleTest::abilityMgrServ_->eventLoop_, - AbilityMgrModuleTest::abilityMgrServ_); + AbilityMgrModuleTest::abilityMgrServ_->handler_ =std::make_shared( + AbilityMgrModuleTest::abilityMgrServ_->eventLoop_, AbilityMgrModuleTest::abilityMgrServ_); + AbilityMgrModuleTest::abilityMgrServ_->connectManager_ = std::make_shared(); + AbilityMgrModuleTest::abilityMgrServ_->connectManagers_.emplace(0, + AbilityMgrModuleTest::abilityMgrServ_->connectManager_); EXPECT_TRUE(AbilityMgrModuleTest::abilityMgrServ_->handler_); EXPECT_TRUE(AbilityMgrModuleTest::abilityMgrServ_->connectManager_); @@ -176,17 +177,24 @@ static void OnStartAms() SetEventHandler(AbilityMgrModuleTest::abilityMgrServ_->handler_); AbilityMgrModuleTest::abilityMgrServ_->dataAbilityManager_ = std::make_shared(); + AbilityMgrModuleTest::abilityMgrServ_->dataAbilityManagers_.emplace(0, + AbilityMgrModuleTest::abilityMgrServ_->dataAbilityManager_); EXPECT_TRUE(AbilityMgrModuleTest::abilityMgrServ_->dataAbilityManager_); AbilityMgrModuleTest::abilityMgrServ_->amsConfigResolver_ = std::make_shared(); EXPECT_TRUE(AbilityMgrModuleTest::abilityMgrServ_->amsConfigResolver_); AbilityMgrModuleTest::abilityMgrServ_->amsConfigResolver_->Parse(); + AbilityMgrModuleTest::abilityMgrServ_->currentMissionListManager_ = std::make_shared(0); + AbilityMgrModuleTest::abilityMgrServ_->currentMissionListManager_->Init(); + AbilityMgrModuleTest::abilityMgrServ_->pendingWantManager_ = std::make_shared(); EXPECT_TRUE(AbilityMgrModuleTest::abilityMgrServ_->pendingWantManager_); int userId = AbilityMgrModuleTest::abilityMgrServ_->GetUserId(); AbilityMgrModuleTest::abilityMgrServ_->SetStackManager(userId, true); + AbilityMgrModuleTest::abilityMgrServ_->stackManagers_.emplace(0, + AbilityMgrModuleTest::abilityMgrServ_->GetStackManager()); AbilityMgrModuleTest::abilityMgrServ_->systemAppManager_ = std::make_shared(userId); EXPECT_TRUE(AbilityMgrModuleTest::abilityMgrServ_->systemAppManager_); @@ -201,28 +209,24 @@ static void OnStartAms() void AbilityMgrModuleTest::SetUpTestCase(void) { - OHOS::DelayedSingleton::DestroyInstance(); OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, new (std::nothrow) BundleMgrService()); - abilityMgrServ_ = OHOS::DelayedSingleton::GetInstance(); mockAppMgrClient_ = std::make_shared(); - OnStartAms(); } void AbilityMgrModuleTest::TearDownTestCase(void) { - OHOS::DelayedSingleton::DestroyInstance(); - abilityMgrServ_.reset(); + abilityMgrServ_->OnStop(); mockAppMgrClient_.reset(); } + void AbilityMgrModuleTest::SetUp(void) { scheduler_ = new MockAbilityScheduler(); if (!doOnce_) { doOnce_ = true; - MockAppClent(); } WaitAMS(); @@ -281,10 +285,10 @@ std::shared_ptr AbilityMgrModuleTest::GreatePageAbility( const std::string &abilityName, const std::string &bundleName) { Want want = CreateWant(abilityName, bundleName); - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1).WillOnce(Return(AppMgrResultCode::RESULT_OK)); + EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _, _)).Times(1).WillOnce(Return(AppMgrResultCode::RESULT_OK)); int testRequestCode = 1; SetActive(); - abilityMgrServ_->StartAbility(want, testRequestCode); + abilityMgrServ_->StartAbility(want, 0, testRequestCode); WaitAMS(); auto stack = abilityMgrServ_->GetStackManager(); @@ -325,7 +329,8 @@ void AbilityMgrModuleTest::MockDataAbilityLoadHandlerInner(bool &testFailed, spt const sptr &token, const sptr &preToken, const AbilityInfo &abilityInfo, - const ApplicationInfo &appInfo) { + const ApplicationInfo &appInfo, + const Want &want) { dataAbilityToken = token; testFailed = testFailed || (abilityInfo.type != AbilityType::DATA); std::thread(&AbilityManagerService::AttachAbilityThread, abilityMgrServ.get(), mockDataAbilityScheduler, token) @@ -333,7 +338,7 @@ void AbilityMgrModuleTest::MockDataAbilityLoadHandlerInner(bool &testFailed, spt return AppMgrResultCode::RESULT_OK; }; - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1).WillOnce(Invoke(mockLoadAbility)); + EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _, _)).Times(1).WillOnce(Invoke(mockLoadAbility)); int counts = 2; EXPECT_CALL(*mockAppMgrClient_, UpdateAbilityState(_, _)) .Times(counts) @@ -381,14 +386,15 @@ void AbilityMgrModuleTest::MockServiceAbilityLoadHandlerInner( auto mockHandler = [&testResult, &bundleName, &abilityName, &testToken](const sptr &token, const sptr &preToken, const AbilityInfo &abilityInfo, - const ApplicationInfo &appInfo) { + const ApplicationInfo &appInfo, + const Want &want) { testToken = token; testResult = !!testToken && abilityInfo.bundleName == bundleName && abilityInfo.name == abilityName && appInfo.bundleName == bundleName; return AppMgrResultCode::RESULT_OK; }; - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1).WillOnce(Invoke(mockHandler)); + EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _, _)).Times(1).WillOnce(Invoke(mockHandler)); } void AbilityMgrModuleTest::CreateServiceRecord(std::shared_ptr &record, Want &want, @@ -518,51 +524,6 @@ WantSenderInfo AbilityMgrModuleTest::MakeWantSenderInfo(Want &want, int32_t flag return wantSenderInfo; } -/* - * Feature: AaFwk - * Function: ability manager service - * SubFunction: NA - * FunctionPoints: NA - * EnvConditions: NA - * CaseDescription: start ability. - */ -HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_001, TestSize.Level1) -{ - EXPECT_TRUE(abilityMgrServ_); - EXPECT_TRUE(mockAppMgrClient_); - - auto stackManager = abilityMgrServ_->GetStackManager(); - EXPECT_TRUE(stackManager); - - std::string abilityName = "MusicAbility"; - std::string bundleName = "com.ix.hiMusic"; - Want want = CreateWant(abilityName, bundleName); - bool testResult = false; - sptr testToken; - - auto mockHandler = [&](const sptr &token, - const sptr &preToken, - const AbilityInfo &abilityInfo, - const ApplicationInfo &appInfo) { - testToken = token; - testResult = !!testToken && abilityInfo.bundleName == bundleName && abilityInfo.name == abilityName && - appInfo.bundleName == bundleName; - return AppMgrResultCode::RESULT_OK; - }; - - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1).WillOnce(Invoke(mockHandler)); - - int testRequestCode = 123; - abilityMgrServ_->StartAbility(want, testRequestCode); - - EXPECT_TRUE(testResult); - EXPECT_TRUE(testToken); - - auto testAbilityRecord = stackManager->GetAbilityRecordByToken(testToken); - EXPECT_TRUE(testAbilityRecord); - EXPECT_EQ(testAbilityRecord->GetRequestCode(), testRequestCode); -} - /* * Feature: AaFwk * Function: ability manager service @@ -908,7 +869,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_009, TestSize.Level1) const sptr callback(new AbilityConnectionProxy(stub)); abilityMgrServ_->RemoveAllServiceRecord(); - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1); + EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _, _)).Times(1); abilityMgrServ_->ConnectAbility(want, callback, nullptr); std::shared_ptr record = abilityMgrServ_->connectManager_->GetServiceRecordByElementName(want.GetElement().GetURI()); @@ -972,7 +933,7 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_010, TestSize.Level1) abilityMgrServ_->RemoveAllServiceRecord(); - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(2); + EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _, _)).Times(2); abilityMgrServ_->ConnectAbility(want1, callback1, nullptr); abilityMgrServ_->ConnectAbility(want2, callback1, nullptr); abilityMgrServ_->ConnectAbility(want1, callback2, nullptr); @@ -1014,281 +975,6 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_010, TestSize.Level1) testing::Mock::AllowLeak(scheduler); } -/* - * Feature: AaFwk - * Function: ability manager service - * SubFunction: NA - * FunctionPoints: NA - * EnvConditions: NA - * CaseDescription: start ability (serive ability). - */ -HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_011, TestSize.Level1) -{ - std::string abilityName = "MusicAbility_service"; - std::string bundleName = "com.ix.hiMusic_service"; - Want want = CreateWant(abilityName, bundleName); - bool testResult = false; - sptr testToken; - auto mockHandler = [&](const sptr &token, - const sptr &preToken, - const AbilityInfo &abilityInfo, - const ApplicationInfo &appInfo) { - testToken = token; - testResult = !!testToken && abilityInfo.bundleName == bundleName && abilityInfo.name == abilityName && - appInfo.bundleName == bundleName; - return AppMgrResultCode::RESULT_OK; - }; - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1).WillOnce(Invoke(mockHandler)); - - int testRequestCode = 123; - SetActive(); - abilityMgrServ_->StartAbility(want, testRequestCode); - EXPECT_TRUE(testResult); - EXPECT_TRUE(testToken); - - std::shared_ptr record = abilityMgrServ_->GetServiceRecordByElementName(want.GetElement().GetURI()); - EXPECT_TRUE(record); - EXPECT_FALSE(record->IsCreateByConnect()); - - sptr scheduler = new MockAbilityScheduler(); - EXPECT_TRUE(scheduler); - EXPECT_CALL(*scheduler, AsObject()).Times(2); - EXPECT_CALL(*mockAppMgrClient_, UpdateAbilityState(_, _)).Times(1); - abilityMgrServ_->AttachAbilityThread(scheduler, record->GetToken()); - EXPECT_TRUE(record->isReady_); - - EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(_, _)).Times(1); - abilityMgrServ_->OnAbilityRequestDone( - record->GetToken(), (int32_t)OHOS::AppExecFwk::AbilityState::ABILITY_STATE_FOREGROUND); - EXPECT_EQ(OHOS::AAFwk::AbilityState::INACTIVATING, record->GetAbilityState()); - - int testId = 0; - auto handler = [&](const Want &want, bool restart, int startid) { testId = startid; }; - EXPECT_CALL(*scheduler, ScheduleCommandAbility(_, _, _)).Times(1).WillOnce(Invoke(handler)); - PacMap saveData; - abilityMgrServ_->AbilityTransitionDone(record->GetToken(), AbilityLifeCycleState::ABILITY_STATE_INACTIVE, saveData); - EXPECT_EQ(1, testId); - - abilityMgrServ_->ScheduleCommandAbilityDone(record->GetToken()); - EXPECT_EQ(OHOS::AAFwk::AbilityState::ACTIVE, record->GetAbilityState()); - - EXPECT_CALL(*scheduler, ScheduleCommandAbility(_, _, _)) - .Times(3) - .WillOnce(Invoke(handler)) - .WillOnce(Invoke(handler)) - .WillOnce(Invoke(handler)); - - for (int i = 0; i < 3; ++i) { - abilityMgrServ_->StartAbility(want, testRequestCode); - } - EXPECT_EQ(4, testId); - abilityMgrServ_->RemoveAllServiceRecord(); - testing::Mock::AllowLeak(scheduler); -} -/* - * Feature: AaFwk - * Function: ability manager service - * SubFunction: NA - * FunctionPoints: NA - * EnvConditions: NA - * CaseDescription: start ability (serive ability). - */ -HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_012, TestSize.Level1) -{ - std::string abilityName = "MusicAbility_service"; - std::string bundleName = "com.ix.hiMusic_service"; - Want want = CreateWant(abilityName, bundleName); - bool testResult = false; - sptr testToken; - auto mockHandler = [&](const sptr &token, - const sptr &preToken, - const AbilityInfo &abilityInfo, - const ApplicationInfo &appInfo) { - testToken = token; - testResult = !!testToken && abilityInfo.bundleName == bundleName && abilityInfo.name == abilityName && - appInfo.bundleName == bundleName; - return AppMgrResultCode::RESULT_OK; - }; - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1).WillOnce(Invoke(mockHandler)); - - int testRequestCode = 123; - abilityMgrServ_->StartAbility(want, testRequestCode); - WaitAMS(); - EXPECT_TRUE(testResult); - EXPECT_TRUE(testToken); - - std::shared_ptr record = abilityMgrServ_->GetServiceRecordByElementName(want.GetElement().GetURI()); - EXPECT_TRUE(record); - EXPECT_FALSE(record->IsCreateByConnect()); - - sptr scheduler = new MockAbilityScheduler(); - EXPECT_TRUE(scheduler); - EXPECT_CALL(*scheduler, AsObject()).Times(2); - EXPECT_CALL(*mockAppMgrClient_, UpdateAbilityState(_, _)).Times(1); - abilityMgrServ_->AttachAbilityThread(scheduler, record->GetToken()); - EXPECT_TRUE(record->isReady_); - - EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(_, _)).Times(1); - abilityMgrServ_->OnAbilityRequestDone( - record->GetToken(), (int32_t)OHOS::AppExecFwk::AbilityState::ABILITY_STATE_FOREGROUND); - EXPECT_EQ(OHOS::AAFwk::AbilityState::INACTIVATING, record->GetAbilityState()); - - int testId = 0; - auto handler = [&](const Want &want, bool restart, int startid) { testId = startid; }; - EXPECT_CALL(*scheduler, ScheduleCommandAbility(_, _, _)).Times(1).WillOnce(Invoke(handler)); - PacMap saveData; - abilityMgrServ_->AbilityTransitionDone(record->GetToken(), AbilityLifeCycleState::ABILITY_STATE_INACTIVE, saveData); - EXPECT_EQ(1, testId); - - abilityMgrServ_->ScheduleCommandAbilityDone(record->GetToken()); - EXPECT_EQ(OHOS::AAFwk::AbilityState::ACTIVE, record->GetAbilityState()); - - sptr stub(new MockAbilityConnectCallbackStub()); - const sptr callback(new AbilityConnectionProxy(stub)); - EXPECT_CALL(*scheduler, ScheduleConnectAbility(_)).Times(1); - abilityMgrServ_->ConnectAbility(want, callback, nullptr); - std::shared_ptr connectRecord = record->GetConnectingRecord(); - EXPECT_TRUE(connectRecord); - EXPECT_EQ((size_t)1, abilityMgrServ_->GetConnectRecordListByCallback(callback).size()); - - EXPECT_CALL(*stub, OnAbilityConnectDone(_, _, _)).Times(1); - abilityMgrServ_->ScheduleConnectAbilityDone(record->GetToken(), nullptr); - EXPECT_EQ(ConnectionState::CONNECTED, connectRecord->GetConnectState()); - - abilityMgrServ_->RemoveAllServiceRecord(); - - testing::Mock::AllowLeak(scheduler); - testing::Mock::AllowLeak(stub); - testing::Mock::AllowLeak(callback); -} - -/* - * Feature: AaFwk - * Function: ability manager service - * SubFunction: NA - * FunctionPoints: NA - * EnvConditions: NA - * CaseDescription: start ability (serive ability). - */ -HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_013, TestSize.Level1) -{ - std::string abilityName1 = "MusicAbility_service_1"; - std::string bundleName1 = "com.ix.hiMusic_service_1"; - Want want1 = CreateWant(abilityName1, bundleName1); - std::string abilityName2 = "MusicAbility_service_2"; - std::string bundleName2 = "com.ix.hiMusic_service_2"; - Want want2 = CreateWant(abilityName2, bundleName2); - - abilityMgrServ_->RemoveAllServiceRecord(); - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(2); - int testRequestCode = 123; - abilityMgrServ_->StartAbility(want1, testRequestCode); - abilityMgrServ_->StartAbility(want2, testRequestCode); - - std::shared_ptr record1 = - abilityMgrServ_->GetServiceRecordByElementName(want1.GetElement().GetURI()); - EXPECT_TRUE(record1); - EXPECT_FALSE(record1->IsCreateByConnect()); - - std::shared_ptr record2 = - abilityMgrServ_->GetServiceRecordByElementName(want2.GetElement().GetURI()); - EXPECT_TRUE(record2); - EXPECT_FALSE(record2->IsCreateByConnect()); - - abilityMgrServ_->RemoveAllServiceRecord(); -} - -/* - * Feature: AaFwk - * Function: ability manager service - * SubFunction: NA - * FunctionPoints: NA - * EnvConditions: NA - * CaseDescription: TerminateAbility (serive ability). - */ -HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_014, TestSize.Level1) -{ - std::string abilityName = "MusicAbility_service"; - std::string bundleName = "com.ix.hiMusic_service"; - Want want = CreateWant(abilityName, bundleName); - - abilityMgrServ_->RemoveAllServiceRecord(); - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1); - int testRequestCode = 123; - abilityMgrServ_->StartAbility(want, testRequestCode); - std::shared_ptr record = abilityMgrServ_->GetServiceRecordByElementName(want.GetElement().GetURI()); - EXPECT_TRUE(record); - EXPECT_FALSE(record->IsCreateByConnect()); - record->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); - - sptr scheduler = new MockAbilityScheduler(); - EXPECT_TRUE(scheduler); - EXPECT_CALL(*scheduler, AsObject()).Times(2); - record->SetScheduler(scheduler); - - EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(_, _)).Times(1); - abilityMgrServ_->TerminateAbility(record->GetToken(), -1); - EXPECT_EQ(OHOS::AAFwk::AbilityState::TERMINATING, record->GetAbilityState()); - - EXPECT_CALL(*mockAppMgrClient_, UpdateAbilityState(_, _)).Times(1); - PacMap saveData; - abilityMgrServ_->AbilityTransitionDone(record->GetToken(), AbilityLifeCycleState::ABILITY_STATE_INITIAL, saveData); - - EXPECT_CALL(*mockAppMgrClient_, TerminateAbility(_)).Times(1); - abilityMgrServ_->OnAbilityRequestDone( - record->GetToken(), (int32_t)OHOS::AppExecFwk::AbilityState::ABILITY_STATE_BACKGROUND); - EXPECT_EQ((std::size_t)0, abilityMgrServ_->connectManager_->GetServiceMap().size()); - - abilityMgrServ_->RemoveAllServiceRecord(); - - testing::Mock::AllowLeak(scheduler); -} - -/* - * Feature: AaFwk - * Function: ability manager service - * SubFunction: NA - * FunctionPoints: NA - * EnvConditions: NA - * CaseDescription: TerminateAbility (serive ability). - */ -HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_015, TestSize.Level1) -{ - std::string abilityName = "MusicAbility_service"; - std::string bundleName = "com.ix.hiMusic_service"; - Want want = CreateWant(abilityName, bundleName); - - abilityMgrServ_->RemoveAllServiceRecord(); - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1); - int testRequestCode = 123; - abilityMgrServ_->StartAbility(want, testRequestCode); - std::shared_ptr record = abilityMgrServ_->GetServiceRecordByElementName(want.GetElement().GetURI()); - EXPECT_TRUE(record); - EXPECT_FALSE(record->IsCreateByConnect()); - record->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); - - sptr scheduler = new MockAbilityScheduler(); - EXPECT_TRUE(scheduler); - EXPECT_CALL(*scheduler, AsObject()).Times(2); - record->SetScheduler(scheduler); - - EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(_, _)).Times(1); - abilityMgrServ_->StopServiceAbility(want); - EXPECT_EQ(OHOS::AAFwk::AbilityState::TERMINATING, record->GetAbilityState()); - - EXPECT_CALL(*mockAppMgrClient_, UpdateAbilityState(_, _)).Times(1); - PacMap saveData; - abilityMgrServ_->AbilityTransitionDone(record->GetToken(), AbilityLifeCycleState::ABILITY_STATE_INITIAL, saveData); - - EXPECT_CALL(*mockAppMgrClient_, TerminateAbility(_)).Times(1); - abilityMgrServ_->OnAbilityRequestDone( - record->GetToken(), (int32_t)OHOS::AppExecFwk::AbilityState::ABILITY_STATE_BACKGROUND); - EXPECT_EQ((std::size_t)0, abilityMgrServ_->connectManager_->GetServiceMap().size()); - - abilityMgrServ_->RemoveAllServiceRecord(); - testing::Mock::AllowLeak(scheduler); -} - /* * Feature: AaFwk * Function: ability manager service @@ -1304,9 +990,9 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_016, TestSize.Level1) Want want = CreateWant(abilityName, bundleName); abilityMgrServ_->RemoveAllServiceRecord(); - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1); + EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _, _)).Times(1); int testRequestCode = 123; - abilityMgrServ_->StartAbility(want, testRequestCode); + abilityMgrServ_->StartAbility(want, 0, testRequestCode); std::shared_ptr record = abilityMgrServ_->GetServiceRecordByElementName(want.GetElement().GetURI()); EXPECT_TRUE(record); EXPECT_FALSE(record->IsCreateByConnect()); @@ -1324,12 +1010,11 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_016, TestSize.Level1) std::shared_ptr connectRecord = record->GetConnectingRecord(); EXPECT_TRUE(connectRecord); EXPECT_EQ((size_t)1, abilityMgrServ_->GetConnectRecordListByCallback(callback).size()); - EXPECT_CALL(*stub, OnAbilityConnectDone(_, _, _)).Times(1); abilityMgrServ_->ScheduleConnectAbilityDone(record->GetToken(), nullptr); EXPECT_EQ(ConnectionState::CONNECTED, connectRecord->GetConnectState()); int result = abilityMgrServ_->TerminateAbility(record->GetToken(), -1); - EXPECT_EQ(TERMINATE_SERVICE_IS_CONNECTED, result); + EXPECT_EQ(0, result); abilityMgrServ_->RemoveAllServiceRecord(); @@ -1353,9 +1038,9 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_017, TestSize.Level1) Want want = CreateWant(abilityName, bundleName); abilityMgrServ_->RemoveAllServiceRecord(); - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1); + EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _, _)).Times(1); int testRequestCode = 123; - abilityMgrServ_->StartAbility(want, testRequestCode); + abilityMgrServ_->StartAbility(want, 0, testRequestCode); std::shared_ptr record = abilityMgrServ_->GetServiceRecordByElementName(want.GetElement().GetURI()); EXPECT_TRUE(record); EXPECT_FALSE(record->IsCreateByConnect()); @@ -1373,12 +1058,11 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_017, TestSize.Level1) std::shared_ptr connectRecord = record->GetConnectingRecord(); EXPECT_TRUE(connectRecord); EXPECT_EQ((size_t)1, abilityMgrServ_->GetConnectRecordListByCallback(callback).size()); - EXPECT_CALL(*stub, OnAbilityConnectDone(_, _, _)).Times(1); abilityMgrServ_->ScheduleConnectAbilityDone(record->GetToken(), nullptr); EXPECT_EQ(ConnectionState::CONNECTED, connectRecord->GetConnectState()); int result = abilityMgrServ_->StopServiceAbility(want); - EXPECT_EQ(TERMINATE_SERVICE_IS_CONNECTED, result); + EXPECT_EQ(0, result); abilityMgrServ_->RemoveAllServiceRecord(); @@ -1402,10 +1086,10 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_018, TestSize.Level1) Want want = CreateWant(abilityName, bundleName); abilityMgrServ_->RemoveAllServiceRecord(); - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1); + EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _, _)).Times(1); int testRequestCode = 123; SetActive(); - abilityMgrServ_->StartAbility(want, testRequestCode); + abilityMgrServ_->StartAbility(want, 0, testRequestCode); std::shared_ptr record = abilityMgrServ_->GetServiceRecordByElementName(want.GetElement().GetURI()); EXPECT_TRUE(record); EXPECT_FALSE(record->IsCreateByConnect()); @@ -1458,269 +1142,6 @@ HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_018, TestSize.Level1) testing::Mock::AllowLeak(callback); } -/* - * Feature: AaFwk - * Function: ability manager service - * SubFunction: NA - * FunctionPoints: NA - * EnvConditions: NA - * CaseDescription: disconnectAbility and terminate (serive ability). - */ -HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_019, TestSize.Level1) -{ - std::string abilityName = "MusicAbilityService"; - std::string bundleName = "com.ix.hiservice"; - Want want = CreateWant(abilityName, bundleName); - EXPECT_TRUE(abilityMgrServ_); - abilityMgrServ_->RemoveAllServiceRecord(); - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1); - int testRequestCode = 123; - abilityMgrServ_->StartAbility(want, testRequestCode); - std::shared_ptr record = abilityMgrServ_->GetServiceRecordByElementName(want.GetElement().GetURI()); - EXPECT_TRUE(record); - EXPECT_FALSE(record->IsCreateByConnect()); - record->AddStartId(); - record->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); - - sptr scheduler = new MockAbilityScheduler(); - EXPECT_TRUE(scheduler); - EXPECT_CALL(*scheduler, AsObject()).Times(2); - record->SetScheduler(scheduler); - sptr stub(new MockAbilityConnectCallbackStub()); - const sptr callback(new AbilityConnectionProxy(stub)); - EXPECT_CALL(*scheduler, ScheduleConnectAbility(_)).Times(1); - abilityMgrServ_->ConnectAbility(want, callback, nullptr); - std::shared_ptr connectRecord = record->GetConnectingRecord(); - EXPECT_TRUE(connectRecord); - EXPECT_EQ((size_t)1, abilityMgrServ_->GetConnectRecordListByCallback(callback).size()); - EXPECT_CALL(*stub, OnAbilityConnectDone(_, _, _)).Times(1); - abilityMgrServ_->ScheduleConnectAbilityDone(record->GetToken(), stub); - EXPECT_EQ(ConnectionState::CONNECTED, connectRecord->GetConnectState()); - - EXPECT_CALL(*scheduler, ScheduleDisconnectAbility(_)).Times(1); - abilityMgrServ_->DisconnectAbility(callback); - EXPECT_EQ(OHOS::AAFwk::ConnectionState::DISCONNECTING, connectRecord->GetConnectState()); - - EXPECT_CALL(*stub, OnAbilityDisconnectDone(_, _)).Times(1); - abilityMgrServ_->ScheduleDisconnectAbilityDone(record->GetToken()); - EXPECT_EQ((std::size_t)0, record->GetConnectRecordList().size()); - EXPECT_EQ((std::size_t)0, abilityMgrServ_->connectManager_->GetConnectMap().size()); - EXPECT_EQ(OHOS::AAFwk::ConnectionState::DISCONNECTED, connectRecord->GetConnectState()); - EXPECT_EQ((std::size_t)1, abilityMgrServ_->connectManager_->GetServiceMap().size()); - - EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(_, _)).Times(1); - abilityMgrServ_->TerminateAbility(record->GetToken(), -1); - EXPECT_EQ(OHOS::AAFwk::AbilityState::TERMINATING, record->GetAbilityState()); - - EXPECT_CALL(*mockAppMgrClient_, UpdateAbilityState(_, _)).Times(1); - PacMap saveData; - abilityMgrServ_->AbilityTransitionDone(record->GetToken(), AbilityLifeCycleState::ABILITY_STATE_INITIAL, saveData); - EXPECT_CALL(*mockAppMgrClient_, TerminateAbility(_)).Times(1); - abilityMgrServ_->OnAbilityRequestDone( - record->GetToken(), (int32_t)OHOS::AppExecFwk::AbilityState::ABILITY_STATE_BACKGROUND); - EXPECT_EQ((std::size_t)0, abilityMgrServ_->connectManager_->GetServiceMap().size()); - - testing::Mock::AllowLeak(scheduler); - testing::Mock::AllowLeak(stub); - testing::Mock::AllowLeak(callback); -} - -/* - * Feature: AaFwk - * Function: ability manager service - * SubFunction: OnAbilityDied - * FunctionPoints: NA - * EnvConditions: NA - * CaseDescription: Test service abilities death notification. - */ -HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_020, TestSize.Level3) -{ - std::string abilityName = "MusicAbility_service"; - std::string bundleName = "com.ix.hiMusic_service"; - Want want = CreateWant(abilityName, bundleName); - - abilityMgrServ_->RemoveAllServiceRecord(); - - sptr stub(new MockAbilityConnectCallbackStub()); - const sptr callback(new AbilityConnectionProxy(stub)); - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1); - abilityMgrServ_->ConnectAbility(want, callback, nullptr); - EXPECT_EQ((std::size_t)1, abilityMgrServ_->connectManager_->connectMap_.size()); - EXPECT_EQ((std::size_t)1, abilityMgrServ_->connectManager_->serviceMap_.size()); - std::shared_ptr record = - abilityMgrServ_->connectManager_->GetServiceRecordByElementName(want.GetElement().GetURI()); - EXPECT_TRUE(record); - EXPECT_TRUE(record->IsCreateByConnect()); - std::shared_ptr connectRecord = record->GetConnectingRecord(); - EXPECT_TRUE(connectRecord); - connectRecord->SetConnectState(ConnectionState::CONNECTED); - record->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); - - EXPECT_CALL(*stub, OnAbilityDisconnectDone(_, _)).Times(1); - abilityMgrServ_->OnAbilityDied(record); - usleep(100 * 1000); - - EXPECT_EQ((std::size_t)0, abilityMgrServ_->connectManager_->GetServiceMap().size()); - EXPECT_EQ((std::size_t)0, abilityMgrServ_->connectManager_->connectMap_.size()); - - abilityMgrServ_->RemoveAllServiceRecord(); - testing::Mock::AllowLeak(stub); - testing::Mock::AllowLeak(callback); -} - -/* - * Feature: AbilityManagerService - * Function: HandleLoadTimeOut - * SubFunction: NA - * FunctionPoints: AbilityManagerService HandleLoadTimeOut - * EnvConditions: NA - * CaseDescription: Verify function HandleLoadTimeOut - */ -HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_021, TestSize.Level1) -{ - EXPECT_TRUE(abilityMgrServ_); - EXPECT_TRUE(mockAppMgrClient_); - ClearStack(); - - std::string abilityName = "MusicSAbility"; - std::string bundleName = "com.ix.hiMusic"; - std::string abilityName2 = "RadioAbility"; - std::string bundleName2 = "com.ix.hiRadio"; - Want want = CreateWant(abilityName, bundleName); - Want want2 = CreateWant(abilityName2, bundleName2); - sptr scheduler = new MockAbilityScheduler(); - EXPECT_TRUE(scheduler); - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(2); - EXPECT_CALL(*mockAppMgrClient_, AbilityAttachTimeOut(_)).Times(1); - EXPECT_CALL(*mockAppMgrClient_, UpdateAbilityState(_, _)).Times(2); - EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(_, _)).Times(1); - EXPECT_CALL(*scheduler, AsObject()).Times(2); - abilityMgrServ_->StartAbility(want); - auto testAbilityRecord = GetTopAbility(); - EXPECT_TRUE(testAbilityRecord); - abilityMgrServ_->AttachAbilityThread(scheduler, testAbilityRecord->GetToken()); - SetActive(); - abilityMgrServ_->StartAbility(want2); - auto testAbilityRecord2 = GetTopAbility(); - EXPECT_TRUE(testAbilityRecord2); - auto stackMgr = abilityMgrServ_->GetStackManager(); - EXPECT_TRUE(stackMgr); - stackMgr->CompleteInactive(testAbilityRecord); - testAbilityRecord->SetAbilityState(OHOS::AAFwk::AbilityState::BACKGROUND); - abilityMgrServ_->HandleLoadTimeOut(testAbilityRecord2->GetEventId()); - testAbilityRecord = GetTopAbility(); - EXPECT_TRUE(testAbilityRecord); - EXPECT_TRUE(testAbilityRecord->GetAbilityInfo().bundleName == bundleName); - testing::Mock::AllowLeak(scheduler); -} - -/* - * Feature: AbilityManagerService - * Function: HandleLoadTimeOut - * SubFunction: NA - * FunctionPoints: AbilityManagerService HandleLoadTimeOut - * EnvConditions: NA - * CaseDescription: Verify function HandleLoadTimeOut - */ -HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_022, TestSize.Level1) -{ - EXPECT_TRUE(abilityMgrServ_); - EXPECT_TRUE(mockAppMgrClient_); - ClearStack(); - - std::string abilityName = "TVAbility"; - std::string bundleName = COM_IX_TV; - std::string abilityName2 = "FilmAbility"; - std::string bundleName2 = COM_IX_Film; - Want want = CreateWant(abilityName, bundleName); - Want want2 = CreateWant(abilityName2, bundleName2); - sptr scheduler = new MockAbilityScheduler(); - EXPECT_TRUE(scheduler); - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(2); - EXPECT_CALL(*mockAppMgrClient_, AbilityAttachTimeOut(_)).Times(1); - EXPECT_CALL(*mockAppMgrClient_, UpdateAbilityState(_, _)).Times(1); - EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(_, _)).Times(2); - EXPECT_CALL(*scheduler, AsObject()).Times(2); - abilityMgrServ_->StartAbility(want); - auto testAbilityRecord = GetTopAbility(); - EXPECT_TRUE(testAbilityRecord); - abilityMgrServ_->AttachAbilityThread(scheduler, testAbilityRecord->GetToken()); - SetActive(); - abilityMgrServ_->StartAbility(want2); - auto testAbilityRecord2 = GetTopAbility(); - EXPECT_TRUE(testAbilityRecord2); - auto stackMgr = abilityMgrServ_->GetStackManager(); - EXPECT_TRUE(stackMgr); - stackMgr->CompleteInactive(testAbilityRecord); - abilityMgrServ_->HandleLoadTimeOut(testAbilityRecord2->GetEventId()); - testAbilityRecord = GetTopAbility(); - EXPECT_TRUE(testAbilityRecord); - EXPECT_TRUE(testAbilityRecord->GetAbilityInfo().bundleName == bundleName); - testing::Mock::AllowLeak(scheduler); -} - -/* - * Feature: AbilityManagerService - * Function: IsFirstInMission - * SubFunction: NA - * FunctionPoints: AbilityManagerService IsFirstInMission - * EnvConditions: NA - * CaseDescription: Verify function IsFirstInMission - * Checks whether this ability is the first ability in a mission. - */ -HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_023, TestSize.Level1) -{ - EXPECT_TRUE(abilityMgrServ_); - EXPECT_TRUE(mockAppMgrClient_); - ClearStack(); - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1); - Want want = CreateWant("RadioTopAbility", COM_IX_HIRADIO); - abilityMgrServ_->StartAbility(want); - auto testAbilityRecord = GetTopAbility(); - EXPECT_TRUE(testAbilityRecord); - SetActive(); - auto resultTvFunction = abilityMgrServ_->IsFirstInMission(testAbilityRecord->GetToken()); - EXPECT_EQ(resultTvFunction, true); -} - -/* - * Feature: AbilityManagerService - * Function: MoveMissionToEnd - * SubFunction: NA - * FunctionPoints: AbilityManagerService MoveMissionToEnd - * EnvConditions: NA - * CaseDescription: Verify function MoveMissionToEnd - * Multiple MissionRecord in Stack,When this ability is not the first ability in a mission, - * and MoveMissionToEnd second parameter is true. - */ -HWTEST_F(AbilityMgrModuleTest, ability_mgr_service_test_024, TestSize.Level1) -{ - EXPECT_TRUE(abilityMgrServ_); - EXPECT_TRUE(mockAppMgrClient_); - ClearStack(); - auto stackManager = abilityMgrServ_->GetStackManager(); - EXPECT_TRUE(stackManager); - sptr scheduler = new MockAbilityScheduler(); - EXPECT_CALL(*mockAppMgrClient_, LoadAbility(_, _, _, _)).Times(1); - EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(_, _)).Times(1); - EXPECT_CALL(*scheduler, AsObject()).Times(2); - Want want = CreateWant("PhoneAbility1", COM_IX_PHONE); - abilityMgrServ_->StartAbility(want); - auto ability = stackManager->GetCurrentTopAbility(); - EXPECT_TRUE(ability); - SetActive(); - Want want2 = CreateWant("PhoneAbility2", COM_IX_PHONE); - abilityMgrServ_->StartAbility(want2); - EXPECT_TRUE(scheduler); - auto abilityTv = stackManager->GetCurrentTopAbility(); - EXPECT_TRUE(abilityTv); - abilityTv->SetScheduler(scheduler); - SetActive(); - auto resultFunction = abilityMgrServ_->MoveMissionToEnd(abilityTv->GetToken(), true); - EXPECT_EQ(resultFunction, ERR_OK); - testing::Mock::AllowLeak(scheduler); -} - /* * Feature: AbilityManagerService * Function: CompelVerifyPermission diff --git a/services/test/moduletest/ability_record_test/BUILD.gn b/services/test/moduletest/ability_record_test/BUILD.gn index d4769d67f211a157da47d59d2c055fa1e332b85e..7c35ff46dcba1b63e4772e2ddfac9701d2ce500c 100644 --- a/services/test/moduletest/ability_record_test/BUILD.gn +++ b/services/test/moduletest/ability_record_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -90,6 +90,7 @@ ohos_moduletest("AbilityRecordModuleTest") { } deps = [ "${innerkits_path}/base:base", + "${innerkits_path}/uri_permission:uri_permission_mgr", "${innerkits_path}/want:want", "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//base/global/i18n_standard/frameworks/intl:intl_util", @@ -113,6 +114,7 @@ ohos_moduletest("AbilityRecordModuleTest") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "bytrace_standard:bytrace_core", "ces_standard:cesfwk_core", "ces_standard:cesfwk_innerkits", diff --git a/services/test/moduletest/ability_record_test/ability_record_module_test.cpp b/services/test/moduletest/ability_record_test/ability_record_module_test.cpp index e2d993272ff357d24c5b62e2bbf434e87a577bab..21ecfb1a12d08dee7adae4250a19c59a034348ab 100644 --- a/services/test/moduletest/ability_record_test/ability_record_module_test.cpp +++ b/services/test/moduletest/ability_record_test/ability_record_module_test.cpp @@ -219,53 +219,6 @@ HWTEST_F(AbilityRecordModuleTest, Init_002, TestSize.Level2) } } -/* - * Feature: AbilityRecord - * Function: LoadAbility - * SubFunction: N/A - * FunctionPoints: Load a test ability - * CaseDescription: Load a test ability and check state in 'AppMgrClient' mocker. - */ -HWTEST_F(AbilityRecordModuleTest, LoadAbility_001, TestSize.Level3) -{ - auto &abilityRequest = MakeDefaultAbilityRequest(); - - for (int i = 0; i < COUNT; ++i) { - auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - EXPECT_TRUE(abilityRecord); - - std::unique_ptr mockAppMgrClient(new MockAppMgrClient); - EXPECT_TRUE(mockAppMgrClient); - - auto mockHandler = [&](const sptr &token, - const sptr &preToken, - const AbilityInfo &abilityInfo, - const ApplicationInfo &appInfo) { - if (abilityInfo != abilityRequest.abilityInfo) { - return static_cast(ERR_INVALID_VALUE); - } - if (appInfo != abilityRequest.appInfo) { - return static_cast(ERR_INVALID_VALUE); - } - return AppExecFwk::RESULT_OK; - }; - - EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)).Times(1).WillOnce(Invoke(mockHandler)); - - auto appScheduler = DelayedSingleton::GetInstance(); - auto backupAppMgrClient = std::move(appScheduler->appMgrClient_); - appScheduler->appMgrClient_ = std::move(mockAppMgrClient); - - auto result = abilityRecord->LoadAbility(); - EXPECT_EQ(result, ERR_OK); - - EXPECT_EQ(abilityRecord->GetAbilityInfo(), abilityRequest.abilityInfo); - EXPECT_EQ(abilityRecord->GetApplicationInfo(), abilityRequest.appInfo); - - appScheduler->appMgrClient_ = std::move(backupAppMgrClient); - } -} - /* * Feature: AbilityRecord * Function: TerminateAbility diff --git a/services/test/moduletest/ability_stack_test/BUILD.gn b/services/test/moduletest/ability_stack_test/BUILD.gn index 3a0d5cb3cfaeb7b6e65f05fbafac6ae7c31a5071..59960e6fc515e296dcd91497d71defbdefde6452 100644 --- a/services/test/moduletest/ability_stack_test/BUILD.gn +++ b/services/test/moduletest/ability_stack_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -89,6 +89,7 @@ ohos_moduletest("ability_stack_module_test") { deps = [ "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", "${innerkits_path}/base:base", + "${innerkits_path}/uri_permission:uri_permission_mgr", "${innerkits_path}/want:want", "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//base/global/i18n_standard/frameworks/intl:intl_util", @@ -111,6 +112,7 @@ ohos_moduletest("ability_stack_module_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "bytrace_standard:bytrace_core", "ces_standard:cesfwk_core", "ces_standard:cesfwk_innerkits", diff --git a/services/test/moduletest/ability_stack_test/ability_stack_module_test.cpp b/services/test/moduletest/ability_stack_test/ability_stack_module_test.cpp index e1edffa368ead64b17b7de906b2251f11c0e175f..666c937d822970f78e8eac4b0541370a440b014b 100644 --- a/services/test/moduletest/ability_stack_test/ability_stack_module_test.cpp +++ b/services/test/moduletest/ability_stack_test/ability_stack_module_test.cpp @@ -74,35 +74,32 @@ void AbilityStackModuleTest::OnStartabilityMs(std::shared_ptrstate_ == ServiceRunningState::STATE_RUNNING) { return; } - abilityMs->state_ = ServiceRunningState::STATE_RUNNING; - abilityMs->eventLoop_ = AppExecFwk::EventRunner::Create(AbilityConfig::NAME_ABILITY_MGR_SERVICE); EXPECT_TRUE(abilityMs->eventLoop_); - abilityMs->handler_ = std::make_shared(abilityMs->eventLoop_, abilityMs); + abilityMs->connectManager_ = std::make_shared(); + abilityMs->connectManagers_.emplace(0, abilityMs->connectManager_); EXPECT_TRUE(abilityMs->handler_); EXPECT_TRUE(abilityMs->connectManager_); - abilityMs->connectManager_->SetEventHandler(abilityMs->handler_); - abilityMs->dataAbilityManager_ = std::make_shared(); + abilityMs->dataAbilityManagers_.emplace(0, abilityMs->dataAbilityManager_); EXPECT_TRUE(abilityMs->dataAbilityManager_); abilityMs->amsConfigResolver_ = std::make_shared(); EXPECT_TRUE(abilityMs->amsConfigResolver_); abilityMs->amsConfigResolver_->Parse(); - + abilityMs->currentMissionListManager_ = std::make_shared(0); + abilityMs->currentMissionListManager_->Init(); abilityMs->pendingWantManager_ = std::make_shared(); EXPECT_TRUE(abilityMs->pendingWantManager_); - int userId = abilityMs->GetUserId(); abilityMs->SetStackManager(userId, true); + abilityMs->stackManagers_.emplace(0, abilityMs->GetStackManager()); abilityMs->systemAppManager_ = std::make_shared(userId); EXPECT_TRUE(abilityMs->systemAppManager_); - abilityMs->eventLoop_->Run(); - return; } GTEST_LOG_(INFO) << "OnStart fail"; @@ -131,30 +128,29 @@ void AbilityStackModuleTest::TearDownTestCase(void) void AbilityStackModuleTest::SetUp(void) { - GTEST_LOG_(INFO) << "SetUp"; - + GTEST_LOG_(INFO) << "SetUp start"; auto ams = DelayedSingleton::GetInstance(); auto bms = ams->GetBundleManager(); OnStartabilityMs(ams); stackManager_ = ams->GetStackManager(); EXPECT_TRUE(stackManager_); - stackManager_->Init(); EXPECT_NE(bms, nullptr); if (mockScheduler_ == nullptr) { mockScheduler_ = new MockAbilityScheduler(); } + GTEST_LOG_(INFO) << "SetUp end"; } void AbilityStackModuleTest::TearDown(void) { - GTEST_LOG_(INFO) << "TearDown"; + GTEST_LOG_(INFO) << "TearDown start"; auto ams = DelayedSingleton::GetInstance(); - OHOS::DelayedSingleton::DestroyInstance(); - - if (mockScheduler_ != nullptr) { - mockScheduler_.clear(); - } + ams->stackManagers_.clear(); + ams->currentStackManager_ = nullptr; + stackManager_ = nullptr; + ams->OnStop(); + GTEST_LOG_(INFO) << "TearDown end"; } AbilityRequest AbilityStackModuleTest::GenerateAbilityRequest(const std::string &deviceName, @@ -274,9 +270,7 @@ ApplicationInfo AbilityStackModuleTest::CreateAppInfo(const std::string &appName */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_getMissionSnapshot_001, TestSize.Level1) { - std::this_thread::sleep_for(std::chrono::milliseconds(2000)); - stackManager_->Init(); - + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); WindowManagerServiceMock *mockWindowManager = new WindowManagerServiceMock(); // set mock stackManager_->screenshotHandler_->windowMS_ = mockWindowManager; @@ -303,7 +297,7 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_getMissionSnapshot_001, Test imageInfo.format = 10; promise->Resolve(imageInfo); }).detach(); - auto ret = stackManager_->GetMissionSnapshot(missionId,missionPixelMap); + auto ret = stackManager_->GetMissionSnapshot(missionId, missionPixelMap); EXPECT_TRUE(missionPixelMap.topAbility.abilityName_ == "LauncherAbility"); EXPECT_TRUE(missionPixelMap.topAbility.bundleName_ == "com.ix.hiworld"); @@ -338,7 +332,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_001, TestSize.Level1) abilityRequest.appInfo.isLauncherApp = true; // launcher ability abilityRequest.abilityInfo.applicationInfo = abilityRequest.appInfo; - stackManager_->Init(); std::shared_ptr curMissionStack = stackManager_->GetCurrentMissionStack(); EXPECT_TRUE(curMissionStack); stackManager_->StartAbility(abilityRequest); @@ -2159,12 +2152,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_043, TestSize.Level1) EXPECT_CALL(*schedulerluncher, AsObject()).WillRepeatedly(Return(nullptr)); topAbilityRecordlauncher->SetScheduler(schedulerluncher); - auto getFocusChangeFlag = [](bool flag) { EXPECT_TRUE(flag); }; - - EXPECT_CALL(*schedulerluncher, NotifyTopActiveAbilityChanged(testing::_)) - .Times(testing::AtLeast(1)) - .WillOnce(testing::Invoke(getFocusChangeFlag)); - EXPECT_EQ(topAbilityRecord->GetMissionStackId(), FLOATING_MISSION_STACK_ID); EXPECT_FALSE(topAbilityRecord->IsToEnd()); @@ -3098,8 +3085,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_059, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_060, TestSize.Level1) { - stackManager_->Init(); - auto musicAbilityRequest = GenerateAbilityRequest("device", "MusicTopAbility", "music", "com.ix.hiMusic"); auto ref = stackManager_->StartAbility(musicAbilityRequest); EXPECT_EQ(ERR_OK, ref); @@ -3146,8 +3131,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_060, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_061, TestSize.Level1) { - stackManager_->Init(); - auto musicAbilityRequest = GenerateAbilityRequest("device", "MusicTopAbility", "music", "com.ix.hiMusic"); auto ref = stackManager_->StartAbility(musicAbilityRequest); EXPECT_EQ(ERR_OK, ref); @@ -3192,8 +3175,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_061, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_062, TestSize.Level1) { - stackManager_->Init(); - // start launcher auto worldAbilityRequest = GenerateAbilityRequest("device", "WorldAbility", "world", "com.ix.hiworld"); auto ref = stackManager_->StartAbility(worldAbilityRequest); @@ -3238,8 +3219,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_062, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_063, TestSize.Level1) { - stackManager_->Init(); - // start launcher auto worldAbilityRequest = GenerateAbilityRequest("device", "WorldAbility", "world", "com.ix.hiworld"); auto ref = stackManager_->StartAbility(worldAbilityRequest); @@ -3291,7 +3270,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_063, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_064, TestSize.Level1) { - stackManager_->Init(); // start launcher auto worldAbilityRequest = GenerateAbilityRequest("device", "WorldAbility", "world", "com.ix.hiworld"); auto ref = stackManager_->StartAbility(worldAbilityRequest); @@ -3346,7 +3324,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_064, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_065, TestSize.Level1) { - stackManager_->Init(); // start launcher auto worldAbilityRequest = GenerateAbilityRequest("device", "WorldAbility", "world", "com.ix.hiworld"); auto ref = stackManager_->StartAbility(worldAbilityRequest); @@ -3399,7 +3376,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_065, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_067, TestSize.Level1) { - stackManager_->Init(); // start launcher auto worldAbilityRequest = GenerateAbilityRequest("device", "WorldAbility", "world", "com.ix.hiworld"); auto ref = stackManager_->StartAbility(worldAbilityRequest); @@ -3459,7 +3435,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_067, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_068, TestSize.Level1) { - stackManager_->Init(); stackManager_->isMultiWinMoving_ = false; // start launcher auto worldAbilityRequest = GenerateAbilityRequest("device", "WorldAbility", "world", "com.ix.hiworld"); @@ -3512,7 +3487,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_068, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_069, TestSize.Level1) { - stackManager_->Init(); stackManager_->isMultiWinMoving_ = false; // start launcher auto worldAbilityRequest = GenerateAbilityRequest("device", "WorldAbility", "world", "com.ix.hiworld"); @@ -3565,7 +3539,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_069, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_070, TestSize.Level1) { - stackManager_->Init(); stackManager_->isMultiWinMoving_ = false; // start launcher auto worldAbilityRequest = GenerateAbilityRequest("device", "WorldAbility", "world", "com.ix.hiworld"); @@ -3730,7 +3703,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_072, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_073, TestSize.Level1) { - stackManager_->Init(); // start launcher auto worldAbilityRequest = GenerateAbilityRequest("device", "WorldAbility", "world", "com.ix.hiworld"); auto ref = stackManager_->StartAbility(worldAbilityRequest); @@ -3790,7 +3762,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_073, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_074, TestSize.Level1) { - stackManager_->Init(); // start launcher auto worldAbilityRequest = GenerateAbilityRequest("device", "WorldAbility", "world", "com.ix.hiworld"); auto ref = stackManager_->StartAbility(worldAbilityRequest); @@ -3836,8 +3807,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_074, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_075, TestSize.Level1) { - stackManager_->Init(); - auto musicTopAbilityRequest = GenerateAbilityRequest("device", "MusicTopAbility", "musicTop", "com.ix.hiTopMusic"); auto ref = stackManager_->StartAbility(musicTopAbilityRequest); EXPECT_EQ(ERR_OK, ref); @@ -3881,8 +3850,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_075, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_076, TestSize.Level1) { - stackManager_->Init(); - // start launcher auto worldAbilityRequest = GenerateAbilityRequest("device", "WorldAbility", "world", "com.ix.hiworld"); auto ref = stackManager_->StartAbility(worldAbilityRequest); @@ -3940,7 +3907,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_076, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_077, TestSize.Level1) { - stackManager_->Init(); stackManager_->SetShowOnLockScreen("com.ix.hiMusic", true); stackManager_->SetShowOnLockScreen("com.ix.hiRadio", false); auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); @@ -3977,7 +3943,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_077, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_078, TestSize.Level1) { - stackManager_->Init(); stackManager_->SetShowOnLockScreen("com.ix.hiMusic", true); stackManager_->SetShowOnLockScreen("com.ix.hiRadio", true); auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); @@ -4014,7 +3979,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_078, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_079, TestSize.Level1) { - stackManager_->Init(); stackManager_->SetShowOnLockScreen("com.ix.hiMusic", true); stackManager_->SetShowOnLockScreen("com.ix.hiRadio", false); auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); @@ -4051,7 +4015,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_079, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_080, TestSize.Level1) { - stackManager_->Init(); stackManager_->SetShowOnLockScreen("com.ix.hiMusic", true); stackManager_->SetShowOnLockScreen("com.ix.hiRadio", true); auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioAbility", "radio", "com.ix.hiRadio"); @@ -4094,7 +4057,6 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_080, TestSize.Level1) */ HWTEST_F(AbilityStackModuleTest, ability_stack_test_081, TestSize.Level1) { - stackManager_->Init(); stackManager_->SetShowOnLockScreen("com.ix.hiMusic", true); stackManager_->SetShowOnLockScreen("com.ix.hiRadio", true); auto radioAbilityRequest = GenerateAbilityRequest("device", "RadioTopAbility", "radio", "com.ix.hiRadio"); diff --git a/services/test/moduletest/common/ams/BUILD.gn b/services/test/moduletest/common/ams/BUILD.gn index 6f2847bf6a709a8bb77e1a1daaf153590f520805..571d3de69b98bbb4616ef3ce4050b1a4f109507b 100755 --- a/services/test/moduletest/common/ams/BUILD.gn +++ b/services/test/moduletest/common/ams/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -77,6 +77,7 @@ ohos_source_set("appmgr_mst_source") { "${aafwk_path}/interfaces/innerkits/app_manager:app_manager", "${appexecfwk_path}/common:libappexecfwk_common", "${appexecfwk_path}/libs/libeventhandler:libeventhandler_target", + "${innerkits_path}/uri_permission:uri_permission_mgr", "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", diff --git a/services/test/moduletest/common/ams/ability_running_record_test/ams_ability_running_record_module_test.cpp b/services/test/moduletest/common/ams/ability_running_record_test/ams_ability_running_record_module_test.cpp index 5c00685518f8f47960fc56218bc4861f48f39a00..45d723fed9dae76dd86d37c750189f84cad4240f 100644 --- a/services/test/moduletest/common/ams/ability_running_record_test/ams_ability_running_record_module_test.cpp +++ b/services/test/moduletest/common/ams/ability_running_record_test/ams_ability_running_record_module_test.cpp @@ -94,7 +94,8 @@ public: scheduled_ |= LAUNCH_APPLICATION_SCHEDULED; appLaunchTime++; } - void ScheduleLaunchAbility(const AbilityInfo &, const sptr &) override + void ScheduleLaunchAbility(const AbilityInfo &, const sptr &, + const std::shared_ptr &) override { scheduled_ |= LAUNCH_ABILITY_SCHEDULED; abilityLaunchTime++; @@ -213,14 +214,14 @@ HWTEST_F(AmsAbilityRunningRecordModuleTest, AddAbilityRunningRecord_001, TestSiz HapModuleInfo hapModuleInfo; hapModuleInfo.moduleName = "Module"; sptr token = new MockAbilityToken(); - appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); - auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo); + auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo, nullptr); EXPECT_TRUE(caseAbilityRunningRecord == nullptr); caseAbilityRunningRecord = moduleRecord->GetAbilityRunningRecord(ABILITY_RECORD_NAME); EXPECT_EQ(caseAbilityRunningRecord, appRunningRecord->GetAbilityRunningRecordByToken(token)); - auto abilityRunningRecordWithSameName = moduleRecord->AddAbility(token, caseAbilityInfo); + auto abilityRunningRecordWithSameName = moduleRecord->AddAbility(token, caseAbilityInfo, nullptr); EXPECT_TRUE(abilityRunningRecordWithSameName == nullptr); appRunningRecord->ClearAbility(caseAbilityRunningRecord); EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(token) == nullptr); @@ -249,10 +250,10 @@ HWTEST_F(AmsAbilityRunningRecordModuleTest, AddAbilityRunningRecord_002, TestSiz sptr token = new MockAbilityToken(); HapModuleInfo hapModuleInfo; hapModuleInfo.moduleName = "Module"; - appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); - auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo); + auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo, nullptr); EXPECT_TRUE(caseAbilityRunningRecord == nullptr); caseAbilityRunningRecord = moduleRecord->GetAbilityRunningRecord(ABILITY_RECORD_NAME + "_" + std::to_string(i)); EXPECT_EQ(caseAbilityRunningRecord, appRunningRecord->GetAbilityRunningRecordByToken(token)); @@ -283,10 +284,10 @@ HWTEST_F(AmsAbilityRunningRecordModuleTest, UpdateAbilityRunningRecord_001, Test sptr token = new MockAbilityToken(); HapModuleInfo hapModuleInfo; hapModuleInfo.moduleName = "Module"; - appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); - auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo); + auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo, nullptr); EXPECT_TRUE(caseAbilityRunningRecord == nullptr); caseAbilityRunningRecord = moduleRecord->GetAbilityRunningRecord(ABILITY_RECORD_NAME + "_" + std::to_string(i)); EXPECT_EQ(caseAbilityRunningRecord, appRunningRecord->GetAbilityRunningRecordByToken(token)); @@ -322,10 +323,10 @@ HWTEST_F(AmsAbilityRunningRecordModuleTest, UpdateAbilityRunningRecord_002, Test sptr token = new MockAbilityToken(); HapModuleInfo hapModuleInfo; hapModuleInfo.moduleName = "Module"; - appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); - auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo); + auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo, nullptr); EXPECT_TRUE(caseAbilityRunningRecord == nullptr); caseAbilityRunningRecord = moduleRecord->GetAbilityRunningRecord(ABILITY_RECORD_NAME + "_" + std::to_string(i)); EXPECT_EQ(caseAbilityRunningRecord, appRunningRecord->GetAbilityRunningRecordByToken(token)); @@ -357,10 +358,10 @@ HWTEST_F(AmsAbilityRunningRecordModuleTest, UpdateAbilityRunningRecord_003, Test sptr token = new MockAbilityToken(); HapModuleInfo hapModuleInfo; hapModuleInfo.moduleName = "Module"; - appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); - auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo); + auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo, nullptr); EXPECT_TRUE(caseAbilityRunningRecord == nullptr); caseAbilityRunningRecord = moduleRecord->GetAbilityRunningRecord(ABILITY_RECORD_NAME + "_" + std::to_string(i)); EXPECT_EQ(caseAbilityRunningRecord, appRunningRecord->GetAbilityRunningRecordByToken(token)); @@ -396,10 +397,10 @@ HWTEST_F(AmsAbilityRunningRecordModuleTest, ClearAbilityRunningRecord_001, TestS sptr token = new MockAbilityToken(); HapModuleInfo hapModuleInfo; hapModuleInfo.moduleName = "Module"; - appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); - auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo); + auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo, nullptr); EXPECT_TRUE(caseAbilityRunningRecord == nullptr); caseAbilityRunningRecord = moduleRecord->GetAbilityRunningRecord(ABILITY_RECORD_NAME + "_" + std::to_string(i)); EXPECT_EQ(caseAbilityRunningRecord, appRunningRecord->GetAbilityRunningRecordByToken(token)); @@ -437,10 +438,10 @@ HWTEST_F(AmsAbilityRunningRecordModuleTest, ClearAbilityRunningRecord_002, TestS sptr token = new MockAbilityToken(); HapModuleInfo hapModuleInfo; hapModuleInfo.moduleName = "Module"; - appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); - auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo); + auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo, nullptr); EXPECT_TRUE(caseAbilityRunningRecord == nullptr); caseAbilityRunningRecord = moduleRecord->GetAbilityRunningRecord(ABILITY_RECORD_NAME + "_" + std::to_string(i)); EXPECT_EQ(caseAbilityRunningRecord, appRunningRecord->GetAbilityRunningRecordByToken(token)); @@ -476,10 +477,10 @@ HWTEST_F(AmsAbilityRunningRecordModuleTest, OperateAbilityRunningRecord_001, Tes sptr token = new MockAbilityToken(); HapModuleInfo hapModuleInfo; hapModuleInfo.moduleName = "Module"; - appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo); + appRunningRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo, nullptr); auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); - auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo); + auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo, nullptr); EXPECT_TRUE(caseAbilityRunningRecord == nullptr); caseAbilityRunningRecord = moduleRecord->GetAbilityRunningRecord(ABILITY_RECORD_NAME + "_" + std::to_string(i)); EXPECT_EQ(caseAbilityRunningRecord, appRunningRecord->GetAbilityRunningRecordByToken(token)); diff --git a/services/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp b/services/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp index 41ae0c5b356eb4ae89040f745f099435a68b994d..d6b39eb576442e7595d0e710c993a02e9f52de9f 100755 --- a/services/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp +++ b/services/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp @@ -170,10 +170,10 @@ std::shared_ptr AmsAppLifeCycleModuleTest::StartProcessAndLoad if (!testProcessInfo.isStart) { StartAppProcess(testProcessInfo.pid); } else { - EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _, _)).Times(1); } - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); BundleInfo bundleInfo; HapModuleInfo hapModuleInfo; EXPECT_TRUE(serviceInner_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); @@ -204,7 +204,7 @@ void AmsAppLifeCycleModuleTest::ChangeAbilityStateAfterAppStart( const sptr &mockAppScheduler, const pid_t &pid) const { EXPECT_CALL(*mockAppScheduler, ScheduleLaunchApplication(_, _)).Times(1); - EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _)).Times(1); + EXPECT_CALL(*mockAppScheduler, ScheduleLaunchAbility(_, _, _)).Times(1); sptr client = iface_cast(mockAppScheduler.GetRefPtr()); serviceInner_->AttachApplication(pid, client); @@ -349,7 +349,7 @@ void AmsAppLifeCycleModuleTest::CreateAppRecentList(const int32_t appNum) EXPECT_CALL(*mockAppStateCallbackStub_, OnAppStateChanged(_)).Times(1); serviceInner_->SetAppSpawnClient(std::unique_ptr(mockedSpawnClient)); - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); } return; } @@ -682,6 +682,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_006, TestSize.Level2) CheckState(appRunningRecord, token, AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); + int32_t ret = serviceInner_->KillApplication(appInfo->bundleName); EXPECT_EQ(ret, 0); serviceInner_->OnRemoteDied(mockAppScheduler); // A faked death recipient. @@ -1092,7 +1093,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, AbilityBehaviorAnalysis_01, TestSize.Level1) serviceInner_->SetBundleManager(bundleMgr.GetRefPtr()); StartAppProcess(pid); - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); BundleInfo bundleInfo; HapModuleInfo hapModuleInfo; EXPECT_TRUE(serviceInner_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); @@ -1148,7 +1149,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, AbilityBehaviorAnalysis_02, TestSize.Level1) serviceInner_->SetBundleManager(bundleMgr.GetRefPtr()); StartAppProcess(pid); - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); BundleInfo bundleInfo; HapModuleInfo hapModuleInfo; EXPECT_TRUE(serviceInner_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); @@ -1204,7 +1205,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, AbilityBehaviorAnalysis_03, TestSize.Level1) serviceInner_->SetBundleManager(bundleMgr.GetRefPtr()); StartAppProcess(pid); - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); BundleInfo bundleInfo; HapModuleInfo hapModuleInfo; EXPECT_TRUE(serviceInner_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); @@ -1260,7 +1261,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, AbilityBehaviorAnalysis_04, TestSize.Level1) serviceInner_->SetBundleManager(bundleMgr.GetRefPtr()); StartAppProcess(pid); - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); BundleInfo bundleInfo; HapModuleInfo hapModuleInfo; EXPECT_TRUE(serviceInner_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); @@ -1316,7 +1317,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, AbilityBehaviorAnalysis_05, TestSize.Level1) serviceInner_->SetBundleManager(bundleMgr.GetRefPtr()); StartAppProcess(pid); - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); BundleInfo bundleInfo; HapModuleInfo hapModuleInfo; EXPECT_TRUE(serviceInner_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); @@ -1374,7 +1375,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, AbilityBehaviorAnalysis_06, TestSize.Level1) serviceInner_->SetBundleManager(bundleMgr.GetRefPtr()); StartAppProcess(pid); - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); BundleInfo bundleInfo; HapModuleInfo hapModuleInfo; EXPECT_TRUE(serviceInner_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); @@ -1710,6 +1711,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, KillApplication_001, TestSize.Level1) EXPECT_EQ(2, static_cast(appMap.size())); EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); EXPECT_CALL(*mockAppScheduler1, ScheduleProcessSecurityExit()).Times(1); + int32_t ret = serviceInner_->KillApplication("com.ohos.test.helloworld0"); EXPECT_EQ(ret, 0); serviceInner_->OnRemoteDied(mockAppScheduler); // A faked death recipient. @@ -1764,6 +1766,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, KillApplication_002, TestSize.Level1) auto appMap = serviceInner_->appRunningManager_->GetAppRunningRecordMap(); EXPECT_EQ(2, static_cast(appMap.size())); EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); + int32_t ret = serviceInner_->KillApplication("com.ohos.test.helloworld103"); EXPECT_EQ(ret, 0); serviceInner_->OnRemoteDied(mockAppScheduler); // A faked death recipient. @@ -1815,6 +1818,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, KillApplication_003, TestSize.Level1) auto appMap = serviceInner_->appRunningManager_->GetAppRunningRecordMap(); EXPECT_EQ(1, static_cast(appMap.size())); EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); + int32_t ret = serviceInner_->KillApplication("com.ohos.test.helloworld101"); EXPECT_EQ(ret, 0); serviceInner_->OnRemoteDied(mockAppScheduler); // A faked death recipient. diff --git a/services/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp b/services/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp index 7cf2697ee730eee1351e0f6f82f97a9515eb952e..abb68fa83aa7fc4e762c39a0dcc95891cc7348bc 100644 --- a/services/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp +++ b/services/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp @@ -53,7 +53,8 @@ public: {} void ScheduleLaunchApplication(const AppLaunchData &, const Configuration &) override {} - void ScheduleLaunchAbility(const AbilityInfo &, const sptr &) override + void ScheduleLaunchAbility(const AbilityInfo &, const sptr &, + const std::shared_ptr &) override {} void ScheduleCleanAbility(const sptr &) override {} diff --git a/services/test/moduletest/common/ams/app_recent_list_test/ams_app_recent_list_module_test.cpp b/services/test/moduletest/common/ams/app_recent_list_test/ams_app_recent_list_module_test.cpp index 6abb9ed978dc6f15483cdac4800bfde2a61eb403..ba7660d872338d1be7a2c501abfde5c9250044a6 100644 --- a/services/test/moduletest/common/ams/app_recent_list_test/ams_app_recent_list_module_test.cpp +++ b/services/test/moduletest/common/ams/app_recent_list_test/ams_app_recent_list_module_test.cpp @@ -124,7 +124,7 @@ void AmsAppRecentListModuleTest::CreateAppRecentList(const int32_t appNum) .WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); serviceInner_->SetAppSpawnClient(std::unique_ptr(mockedSpawnClient)); - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); } return; } @@ -157,7 +157,7 @@ HWTEST_F(AmsAppRecentListModuleTest, Create_Recent_List_001, TestSize.Level1) MockAppSpawnClient *mockedSpawnClient = new MockAppSpawnClient(); serviceInner_->SetAppSpawnClient(std::unique_ptr(mockedSpawnClient)); - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); EXPECT_EQ(INDEX_NUM_10, static_cast(serviceInner_->GetRecentAppList().size())); APP_LOGI("Create_Recent_List_001 end"); } @@ -192,7 +192,7 @@ HWTEST_F(AmsAppRecentListModuleTest, Create_Recent_List_002, TestSize.Level1) EXPECT_CALL(*mockedSpawnClient, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); serviceInner_->SetAppSpawnClient(std::unique_ptr(mockedSpawnClient)); - serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr); EXPECT_EQ(INDEX_NUM_10 + INDEX_NUM_1, static_cast(serviceInner_->GetRecentAppList().size())); APP_LOGI("Create_Recent_List_002 end"); } diff --git a/services/test/moduletest/common/ams/app_running_record_test/ams_app_running_record_module_test.cpp b/services/test/moduletest/common/ams/app_running_record_test/ams_app_running_record_module_test.cpp index b683cbb65bb41ed26b88cfb79d96f7696d407527..c4c5d25242a281e7f7be044b782d66693a7b14d6 100644 --- a/services/test/moduletest/common/ams/app_running_record_test/ams_app_running_record_module_test.cpp +++ b/services/test/moduletest/common/ams/app_running_record_test/ams_app_running_record_module_test.cpp @@ -197,7 +197,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, ApplicationStart_001, TestSize.Level1) HapModuleInfo hapModuleInfo; EXPECT_TRUE(service_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); auto record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo); + GetMockToken(), nullptr, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo, nullptr); record->SetUid(0); EXPECT_TRUE(record != nullptr) << ",create apprunningrecord fail!"; @@ -261,7 +261,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, MultiApplicationStart_002, TestSize.Leve HapModuleInfo hapModuleInfo; EXPECT_TRUE(service_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); auto record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo); + GetMockToken(), nullptr, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo, nullptr); record->SetUid(0); EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; @@ -307,7 +307,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, ScheduleTrimMemory_003, TestSize.Level1) HapModuleInfo hapModuleInfo; EXPECT_TRUE(service_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); auto record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo); + GetMockToken(), nullptr, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo, nullptr); EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; // LaunchApplication @@ -357,7 +357,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, LowMemoryWarning_004, TestSize.Level1) HapModuleInfo hapModuleInfo; EXPECT_TRUE(service_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); auto record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo); + GetMockToken(), nullptr, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo, nullptr); EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; // LaunchApplication @@ -409,7 +409,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, ApplicationStartAndQuit_005, TestSize.Le HapModuleInfo hapModuleInfo; EXPECT_TRUE(service_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); auto record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo); + GetMockToken(), nullptr, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo, nullptr); EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; // LaunchApplication @@ -479,7 +479,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, ApplicationStatusChange_006, TestSize.Le HapModuleInfo hapModuleInfo; EXPECT_TRUE(service_->GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)); auto record = service_->CreateAppRunningRecord( - GetMockToken(), nullptr, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo); + GetMockToken(), nullptr, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo, nullptr); EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; // LaunchApplication diff --git a/services/test/moduletest/common/ams/app_service_flow_test/ams_app_service_flow_module_test.cpp b/services/test/moduletest/common/ams/app_service_flow_test/ams_app_service_flow_module_test.cpp index e05981c13326588bd5d3400cb1f4a1fcd8ce2ba9..905040828ea22c0625d3b867ac07e94084f92929 100644 --- a/services/test/moduletest/common/ams/app_service_flow_test/ams_app_service_flow_module_test.cpp +++ b/services/test/moduletest/common/ams/app_service_flow_test/ams_app_service_flow_module_test.cpp @@ -139,10 +139,10 @@ TestApplicationPreRunningRecord AmsAppServiceFlowModuleTest::TestCreateApplicati appInfo->name, appName, appInfo->uid, bundleInfo); if (!appRecord) { appRecord = serviceInner_->CreateAppRunningRecord( - token, nullptr, appInfo, abilityInfo, appName, bundleInfo, hapModuleInfo); + token, nullptr, appInfo, abilityInfo, appName, bundleInfo, hapModuleInfo, nullptr); appRecord->GetPriorityObject()->SetPid(TestApplicationPreRunningRecord::g_pid++); } else { - serviceInner_->StartAbility(token, nullptr, abilityInfo, appRecord, hapModuleInfo); + serviceInner_->StartAbility(token, nullptr, abilityInfo, appRecord, hapModuleInfo, nullptr); } EXPECT_TRUE(appRecord); diff --git a/services/test/moduletest/common/ams/ipc_ams_mgr_test/ams_ipc_ams_mgr_module_test.cpp b/services/test/moduletest/common/ams/ipc_ams_mgr_test/ams_ipc_ams_mgr_module_test.cpp index b85df8ce86fde64468c9c2aacdd56985641c687f..aafc5a4623a2be8edc24617c4102329dd6280d03 100644 --- a/services/test/moduletest/common/ams/ipc_ams_mgr_test/ams_ipc_ams_mgr_module_test.cpp +++ b/services/test/moduletest/common/ams/ipc_ams_mgr_test/ams_ipc_ams_mgr_module_test.cpp @@ -130,48 +130,6 @@ std::shared_ptr AmsIpcAmsmgrModuleTest::GetAmsEventHandler() return amsEventHandler_; } -/* - * Feature: ApplicationFramework - * Function: AppManagerService - * SubFunction: AmsmgrIPCInterface - * FunctionPoints: test loadAbility API,then check the function whether is good or not - * EnvConditions: system running normally - * CaseDescription: excute loadAbility API 1000 times - */ -HWTEST_F(AmsIpcAmsmgrModuleTest, ExcuteAmsmgrIPCInterface_001, TestSize.Level3) -{ - auto abilityInfo = GetAbilityInfo("0", "MainAbility", "com.ohos.test.helloworld"); - auto appInfo = GetApplicationInfo("com.ohos.test.helloworld"); - auto mockAppMgrServiceInner = GetMockAppMgrServiceInner(); - auto amsEventHandler = GetAmsEventHandler(); - std::unique_ptr amsMgrScheduler = - std::make_unique(mockAppMgrServiceInner, amsEventHandler); - - sptr mockMockAppMgr(new MockMockAppMgrService()); - sptr appMgrClient = iface_cast(mockMockAppMgr); - - auto mockHandler = [&]() -> sptr { - mockMockAppMgr->Post(); - return sptr(amsMgrScheduler.get()); - }; - - EXPECT_CALL(*mockMockAppMgr, GetAmsMgr()).Times(1).WillOnce(Invoke(mockHandler)); - - auto amsMgrScheduler_ = appMgrClient->GetAmsMgr(); - mockMockAppMgr->Wait(); - sptr token = new MockAbilityToken(); - - for (int i = 0; i < COUNT; i++) { - EXPECT_CALL(*mockAppMgrServiceInner, LoadAbility(_, _, _, _)) - .WillOnce(InvokeWithoutArgs(mockAppMgrServiceInner.get(), &MockAppMgrServiceInner::Post)); - amsMgrScheduler_->LoadAbility(token_, nullptr, abilityInfo, appInfo); - mockAppMgrServiceInner->Wait(); - } - - mockAppMgrServiceInner.reset(); - amsMgrScheduler.release(); -} - /* * Feature: ApplicationFramework * Function: AppManagerService diff --git a/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp b/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp index bb42c380bcb1371c06f92c4f0ada0db0f1c4e2e2..42d9a26bbbdb5c031decf32b51719e79ebbb58ad 100644 --- a/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp +++ b/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp @@ -200,34 +200,6 @@ HWTEST_F(AmsIpcAppSchedulerModuleTest, ExcuteApplicationIPCInterface_006, TestSi } } -/* - * Feature: ApplicationFramework - * Function: AppManagerService - * SubFunction: IApplicationScheduler - * FunctionPoints: test ScheduleLaunchAbility API,then check the function whether is good or not - * EnvConditions: system running normally - * CaseDescription: excute ScheduleLaunchAbility API 10000 times - */ -HWTEST_F(AmsIpcAppSchedulerModuleTest, ExcuteApplicationIPCInterface_007, TestSize.Level3) -{ - for (int i = 0; i < COUNT; i++) { - sptr mockApplication(new MockApplication()); - sptr client = iface_cast(mockApplication); - - std::string abilityName("mockAbilityInfo"); - AbilityInfo info; - info.name = abilityName; - - EXPECT_CALL(*mockApplication, ScheduleLaunchAbility(_, _)) - .Times(1) - .WillOnce(Invoke(mockApplication.GetRefPtr(), &MockApplication::LaunchAbility)); - client->ScheduleLaunchAbility(info, GetMockToken()); - mockApplication->Wait(); - bool result = mockApplication->CompareAbilityInfo(info); - EXPECT_EQ(result, true) << "excute fail, index is " << i; - } -} - /* * Feature: ApplicationFramework * Function: AppManagerService diff --git a/services/test/moduletest/dump_module_test/BUILD.gn b/services/test/moduletest/dump_module_test/BUILD.gn index 2a3b91a067aa9b677a406c705c2a9201c193128a..3dda95945a9ead35e8d0b2bf5f037b929b59d60f 100755 --- a/services/test/moduletest/dump_module_test/BUILD.gn +++ b/services/test/moduletest/dump_module_test/BUILD.gn @@ -62,6 +62,7 @@ ohos_moduletest("dump_module_test") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "bytrace_standard:bytrace_core", "device_manager_base:devicemanagersdk", "hiviewdfx_hilog_native:libhilog", diff --git a/services/test/moduletest/dump_module_test/dump_module_test.cpp b/services/test/moduletest/dump_module_test/dump_module_test.cpp index 68943019cac041436adca66c4d22ecc655faad5f..85d1448ceedd944faa0fb15a76c4500d8377eaef 100644 --- a/services/test/moduletest/dump_module_test/dump_module_test.cpp +++ b/services/test/moduletest/dump_module_test/dump_module_test.cpp @@ -46,6 +46,7 @@ namespace { const std::string NAME_BUNDLE_MGR_SERVICE = "BundleMgrService"; static std::shared_ptr g_abilityMs = nullptr; static std::shared_ptr g_appTestService = nullptr; +static bool g_alreadyInit = false; static const ElementName G_TESTABILITY1("device", "com.ix.hiMusic", "MainAbility1"); static const ElementName G_TESTABILITY2("device", "com.ix.hiMusic", "MainAbility2"); @@ -120,29 +121,32 @@ void DumpModuleTest::OnStartAms() } g_abilityMs->state_ = ServiceRunningState::STATE_RUNNING; - g_abilityMs->eventLoop_ = AppExecFwk::EventRunner::Create(AbilityConfig::NAME_ABILITY_MGR_SERVICE); EXPECT_TRUE(g_abilityMs->eventLoop_); g_abilityMs->handler_ = std::make_shared(g_abilityMs->eventLoop_, g_abilityMs); + g_abilityMs->connectManager_ = std::make_shared(); + g_abilityMs->connectManagers_.emplace(0, g_abilityMs->connectManager_); EXPECT_TRUE(g_abilityMs->handler_); EXPECT_TRUE(g_abilityMs->connectManager_); g_abilityMs->connectManager_->SetEventHandler(g_abilityMs->handler_); g_abilityMs->dataAbilityManager_ = std::make_shared(); + g_abilityMs->dataAbilityManagers_.emplace(0, g_abilityMs->dataAbilityManager_); EXPECT_TRUE(g_abilityMs->dataAbilityManager_); + g_abilityMs->currentMissionListManager_ = std::make_shared(0); + g_abilityMs->currentMissionListManager_->Init(); g_abilityMs->pendingWantManager_ = std::make_shared(); EXPECT_TRUE(g_abilityMs->pendingWantManager_); int userId = g_abilityMs->GetUserId(); g_abilityMs->SetStackManager(userId, true); + g_abilityMs->stackManagers_.emplace(0, g_abilityMs->GetStackManager()); g_abilityMs->systemAppManager_ = std::make_shared(userId); EXPECT_TRUE(g_abilityMs->systemAppManager_); - g_abilityMs->eventLoop_->Run(); - GTEST_LOG_(INFO) << "OnStart success"; return; } @@ -183,12 +187,15 @@ void DumpModuleTest::SetUp() void DumpModuleTest::TearDown() { g_abilityMs->OnStop(); - OHOS::DelayedSingleton::DestroyInstance(); GTEST_LOG_(INFO) << "TearDown OK"; } void DumpModuleTest::StartAllAbilities() { + if (g_alreadyInit) { + return; + } + g_alreadyInit = true; wantLauncher.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); g_abilityMs->StartAbility(wantLauncher); WaitUntilTaskFinished(); @@ -245,63 +252,24 @@ HWTEST_F(DumpModuleTest, dump_module_test_001, TestSize.Level2) { std::vector dumpInfo; g_abilityMs->DumpState("--stack 1", dumpInfo); - std::vector abilitiesStarted = { - want55, - want44, - want33, - want22, - want11, - }; std::vector abilityNames; MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, abilityNames); - EXPECT_EQ(abilitiesStarted.size(), abilityNames.size()); - for (unsigned int i = 0; i < abilityNames.size(); ++i) { - EXPECT_EQ(0, abilitiesStarted[i].GetElement().GetAbilityName().compare(abilityNames[i])); - } - + EXPECT_EQ(0, abilityNames.size()); dumpInfo.clear(); g_abilityMs->DumpState("--stack 0", dumpInfo); - abilitiesStarted = { - wantLauncher, - }; MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, abilityNames); - EXPECT_EQ(abilitiesStarted.size(), abilityNames.size()); - for (unsigned int i = 0; i < abilityNames.size(); ++i) { - EXPECT_EQ(0, abilitiesStarted[i].GetElement().GetAbilityName().compare(abilityNames[i])); - } + EXPECT_EQ(6, abilityNames.size()); dumpInfo.clear(); - g_abilityMs->DumpState("--stack 1 abc", dumpInfo); - abilitiesStarted = { - want55, - want44, - want33, - want22, - want11, - }; MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, abilityNames); - EXPECT_EQ(abilitiesStarted.size(), abilityNames.size()); - for (unsigned int i = 0; i < abilityNames.size(); ++i) { - EXPECT_EQ(0, abilitiesStarted[i].GetElement().GetAbilityName().compare(abilityNames[i])); - } + EXPECT_EQ(0, abilityNames.size()); dumpInfo.clear(); - g_abilityMs->DumpState(" --stack 1", dumpInfo); - abilitiesStarted = { - want55, - want44, - want33, - want22, - want11, - }; MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, abilityNames); - EXPECT_EQ(abilitiesStarted.size(), abilityNames.size()); - for (unsigned int i = 0; i < abilityNames.size(); ++i) { - EXPECT_EQ(0, abilitiesStarted[i].GetElement().GetAbilityName().compare(abilityNames[i])); - } + EXPECT_EQ(0, abilityNames.size()); } /* @@ -316,35 +284,14 @@ HWTEST_F(DumpModuleTest, dump_module_test_002, TestSize.Level2) { std::vector dumpInfo; g_abilityMs->GetStackManager()->DumpStack(1, dumpInfo); - std::vector abilitiesStarted = { - want55, - want44, - want33, - want22, - want11, - }; std::vector abilityNames; MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, abilityNames); - - GTEST_LOG_(INFO) << "abilitiesStarted.size() = " << abilitiesStarted.size(); GTEST_LOG_(INFO) << "abilityNames.size() = " << abilityNames.size(); - - EXPECT_EQ(abilitiesStarted.size(), abilityNames.size()); - for (unsigned int i = 0; i < abilityNames.size(); ++i) { - EXPECT_EQ(0, abilitiesStarted[i].GetElement().GetAbilityName().compare(abilityNames[i])); - } - + EXPECT_EQ(0, abilityNames.size()); dumpInfo.clear(); - g_abilityMs->GetStackManager()->DumpStack(0, dumpInfo); - abilitiesStarted = { - wantLauncher, - }; MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, abilityNames); - EXPECT_EQ(abilitiesStarted.size(), abilityNames.size()); - for (unsigned int i = 0; i < abilityNames.size(); ++i) { - EXPECT_EQ(0, abilitiesStarted[i].GetElement().GetAbilityName().compare(abilityNames[i])); - } + EXPECT_EQ(6, abilityNames.size()); } /* @@ -552,20 +499,8 @@ HWTEST_F(DumpModuleTest, dump_module_test_008, TestSize.Level2) GTEST_LOG_(INFO) << "args = " << args; g_abilityMs->DumpState(args, dumpInfo); - - std::vector abilitiesStarted = { - want55, - want44, - want33, - want22, - want11, - }; - MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, abilityNames); - EXPECT_EQ(abilitiesStarted.size(), abilityNames.size()); - for (unsigned int i = 0; i < abilityNames.size(); ++i) { - EXPECT_EQ(0, abilitiesStarted[i].GetElement().GetAbilityName().compare(abilityNames[i])); - } + EXPECT_EQ(6, abilityNames.size()); } /* diff --git a/services/test/moduletest/ipc_ability_scheduler_test/ipc_ability_scheduler_module_test.cpp b/services/test/moduletest/ipc_ability_scheduler_test/ipc_ability_scheduler_module_test.cpp index 810d529a9a337ba060fed27cc276eaac8ffa5720..859946c94775c2cbf7c1224d596ec9a8cf1b339b 100644 --- a/services/test/moduletest/ipc_ability_scheduler_test/ipc_ability_scheduler_module_test.cpp +++ b/services/test/moduletest/ipc_ability_scheduler_test/ipc_ability_scheduler_module_test.cpp @@ -426,7 +426,8 @@ HWTEST_F(IpcAbilitySchedulerModuleTest, Update_001, TestSize.Level1) NativeRdb::DataAbilityPredicates testPred; int testRet = 123; - auto mockHandler = [&](const Uri &uri, const NativeRdb::ValuesBucket &vb, const NativeRdb::DataAbilityPredicates &pred) { + auto mockHandler = [&](const Uri &uri, const NativeRdb::ValuesBucket &vb, + const NativeRdb::DataAbilityPredicates &pred) { testResult = true; sem.Post(); return testRet; @@ -504,7 +505,8 @@ HWTEST_F(IpcAbilitySchedulerModuleTest, Query_001, TestSize.Level1) testColumns.emplace_back("col2"); NativeRdb::DataAbilityPredicates testPred; - auto mockHandler = [&](const Uri &uri, std::vector &columns, const NativeRdb::DataAbilityPredicates &pred) { + auto mockHandler = [&](const Uri &uri, std::vector &columns, + const NativeRdb::DataAbilityPredicates &pred) { testResult = (columns == testColumns); sem.Post(); return std::make_shared("DataAbilityTest"); diff --git a/services/test/moduletest/panding_want_manager_test/BUILD.gn b/services/test/moduletest/panding_want_manager_test/BUILD.gn index db815d1f40732f900e5a6141951a108dea8abd8b..95956bf46694fc03380f5122ca7af7005e4d8af5 100755 --- a/services/test/moduletest/panding_want_manager_test/BUILD.gn +++ b/services/test/moduletest/panding_want_manager_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -49,14 +49,15 @@ ohos_moduletest("PandingWantMgrTest") { deps = [ "${innerkits_path}/base:base", + "${innerkits_path}/uri_permission:uri_permission_mgr", "${innerkits_path}/want:want", "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//base/global/i18n_standard/frameworks/intl:intl_util", "//base/hiviewdfx/hiview/adapter/utility:hiview_adapter_utility", - "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", "//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", + "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/ace/ace_engine/interfaces/innerkits/ui_service_manager:ui_service_mgr", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", @@ -74,6 +75,7 @@ ohos_moduletest("PandingWantMgrTest") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "bytrace_standard:bytrace_core", "ces_standard:cesfwk_core", "ces_standard:cesfwk_innerkits", diff --git a/services/test/moduletest/panding_want_manager_test/panding_want_manager_test.cpp b/services/test/moduletest/panding_want_manager_test/panding_want_manager_test.cpp index 2b20747fefcf69ec6925492ed13e4833e6ae840c..88c1e3e93bf969cbf76d5652c43ca387a9d6b1d4 100644 --- a/services/test/moduletest/panding_want_manager_test/panding_want_manager_test.cpp +++ b/services/test/moduletest/panding_want_manager_test/panding_want_manager_test.cpp @@ -38,7 +38,7 @@ #include "mock_ability_mgr_service.h" #include "os_account_manager.h" -using namespace OHOS::Notification::WantAgent; +using namespace OHOS::AbilityRuntime::WantAgent; using namespace OHOS::AppExecFwk; using namespace testing; @@ -98,7 +98,7 @@ void PandingWantManagerTest::SetUpTestCase(void) void PandingWantManagerTest::TearDownTestCase(void) { - OHOS::DelayedSingleton::DestroyInstance(); + abilityManager->OnStop(); if (appClient) { delete appClient; appClient = nullptr; @@ -249,74 +249,6 @@ WantAgentInfo PandingWantManagerTest::MakeWantAgentInfo(WantAgentConstant::Opera return info; } -/* - * Feature: AaFwk - * Function: GetWantSender - * SubFunction: start a page ability - * FunctionPoints: NA - * EnvConditions: NA - * CaseDescription: get want sender / send want sender - */ -HWTEST_F(PandingWantManagerTest, pending_want_mgr_test_001, TestSize.Level1) -{ - WantAgentConstant::OperationType type = WantAgentConstant::OperationType::START_ABILITY; - int requsetCode = 10; - WantAgentConstant::Flags flag = WantAgentConstant::Flags::ONE_TIME_FLAG; - std::vector flags; - flags.push_back(flag); - - auto abilityWant = GetWant("hiMusic", "com.ix.hiMusic"); - std::vector> wants; - wants.push_back(abilityWant); - - WantAgentInfo info = MakeWantAgentInfo(type, requsetCode, flags, wants); - std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); - - // proxy start - auto amsProxyGetWantSenderReturn = [&](const WantSenderInfo &wantSenderInfo, - const sptr &callerToken) { - EXPECT_EQ(wantSenderInfo.type, (int32_t)WantAgentConstant::OperationType::START_ABILITY); - return abilityManager->GetWantSender(wantSenderInfo, callerToken); - }; - EXPECT_CALL(*amsSerice, GetWantSender(_, _)).Times(1).WillOnce(Invoke(amsProxyGetWantSenderReturn)); - - auto amsProxySendWantSenderReturn = [&](const sptr &target, const SenderInfo &senderInfo) { - return abilityManager->SendWantSender(target, senderInfo); - }; - EXPECT_CALL(*amsSerice, SendWantSender(_, _)).Times(1).WillOnce(Invoke(amsProxySendWantSenderReturn)); - EXPECT_CALL(*amsSerice, GetPendingWantType(_)).Times(1).WillOnce(Return(0)); - - // proxy end - // call GetWantAgent - std::shared_ptr wantAgent = WantAgentHelper::GetWantAgent(context, info); - EXPECT_NE(wantAgent, nullptr); - auto pandingWant = wantAgent->GetPendingWant(); - EXPECT_NE(pandingWant, nullptr); - - // abilityManager mock - EXPECT_CALL(*appClient, LoadAbility(_, _, _, _)).Times(1).WillOnce(Return(AppMgrResultCode::RESULT_OK)); - - std::shared_ptr callback; - MockCompletedCallback *call = new MockCompletedCallback(); - callback.reset(call); - - TriggerInfo paramsInfo("", nullptr, abilityWant, 11); - - EXPECT_CALL(*call, OnSendFinished(_, _, _, _)).Times(1); - WantAgentHelper::TriggerWantAgent(wantAgent, callback, paramsInfo); - - // An ability should be activated - auto stackMgr = abilityManager->GetStackManager(); - EXPECT_NE(stackMgr, nullptr); - auto topAbility = stackMgr->GetCurrentTopAbility(); - EXPECT_NE(topAbility, nullptr); - Want topAbilityWant = topAbility->GetWant(); - ElementName element = topAbilityWant.GetElement(); - - EXPECT_EQ(element.GetAbilityName(), "hiMusic"); - EXPECT_EQ(element.GetBundleName(), "com.ix.hiMusic"); -} - /* * Feature: AaFwk * Function: GetWantSender @@ -382,139 +314,6 @@ HWTEST_F(PandingWantManagerTest, pending_want_mgr_test_002, TestSize.Level1) WantAgentHelper::TriggerWantAgent(wantAgent, callback, paramsInfo); } -/* - * Feature: AaFwk - * Function: GetWantSender - * SubFunction: start services ability - * FunctionPoints: NA - * EnvConditions: NA - * CaseDescription: get want sender / send want sender - */ -HWTEST_F(PandingWantManagerTest, pending_want_mgr_test_003, TestSize.Level1) -{ - WantAgentConstant::OperationType type = WantAgentConstant::OperationType::START_SERVICE; - int requsetCode = 10; - WantAgentConstant::Flags flag = WantAgentConstant::Flags::ONE_TIME_FLAG; - std::vector flags; - flags.push_back(flag); - - auto abilityWant = GetWant("hiService", "com.ix.hiService"); - std::vector> wants; - wants.push_back(abilityWant); - - WantAgentInfo info = MakeWantAgentInfo(type, requsetCode, flags, wants); - std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); - - // proxy start - auto amsProxyGetWantSenderReturn = [&](const WantSenderInfo &wantSenderInfo, - const sptr &callerToken) { - EXPECT_EQ(wantSenderInfo.type, (int32_t)WantAgentConstant::OperationType::START_SERVICE); - return abilityManager->GetWantSender(wantSenderInfo, callerToken); - }; - EXPECT_CALL(*amsSerice, GetWantSender(_, _)).Times(1).WillOnce(Invoke(amsProxyGetWantSenderReturn)); - - auto amsProxySendWantSenderReturn = [&](const sptr &target, const SenderInfo &senderInfo) { - return abilityManager->SendWantSender(target, senderInfo); - }; - EXPECT_CALL(*amsSerice, SendWantSender(_, _)).Times(1).WillOnce(Invoke(amsProxySendWantSenderReturn)); - EXPECT_CALL(*amsSerice, GetPendingWantType(_)).Times(1).WillOnce(Return(0)); - - // proxy end - // call GetWantAgent - std::shared_ptr wantAgent = WantAgentHelper::GetWantAgent(context, info); - EXPECT_NE(wantAgent, nullptr); - auto pandingWant = wantAgent->GetPendingWant(); - EXPECT_NE(pandingWant, nullptr); - - // abilityManager mock - EXPECT_CALL(*appClient, LoadAbility(_, _, _, _)).Times(1).WillOnce(Return(AppMgrResultCode::RESULT_OK)); - - std::shared_ptr callback; - MockCompletedCallback *call = new MockCompletedCallback(); - callback.reset(call); - - TriggerInfo paramsInfo("", nullptr, abilityWant, 11); - - EXPECT_CALL(*call, OnSendFinished(_, _, _, _)).Times(1); - WantAgentHelper::TriggerWantAgent(wantAgent, callback, paramsInfo); - - // An ability should be activated - auto serviceRecord = - abilityManager->connectManager_->GetServiceRecordByElementName(abilityWant->GetElement().GetURI()); - EXPECT_TRUE(serviceRecord); - Want serviceWant = serviceRecord->GetWant(); - ElementName element = serviceWant.GetElement(); - - EXPECT_EQ(element.GetAbilityName(), "hiService"); - EXPECT_EQ(element.GetBundleName(), "com.ix.hiService"); -} - -/* - * Feature: AaFwk - * Function: GetWantSender - * SubFunction: get foreground service ability - * FunctionPoints: NA - * EnvConditions: NA - * CaseDescription: get want sender / send want sender - */ -HWTEST_F(PandingWantManagerTest, pending_want_mgr_test_004, TestSize.Level1) -{ - WantAgentConstant::OperationType type = WantAgentConstant::OperationType::START_FOREGROUND_SERVICE; - int requsetCode = 112; - WantAgentConstant::Flags flag = WantAgentConstant::Flags::ONE_TIME_FLAG; - std::vector flags; - flags.push_back(flag); - - auto abilityWant = GetWant("hiServiceForground", "com.ix.hiService"); - std::vector> wants; - wants.push_back(abilityWant); - - WantAgentInfo info = MakeWantAgentInfo(type, requsetCode, flags, wants); - std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); - - // proxy start - auto amsProxyGetWantSenderReturn = [&](const WantSenderInfo &wantSenderInfo, - const sptr &callerToken) { - EXPECT_EQ(wantSenderInfo.type, (int32_t)WantAgentConstant::OperationType::START_FOREGROUND_SERVICE); - return abilityManager->GetWantSender(wantSenderInfo, callerToken); - }; - EXPECT_CALL(*amsSerice, GetWantSender(_, _)).Times(1).WillOnce(Invoke(amsProxyGetWantSenderReturn)); - - auto amsProxySendWantSenderReturn = [&](const sptr &target, const SenderInfo &senderInfo) { - return abilityManager->SendWantSender(target, senderInfo); - }; - EXPECT_CALL(*amsSerice, SendWantSender(_, _)).Times(1).WillOnce(Invoke(amsProxySendWantSenderReturn)); - EXPECT_CALL(*amsSerice, GetPendingWantType(_)).Times(1).WillOnce(Return(0)); - - // proxy end - // call GetWantAgent - std::shared_ptr wantAgent = WantAgentHelper::GetWantAgent(context, info); - EXPECT_NE(wantAgent, nullptr); - auto pandingWant = wantAgent->GetPendingWant(); - EXPECT_NE(pandingWant, nullptr); - - // abilityManager mock - EXPECT_CALL(*appClient, LoadAbility(_, _, _, _)).Times(1).WillOnce(Return(AppMgrResultCode::RESULT_OK)); - - std::shared_ptr callback; - MockCompletedCallback *call = new MockCompletedCallback(); - callback.reset(call); - - TriggerInfo paramsInfo("", nullptr, abilityWant, 11); - - EXPECT_CALL(*call, OnSendFinished(_, _, _, _)).Times(1); - WantAgentHelper::TriggerWantAgent(wantAgent, callback, paramsInfo); - - // An ability should be activated - auto serviceRecord = - abilityManager->connectManager_->GetServiceRecordByElementName(abilityWant->GetElement().GetURI()); - EXPECT_TRUE(serviceRecord); - Want serviceWant = serviceRecord->GetWant(); - ElementName element = serviceWant.GetElement(); - EXPECT_EQ(element.GetAbilityName(), "hiServiceForground"); - EXPECT_EQ(element.GetBundleName(), "com.ix.hiService"); -} - /* * Feature: AaFwk * Function: GetWantSender diff --git a/services/uripermmgr/BUILD.gn b/services/uripermmgr/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..9389403c97a9c4f93ccf9dc77ffd373f5db49024 --- /dev/null +++ b/services/uripermmgr/BUILD.gn @@ -0,0 +1,67 @@ +# 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("//build/ohos.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +config("upms_config") { + visibility = [ ":*" ] + include_dirs = [ "include" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} + +group("upms_target") { + deps = [ + ":libupms", + ":upms.rc", + ] +} + +ohos_prebuilt_etc("upms.rc") { + relative_install_dir = "init" + source = "upms.cfg" + part_name = "ability_runtime" + subsystem_name = "aafwk" +} + +#build so +ohos_shared_library("libupms") { + configs = [ "${services_path}/common:common_config" ] + public_configs = [ ":upms_config" ] + + sources = [ + "src/uri_permission_manager_service.cpp", + "src/uri_permission_manager_stub_impl.cpp", + ] + + deps = [ + "${innerkits_path}/uri_permission:uri_permission_mgr", + "${innerkits_path}/want:want", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "dmsfwk_standard:zuri", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + "utils_base:utils", + ] + + subsystem_name = "aafwk" + part_name = "ability_runtime" +} diff --git a/services/uripermmgr/include/uri_permission_manager_service.h b/services/uripermmgr/include/uri_permission_manager_service.h new file mode 100644 index 0000000000000000000000000000000000000000..b091b47e6c7b57996b979421f70958febe7a9bc1 --- /dev/null +++ b/services/uripermmgr/include/uri_permission_manager_service.h @@ -0,0 +1,52 @@ +/* + * 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_AAFWK_URI_PERMISSION_MANAGER_SERVICE_H +#define OHOS_AAFWK_URI_PERMISSION_MANAGER_SERVICE_H + +#include "singleton.h" +#include "system_ability.h" +#include "uri_permission_manager_stub_impl.h" + +namespace OHOS { +namespace AAFwk { +class UriPermissionManagerService : public SystemAbility { + DECLARE_DELAYED_SINGLETON(UriPermissionManagerService); + DECLARE_SYSTEM_ABILITY(UriPermissionManagerService); +public: + void OnStart() override; + void OnStop() override; + + /** + * @brief Check whether if the uri permission manager service is ready. + * + * @return Returns true if the uri permission manager service is ready; returns false otherwise. + */ + bool IsServiceReady() const; + +private: + bool Init(); + void SelfClean(); + +private: + bool ready_ = false; + bool registerToService_ = false; + sptr impl_; + + DISALLOW_COPY_AND_MOVE(UriPermissionManagerService); +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_URI_PERMISSION_MANAGER_SERVICE_H diff --git a/services/uripermmgr/include/uri_permission_manager_stub_impl.h b/services/uripermmgr/include/uri_permission_manager_stub_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..8b0b453fea3fa9343ccf27f29d16243e95b37372 --- /dev/null +++ b/services/uripermmgr/include/uri_permission_manager_stub_impl.h @@ -0,0 +1,49 @@ +/* + * 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_AAFWK_URI_PERMISSION_MANAGER_STUB_IMPL_H +#define OHOS_AAFWK_URI_PERMISSION_MANAGER_STUB_IMPL_H + +#include + +#include "uri.h" +#include "uri_permission_manager_stub.h" + +namespace OHOS { +namespace AAFwk { +struct GrantInfo { + unsigned int flag; + int32_t fromTokenId; + int32_t targetTokenId; +}; +class UriPermissionManagerStubImpl : public UriPermissionManagerStub { +public: + UriPermissionManagerStubImpl() = default; + virtual ~UriPermissionManagerStubImpl() = default; + + void GrantUriPermission(const Uri &uri, unsigned int flag, const Security::AccessToken::AccessTokenID fromTokenId, + const Security::AccessToken::AccessTokenID targetTokenId) override; + + bool VerifyUriPermission(const Uri &uri, unsigned int flag, + const Security::AccessToken::AccessTokenID tokenId) override; + + void RemoveUriPermission(const Security::AccessToken::AccessTokenID tokenId) override; + +private: + std::map> uriMap_; +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_URI_PERMISSION_MANAGER_STUB_IMPL_H diff --git a/services/uripermmgr/src/uri_permission_manager_service.cpp b/services/uripermmgr/src/uri_permission_manager_service.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d0bee404edea7825859f1e34b7cd92c948c62c1e --- /dev/null +++ b/services/uripermmgr/src/uri_permission_manager_service.cpp @@ -0,0 +1,92 @@ +/* + * 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 "uri_permission_manager_service.h" + +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AAFwk { +const bool REGISTER_RESULT = + SystemAbility::MakeAndRegisterAbility(DelayedSingleton::GetInstance().get()); + +UriPermissionManagerService::UriPermissionManagerService() : SystemAbility(URI_PERMISSION_MGR_SERVICE_ID, true) {} + +UriPermissionManagerService::~UriPermissionManagerService() +{ + if (impl_ != nullptr) { + impl_ = nullptr; + } +} + +void UriPermissionManagerService::OnStart() +{ + HILOG_INFO("UriPermissionManagerService start is triggered."); + if (!Init()) { + HILOG_ERROR("init failed."); + return; + } + + if (!registerToService_) { + auto systemAabilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!systemAabilityMgr || systemAabilityMgr->AddSystemAbility(URI_PERMISSION_MGR_SERVICE_ID, impl_) != 0) { + HILOG_ERROR("fail to register to system ability manager"); + return; + } + HILOG_INFO("register to system ability manager success"); + registerToService_ = true; + } +} + +void UriPermissionManagerService::OnStop() +{ + HILOG_INFO("OnStop is called."); + SelfClean(); +} + +bool UriPermissionManagerService::IsServiceReady() const +{ + return ready_; +} + +bool UriPermissionManagerService::Init() +{ + if (ready_) { + HILOG_WARN("init more than one time."); + return true; + } + + if (impl_ == nullptr) { + impl_ = new UriPermissionManagerStubImpl(); + } + ready_ = true; + return true; +} + +void UriPermissionManagerService::SelfClean() +{ + if (ready_) { + ready_ = false; + if (registerToService_) { + registerToService_ = false; + } + } +} +} // namespace AAFwk +} // namespace OHOS diff --git a/services/uripermmgr/src/uri_permission_manager_stub_impl.cpp b/services/uripermmgr/src/uri_permission_manager_stub_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..342f9446c50b84ed192dfdf26cd49680abfb90ed --- /dev/null +++ b/services/uripermmgr/src/uri_permission_manager_stub_impl.cpp @@ -0,0 +1,110 @@ +/* + * 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 "uri_permission_manager_stub_impl.h" + +#include "accesstoken_kit.h" +#include "hilog_wrapper.h" +#include "ipc_skeleton.h" +#include "want.h" + +namespace OHOS { +namespace AAFwk { +void UriPermissionManagerStubImpl::GrantUriPermission(const Uri &uri, unsigned int flag, + const Security::AccessToken::AccessTokenID fromTokenId, const Security::AccessToken::AccessTokenID targetTokenId) +{ + auto callerTokenId = IPCSkeleton::GetCallingTokenID(); + HILOG_DEBUG("callerTokenId : %{pulic}u", callerTokenId); + auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callerTokenId); + if (tokenType != Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE) { + HILOG_DEBUG("caller tokenType is not native, verify failure."); + return; + } + if ((flag & (Want::FLAG_AUTH_READ_URI_PERMISSION | Want::FLAG_AUTH_WRITE_URI_PERMISSION)) == 0) { + HILOG_WARN("UriPermissionManagerStubImpl::GrantUriPermission: The param flag is invalid."); + return; + } + auto uriStr = uri.ToString(); + auto search = uriMap_.find(uriStr); + GrantInfo info = {flag, fromTokenId, targetTokenId}; + if (search == uriMap_.end()) { + HILOG_INFO("uri is not exist, add uri and GrantInfo to map."); + std::list infos = { info }; + uriMap_.emplace(uriStr, infos); + return; + } + auto infoList = search->second; + for (auto item : infoList) { + if (item.fromTokenId == fromTokenId && item.targetTokenId == targetTokenId) { + if ((flag & Want::FLAG_AUTH_WRITE_URI_PERMISSION) != 0) { + item.flag = flag; + } + HILOG_INFO("uri permission has granted, not to grant again."); + return; + } + } + HILOG_DEBUG("uri is exist, add GrantInfo to list."); + infoList.emplace_back(info); +} + +bool UriPermissionManagerStubImpl::VerifyUriPermission(const Uri &uri, unsigned int flag, + const Security::AccessToken::AccessTokenID tokenId) +{ + if ((flag & (Want::FLAG_AUTH_READ_URI_PERMISSION | Want::FLAG_AUTH_WRITE_URI_PERMISSION)) == 0) { + HILOG_WARN("UriPermissionManagerStubImpl:::VerifyUriPermission: The param flag is invalid."); + return false; + } + unsigned int tmpFlag = 0; + if (flag & Want::FLAG_AUTH_WRITE_URI_PERMISSION) { + tmpFlag |= Want::FLAG_AUTH_WRITE_URI_PERMISSION; + } + if (flag & Want::FLAG_AUTH_READ_URI_PERMISSION) { + tmpFlag |= Want::FLAG_AUTH_READ_URI_PERMISSION; + } + auto uriStr = uri.ToString(); + auto search = uriMap_.find(uriStr); + if (search == uriMap_.end()) { + HILOG_DEBUG("This tokenID does not have permission for this uri."); + return false; + } + for (auto item : search->second) { + if (item.targetTokenId == tokenId && + (item.flag == Want::FLAG_AUTH_WRITE_URI_PERMISSION || item.flag == tmpFlag)) { + HILOG_DEBUG("This tokenID have permission for this uri."); + return true; + } + } + HILOG_DEBUG("The application does not have permission for this URI."); + return false; +} + +void UriPermissionManagerStubImpl::RemoveUriPermission(const Security::AccessToken::AccessTokenID tokenId) +{ + for (auto iter = uriMap_.begin(); iter != uriMap_.end();) { + auto list = iter->second; + for (auto it = list.begin(); it != list.end();) { + if (it->targetTokenId == tokenId) { + HILOG_INFO("Erase an info form list."); + list.erase(it++); + break; + } + } + if (list.size() == 0) { + uriMap_.erase(iter++); + } + } +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/uripermmgr/upms.cfg b/services/uripermmgr/upms.cfg new file mode 100644 index 0000000000000000000000000000000000000000..3a8eb56789d429fb94ee3286b660a85844258b45 --- /dev/null +++ b/services/uripermmgr/upms.cfg @@ -0,0 +1,16 @@ +{ + "jobs" : [{ + "name" : "post-fs-data", + "cmds" : [ + "start upms" + ] + } + ], + "services" : [{ + "name" : "upms", + "path" : ["/system/bin/sa_main", "/system/profile/upms.xml"], + "uid" : "system", + "gid" : ["system", "shell"] + } + ] +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/BUILD.gn index 4223d110212f9225ea6390aa1f0f340c98d3fa2c..f59a1918eae86de0b6be28dd629a1fd06b8c3cbd 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/BUILD.gn @@ -45,10 +45,10 @@ ohos_shared_library("amsAbilityVisibleTestPageA") { ] configs = [ ":amsAbilityVisibleTestPageAConfig" ] deps = [ - "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", "//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", + "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/interfaces/innerkits/want:want", diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea2.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea2.h index 488d0ff67d07e528eeecb412eba09dc2e00c95ce..1ce71962a77627c11ffa7729e07917fc7482335c 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea2.h +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea2.h @@ -31,7 +31,7 @@ namespace OHOS { namespace AppExecFwk { using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; using Uri = OHOS::Uri; -using namespace OHOS::Notification::WantAgent; +using namespace OHOS::AbilityRuntime::WantAgent; class AbilityConnectCallback : public AbilityConnectionStub { public: diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/BUILD.gn index 93d3c6355624ac1dc241c2f2307863625f02521f..405131df621bb06868c40b2e0cd68e12c5f54bd2 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/BUILD.gn @@ -45,10 +45,10 @@ ohos_shared_library("amsAbilityVisibleTestServiceB") { ] configs = [ ":amsAbilityVisibleTestServiceBConfig" ] deps = [ - "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", "//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", + "//foundation/aafwk/standard/frameworks/kits/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", "//foundation/aafwk/standard/interfaces/innerkits/want:want", diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestpageb2.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestpageb2.h index f22426fc5f3c1ebc16bd2957006b4624d37177f9..9ff13302d83a8e304cba9be12b7ff01d544d437c 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestpageb2.h +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestpageb2.h @@ -32,8 +32,8 @@ namespace OHOS { namespace AppExecFwk { using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; using Uri = OHOS::Uri; -using CompletedCallback = OHOS::Notification::WantAgent::CompletedCallback; -using namespace OHOS::Notification::WantAgent; +using CompletedCallback = OHOS::AbilityRuntime::WantAgent::CompletedCallback; +using namespace OHOS::WantAgent; class AbilityConnectCallback : public AbilityConnectionStub { public: diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/BUILD.gn index 8cb0e5d88070dd4885a92e039c4ad352751d4ac9..010aeffdfbce5422d07cb4add045b615e2af857a 100644 --- a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/BUILD.gn @@ -42,9 +42,9 @@ ohos_shared_library("serviceAbilityA") { "//foundation/appexecfwk/standard/common:libappexecfwk_common", ] external_deps = [ + "ability_base:want", "ability_runtime:ability_manager", "ability_runtime:app_manager", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "hiviewdfx_hilog_native:libhilog", diff --git a/test/resource/formsystemtestability/fmsSystemTestHostCommonA/BUILD.gn b/test/resource/formsystemtestability/fmsSystemTestHostCommonA/BUILD.gn index 377c03097d8eafefc412938a10c3ba1c3970f48c..1a23fa2617e267d42550dc4586605146d72ebaaf 100644 --- a/test/resource/formsystemtestability/fmsSystemTestHostCommonA/BUILD.gn +++ b/test/resource/formsystemtestability/fmsSystemTestHostCommonA/BUILD.gn @@ -65,9 +65,9 @@ ohos_shared_library("fmsSystemTestHostCommonA") { "//utils/native/base:utilsbase", ] external_deps = [ + "ability_base:base", + "ability_base:want", "ability_runtime:app_manager", - "ability_runtime:base", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", diff --git a/test/resource/formsystemtestability/fmsSystemTestHostCommonB/BUILD.gn b/test/resource/formsystemtestability/fmsSystemTestHostCommonB/BUILD.gn index 4c105ec8a2370c521e7165ddaebbba161f6ad2e2..f134680e577305b376e4c0a9cc7253bc69d2d8f2 100644 --- a/test/resource/formsystemtestability/fmsSystemTestHostCommonB/BUILD.gn +++ b/test/resource/formsystemtestability/fmsSystemTestHostCommonB/BUILD.gn @@ -65,9 +65,9 @@ ohos_shared_library("fmsSystemTestHostCommonB") { "//utils/native/base:utilsbase", ] external_deps = [ + "ability_base:base", + "ability_base:want", "ability_runtime:app_manager", - "ability_runtime:base", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormal/BUILD.gn b/test/resource/formsystemtestability/fmsSystemTestHostNormal/BUILD.gn index cc66a9564179b857bff0bc8726830559877ee22a..e6157f54ca85305fbb4baa38939ac2e721f279bd 100755 --- a/test/resource/formsystemtestability/fmsSystemTestHostNormal/BUILD.gn +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormal/BUILD.gn @@ -67,9 +67,9 @@ ohos_shared_library("fmsSystemTestHostNormal") { "//utils/native/base:utilsbase", ] external_deps = [ + "ability_base:base", + "ability_base:want", "ability_runtime:app_manager", - "ability_runtime:base", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormalB/BUILD.gn b/test/resource/formsystemtestability/fmsSystemTestHostNormalB/BUILD.gn index 91ecd814dfaf231fca5344d269aa68e33fd8496a..6cf4481907f5361fa2f62fa67753e01f50de5726 100755 --- a/test/resource/formsystemtestability/fmsSystemTestHostNormalB/BUILD.gn +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormalB/BUILD.gn @@ -65,9 +65,9 @@ ohos_shared_library("fmsSystemTestHostNormalB") { "//utils/native/base:utilsbase", ] external_deps = [ + "ability_base:base", + "ability_base:want", "ability_runtime:app_manager", - "ability_runtime:base", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormalC/BUILD.gn b/test/resource/formsystemtestability/fmsSystemTestHostNormalC/BUILD.gn index c19ced112dc1f02bccb7e7a354b770294b846bfa..294b9b9fce23df72f04ad435be7adfb99b285f1f 100755 --- a/test/resource/formsystemtestability/fmsSystemTestHostNormalC/BUILD.gn +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormalC/BUILD.gn @@ -65,9 +65,9 @@ ohos_shared_library("fmsSystemTestHostNormalC") { "//utils/native/base:utilsbase", ] external_deps = [ + "ability_base:base", + "ability_base:want", "ability_runtime:app_manager", - "ability_runtime:base", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", diff --git a/test/systemtest/common/fms/fms_acquire_form_test/BUILD.gn b/test/systemtest/common/fms/fms_acquire_form_test/BUILD.gn index 24a3f045b536ad28894ae36a27656cec0ab2adac..7391847ab9ce692e4c635c4bc8bb55b8abae6fbb 100644 --- a/test/systemtest/common/fms/fms_acquire_form_test/BUILD.gn +++ b/test/systemtest/common/fms/fms_acquire_form_test/BUILD.gn @@ -53,9 +53,9 @@ ohos_systemtest("FmsAcquireFormTest") { defines = [ "APP_LOG_TAG = \"FMSAcquireFormTest\"" ] external_deps = [ + "ability_base:base", + "ability_base:want", "ability_runtime:app_manager", - "ability_runtime:base", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", diff --git a/test/systemtest/common/fms/fms_acquire_form_test_max/BUILD.gn b/test/systemtest/common/fms/fms_acquire_form_test_max/BUILD.gn index d84cbfb4cd58a3cbd21430316344bfa8c138d3ab..d29328ea20b5a5d5703522c300d13991a2a7f97b 100644 --- a/test/systemtest/common/fms/fms_acquire_form_test_max/BUILD.gn +++ b/test/systemtest/common/fms/fms_acquire_form_test_max/BUILD.gn @@ -53,9 +53,9 @@ ohos_systemtest("FmsAcquireFormTestMax") { defines = [ "APP_LOG_TAG = \"FMSAcquireFormTestMax\"" ] external_deps = [ + "ability_base:base", + "ability_base:want", "ability_runtime:app_manager", - "ability_runtime:base", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", diff --git a/test/systemtest/common/fms/fms_delete_form_test/BUILD.gn b/test/systemtest/common/fms/fms_delete_form_test/BUILD.gn index 17cffb293de605abdf451b6b668e7561a53e0e2d..a4add6d37f6e20875d5274afa8e162505a0b65e6 100644 --- a/test/systemtest/common/fms/fms_delete_form_test/BUILD.gn +++ b/test/systemtest/common/fms/fms_delete_form_test/BUILD.gn @@ -53,9 +53,9 @@ ohos_systemtest("FormDeleteFormTest") { defines = [ "APP_LOG_TAG = \"FMSDeleteFormTest\"" ] external_deps = [ + "ability_base:base", + "ability_base:want", "ability_runtime:app_manager", - "ability_runtime:base", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", diff --git a/test/systemtest/common/fms/fms_fuzz_test/BUILD.gn b/test/systemtest/common/fms/fms_fuzz_test/BUILD.gn index e381fe1e5ed021a3f49288ca0d59069b3a28b841..74d95b2ff48c14ef4f11135edfd5a7749c8fd21d 100755 --- a/test/systemtest/common/fms/fms_fuzz_test/BUILD.gn +++ b/test/systemtest/common/fms/fms_fuzz_test/BUILD.gn @@ -53,9 +53,9 @@ ohos_systemtest("fmsFuzzTest") { defines = [ "APP_LOG_TAG = \"fmsFuzzTest\"" ] external_deps = [ + "ability_base:base", + "ability_base:want", "ability_runtime:app_manager", - "ability_runtime:base", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", diff --git a/test/systemtest/common/fms/fms_performance_test/BUILD.gn b/test/systemtest/common/fms/fms_performance_test/BUILD.gn index 667112559ec2286edb4ef11d7622e858c06a24e3..762b962fe34c7637f17c8cc7c7edeb8bcace3299 100755 --- a/test/systemtest/common/fms/fms_performance_test/BUILD.gn +++ b/test/systemtest/common/fms/fms_performance_test/BUILD.gn @@ -53,9 +53,9 @@ ohos_systemtest("FmsPerformanceTest") { defines = [ "APP_LOG_TAG = \"FmsPerformanceTest\"" ] external_deps = [ + "ability_base:base", + "ability_base:want", "ability_runtime:app_manager", - "ability_runtime:base", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", diff --git a/test/systemtest/common/fms/fms_release_form_test/BUILD.gn b/test/systemtest/common/fms/fms_release_form_test/BUILD.gn index 47b1c1d1d35a27860e4098da77b58c12ebbc2bde..55a314dfcce118c5c9b682dfc86f11e9dea85292 100644 --- a/test/systemtest/common/fms/fms_release_form_test/BUILD.gn +++ b/test/systemtest/common/fms/fms_release_form_test/BUILD.gn @@ -53,9 +53,9 @@ ohos_systemtest("FormReleaseFormTest") { defines = [ "APP_LOG_TAG = \"FMSReleaseFormTest\"" ] external_deps = [ + "ability_base:base", + "ability_base:want", "ability_runtime:app_manager", - "ability_runtime:base", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", diff --git a/test/systemtest/common/fms/fms_self_starting_test/BUILD.gn b/test/systemtest/common/fms/fms_self_starting_test/BUILD.gn index 11d47f57178bf93bdd1e5ea7cd00db66a2c85ee8..00cf9ca81e4bffebc33619842c1ae9666a0af83d 100644 --- a/test/systemtest/common/fms/fms_self_starting_test/BUILD.gn +++ b/test/systemtest/common/fms/fms_self_starting_test/BUILD.gn @@ -59,9 +59,9 @@ ohos_systemtest("FmsSelfStartingTest") { defines = [ "APP_LOG_TAG = \"FmsSelfStartingTest\"" ] external_deps = [ + "ability_base:base", + "ability_base:want", "ability_runtime:app_manager", - "ability_runtime:base", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", diff --git a/test/systemtest/common/fms/fms_stress_test/BUILD.gn b/test/systemtest/common/fms/fms_stress_test/BUILD.gn index 914278dbcc01cff510707a027d8ee806717d15b3..09f0b2836ce251199e7634ec610286ba68feeb3f 100755 --- a/test/systemtest/common/fms/fms_stress_test/BUILD.gn +++ b/test/systemtest/common/fms/fms_stress_test/BUILD.gn @@ -53,9 +53,9 @@ ohos_systemtest("FmsStressTest") { defines = [ "APP_LOG_TAG = \"FmsStressTest\"" ] external_deps = [ + "ability_base:base", + "ability_base:want", "ability_runtime:app_manager", - "ability_runtime:base", - "ability_runtime:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", diff --git a/tools/aa/BUILD.gn b/tools/aa/BUILD.gn index 625017bad2571aab4e61fa5bfd9deb25533a9cec..7b55a42e6b0b2cf5877cef4a7b9cad4c65bd6216 100644 --- a/tools/aa/BUILD.gn +++ b/tools/aa/BUILD.gn @@ -19,7 +19,9 @@ config("ability_command_config") { "include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", - "//utils/system/safwk/native/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//third_party/jsoncpp/include", ] } @@ -73,12 +75,7 @@ ohos_executable("aa") { cflags += [ "-DBINDER_IPC_32BIT" ] } - deps = [ - ":tools_aa_source_set", - "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", - "${innerkits_path}/want:want", - "//utils/native/base:utils", - ] + deps = [ ":tools_aa_source_set" ] external_deps = [ "hiviewdfx_hilog_native:libhilog", diff --git a/tools/aa/include/ability_command.h b/tools/aa/include/ability_command.h index 7fde0445cb463dfeefefb6c3b22aa05532653ed5..7f0750469556d7d34fa2784f9bddbe9b61568dca 100644 --- a/tools/aa/include/ability_command.h +++ b/tools/aa/include/ability_command.h @@ -29,10 +29,10 @@ const std::string HELP_MSG = "usage: aa \n" " help list available commands\n" " start start ability with options\n" " stop-service stop service with options\n" - " dump dump the ability stack info\n" - " dumpsys dump the ability info\n" + " dump dump the ability info\n" " force-stop force stop the process with bundle name\n" - " test start the test framework with options\n"; + " test start the test framework with options\n" + " ApplicationNotRespondin Pass in pid with options\n"; const std::string HELP_MSG_SCREEN = "usage: aa screen \n" @@ -40,6 +40,12 @@ const std::string HELP_MSG_SCREEN = " -h, --help list available commands\n" " -p, --power power on or off with a state name\n"; +const std::string HELP_ApplicationNotRespondin = + "usage: aa ApplicationNotRespondin \n" + "options list:\n" + " -h, --help list available commands\n" + " -p, --pid Pass in pid with option\n"; + const std::string HELP_MSG_START = "usage: aa start \n" "options list:\n" @@ -63,24 +69,31 @@ const std::string HELP_MSG_DUMP = "usage: aa dump \n" " -e, --serv dump the service abilities\n" " -d, --data dump the data abilities\n"; -const std::string HELP_MSG_DUMPSYS = "usage: aa dumpsys \n" +const std::string HELP_MSG_DUMPSYS = "usage: aa dump \n" "options list:\n" " -h, --help list available commands\n" " -a, --all dump all abilities\n" " -l, --mission-list dump mission list\n" " -i, --ability dump abilityRecordId\n" - " -e, --extension dump elementName\n" + " -e, --extension dump elementName (API7 ExtensionRecords," + "API8 serviceAbilityRecords)\n" " -p, --pending dump pendingWantRecordId\n" " -r, --process dump process\n" + " -d, --data dump the data abilities\n" + " -k, --ui dump the kenarl ability list ui stack\n" " -u, --userId userId\n" - " -c, --client client\n"; + " -c, --client client\n" + " -c, -u are auxiliary parameters and cannot be used alone\n" + " The original -s parameter is invalid\n" + " The original -m parameter is invalid\n"; + const std::string HELP_MSG_TEST = "usage: aa test \n" "options list:\n" " -h, --help \ list available commands\n" - " -p -s unittest -s class [-w ] \ + " -p -s unittest [-s class ] [-w ] \ start the test framework with options\n"; const std::string HELP_MSG_FORCE_STOP = "usage: aa force-stop \n"; @@ -130,11 +143,11 @@ private: ErrCode RunAsDumpCommand(); ErrCode RunAsDumpsysCommand(); ErrCode RunAsForceStop(); + ErrCode RunAsSendAppNotRespondinProcessID(); + sptr GetAbilityManagerService(); ErrCode RunAsDumpCommandOptopt(); ErrCode MakeWantFromCmd(Want &want, std::string &windowMode); - ErrCode RunAsDumpSysCommandOptopt(); - ErrCode RunAsTestCommand(); bool IsTestCommandIntegrity(const std::map ¶ms); ErrCode TestCommandError(const std::string &info); diff --git a/tools/aa/src/ability_command.cpp b/tools/aa/src/ability_command.cpp index b08e0b38bef21056a1499384e31421e655fbc544..6cae6b34f6a159367113f045ca418685b97fa6de 100644 --- a/tools/aa/src/ability_command.cpp +++ b/tools/aa/src/ability_command.cpp @@ -12,14 +12,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "ability_command.h" +#include #include #include "ability_manager_client.h" -#include "mission_snapshot.h" #include "hilog_wrapper.h" +#include "iservice_registry.h" +#include "mission_snapshot.h" #include "ohos/aafwk/base/bool_wrapper.h" +#include "sa_mgr_client.h" +#include "system_ability_definition.h" #include "test_observer.h" using namespace OHOS::AppExecFwk; @@ -38,7 +41,12 @@ const struct option LONG_OPTIONS[] = { {"debug", no_argument, nullptr, 'D'}, {nullptr, 0, nullptr, 0}, }; - +const std::string SHORT_OPTIONS_ApplicationNotRespondin = "hp:"; +const struct option LONG_OPTIONS_ApplicationNotRespondin[] = { + {"help", no_argument, nullptr, 'h'}, + {"pid", required_argument, nullptr, 'p'}, + {nullptr, 0, nullptr, 0}, +}; const std::string SHORT_OPTIONS_DUMP = "has:m:lud::e::LS"; const struct option LONG_OPTIONS_DUMP[] = { {"help", no_argument, nullptr, 'h'}, @@ -53,7 +61,7 @@ const struct option LONG_OPTIONS_DUMP[] = { {"mission-infos", no_argument, nullptr, 'S'}, {nullptr, 0, nullptr, 0}, }; -const std::string SHORT_OPTIONS_DUMPSYS = "hal::i:e::p::r::u:c"; +const std::string SHORT_OPTIONS_DUMPSYS = "hal::i:e::p::r::kd::u:c"; const struct option LONG_OPTIONS_DUMPSYS[] = { {"help", no_argument, nullptr, 'h'}, {"all", no_argument, nullptr, 'a'}, @@ -62,6 +70,8 @@ const struct option LONG_OPTIONS_DUMPSYS[] = { {"extension", no_argument, nullptr, 'e'}, {"pending", no_argument, nullptr, 'p'}, {"process", no_argument, nullptr, 'r'}, + {"data", no_argument, nullptr, 'd'}, + {"ui", no_argument, nullptr, 'k'}, {"userId", required_argument, nullptr, 'u'}, {"client", no_argument, nullptr, 'c'}, {nullptr, 0, nullptr, 0}, @@ -82,10 +92,10 @@ ErrCode AbilityManagerShellCommand::CreateCommandMap() {"screen", std::bind(&AbilityManagerShellCommand::RunAsScreenCommand, this)}, {"start", std::bind(&AbilityManagerShellCommand::RunAsStartAbility, this)}, {"stop-service", std::bind(&AbilityManagerShellCommand::RunAsStopService, this)}, - {"dump", std::bind(&AbilityManagerShellCommand::RunAsDumpCommand, this)}, - {"dumpsys", std::bind(&AbilityManagerShellCommand::RunAsDumpsysCommand, this)}, + {"dump", std::bind(&AbilityManagerShellCommand::RunAsDumpsysCommand, this)}, {"force-stop", std::bind(&AbilityManagerShellCommand::RunAsForceStop, this)}, {"test", std::bind(&AbilityManagerShellCommand::RunAsTestCommand, this)}, + {"ApplicationNotRespondin", std::bind(&AbilityManagerShellCommand::RunAsSendAppNotRespondinProcessID, this)}, }; return OHOS::ERR_OK; @@ -556,8 +566,8 @@ ErrCode AbilityManagerShellCommand::RunAsDumpsysCommand() bool isfirstCommand = false; std::string args; - for (size_t i = 0; i < argList_.size(); i++) { - if (argList_[i] == "-c" || argList_[i] == "--client") { + for (auto it = argList_.begin(); it != argList_.end(); it++) { + if (*it == "-c" || *it == "--client") { if (isClient == false) { isClient = true; } else { @@ -565,9 +575,13 @@ ErrCode AbilityManagerShellCommand::RunAsDumpsysCommand() resultReceiver_.append(HELP_MSG_DUMPSYS); return result; } - - } else if (argList_[i] == "-u" || argList_[i] == "--userId") { - (void)StrToInt(argList_[i + 1], userID); + } else if (*it == "-u" || *it == "--userId") { + if (it + 1 == argList_.end()) { + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; + } + (void)StrToInt(*(it + 1), userID); if (userID == DEFAULT_INVAL_VALUE) { result = OHOS::ERR_INVALID_VALUE; resultReceiver_.append(HELP_MSG_DUMPSYS); @@ -580,11 +594,10 @@ ErrCode AbilityManagerShellCommand::RunAsDumpsysCommand() resultReceiver_.append(HELP_MSG_DUMPSYS); return result; } - - } else if (argList_[i] == std::to_string(userID)) { + } else if (*it == std::to_string(userID)) { continue; } else { - args += argList_[i]; + args += *it; args += " "; } } @@ -626,12 +639,16 @@ ErrCode AbilityManagerShellCommand::RunAsDumpsysCommand() break; } case 'l': { - if (isfirstCommand == false) { + if (isfirstCommand == false && optarg == nullptr) { isfirstCommand = true; } else { - result = OHOS::ERR_INVALID_VALUE; - resultReceiver_.append(HELP_MSG_DUMPSYS); - return result; + // 'aa dumpsys -i 10 -element -lastpage' + // 'aa dumpsys -i 10 -render -lastpage' + if (strcmp(optarg, "astpage")) { + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; + } } // 'aa dumpsys -l' // 'aa dumpsys --mission-list' @@ -648,28 +665,34 @@ ErrCode AbilityManagerShellCommand::RunAsDumpsysCommand() return result; } } else { - result = OHOS::ERR_INVALID_VALUE; - resultReceiver_.append(HELP_MSG_DUMPSYS); - return result; + // 'aa dumpsys -i 10 -inspector' + if (strcmp(optarg, "nspector")) { + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; + } } // 'aa dumpsys -i' // 'aa dumpsys --ability' break; } case 'e': { - if (isfirstCommand == false) { + if (isfirstCommand == false && optarg == nullptr) { isfirstCommand = true; } else { - result = OHOS::ERR_INVALID_VALUE; - resultReceiver_.append(HELP_MSG_DUMPSYS); - return result; + // 'aa dumpsys -i 10 -element' + if (strcmp(optarg, "lement")) { + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; + } } // 'aa dumpsys -e' // 'aa dumpsys --extension' break; } case 'p': { - if (isfirstCommand == false) { + if (isfirstCommand == false && optarg == nullptr) { isfirstCommand = true; } else { result = OHOS::ERR_INVALID_VALUE; @@ -681,15 +704,48 @@ ErrCode AbilityManagerShellCommand::RunAsDumpsysCommand() break; } case 'r': { + if (isfirstCommand == false && optarg == nullptr) { + isfirstCommand = true; + } else { + // 'aa dumpsys -i 10 -render' + if (strcmp(optarg, "ender")) { + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; + } + } + // 'aa dumpsys -r' + // 'aa dumpsys --process' + break; + } + case 'd': { + if (isfirstCommand == false && optarg == nullptr) { + isfirstCommand = true; + } else { + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; + } + // 'aa dumpsys -d' + // 'aa dumpsys --data' + break; + } + case 'k': { if (isfirstCommand == false) { isfirstCommand = true; + if (isUserID == true) { + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append("-k is no userID option\n"); + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; + } } else { result = OHOS::ERR_INVALID_VALUE; resultReceiver_.append(HELP_MSG_DUMPSYS); return result; } - // 'aa dumpsys -r' - // 'aa dumpsys --process' + // 'aa dumpsys -k' + // 'aa dumpsys --UI' break; } case 'u': { @@ -727,6 +783,7 @@ ErrCode AbilityManagerShellCommand::RunAsDumpsysCommand() } else { if (isfirstCommand != true) { result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_NO_OPTION); resultReceiver_.append(HELP_MSG_DUMPSYS); return result; } @@ -1187,7 +1244,7 @@ bool AbilityManagerShellCommand::IsTestCommandIntegrity(const std::map opts = {"-p", "-s unittest", "-s class"}; + std::vector opts = {"-p", "-s unittest"}; for (auto opt : opts) { auto it = params.find(opt); if (it == params.end()) { @@ -1242,5 +1299,107 @@ ErrCode AbilityManagerShellCommand::StartUserTest(const std::map AbilityManagerShellCommand::GetAbilityManagerService() +{ + sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemManager == nullptr) { + HILOG_ERROR("Fail to get registry."); + return nullptr; + } + sptr remoteObject = systemManager->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + return iface_cast(remoteObject); +} + +ErrCode AbilityManagerShellCommand::RunAsSendAppNotRespondinProcessID() +{ + static sptr abilityMs_; + std::string pid = ""; + int option = -1; + ErrCode result = OHOS::ERR_OK; + option = getopt_long(argc_, argv_, SHORT_OPTIONS_ApplicationNotRespondin.c_str(), + LONG_OPTIONS_ApplicationNotRespondin, nullptr); + HILOG_INFO("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind); + if (optind < 0 || optind > argc_) { + return OHOS::ERR_INVALID_VALUE; + } + if (option == -1) { + if (strcmp(argv_[optind], cmd_.c_str()) == 0) { + HILOG_INFO("'aa %{public}s' %{public}s", HELP_ApplicationNotRespondin.c_str(), cmd_.c_str()); + result = OHOS::ERR_INVALID_VALUE; + } + } else if (option == '?') { + switch (optopt) { + case 'h': { + result = OHOS::ERR_INVALID_VALUE; + break; + } + case 'p': { + HILOG_INFO("'aa ApplicationNotRespondin -p' with no argument."); + resultReceiver_.append("error: option -p "); + resultReceiver_.append("' requires a value.\n"); + result = OHOS::ERR_INVALID_VALUE; + break; + } + case 0: { + std::string unknownOption = ""; + std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption); + + HILOG_INFO("'aa ApplicationNotRespondin' with an unknown option."); + + resultReceiver_.append(unknownOptionMsg); + result = OHOS::ERR_INVALID_VALUE; + break; + } + default: { + std::string unknownOption = ""; + std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption); + + HILOG_INFO("'aa ApplicationNotRespondin' with an unknown option."); + + resultReceiver_.append(unknownOptionMsg); + result = OHOS::ERR_INVALID_VALUE; + break; + } + } + } else { + switch (option) { + case 'h': { + result = OHOS::ERR_INVALID_VALUE; + break; + } + case 'p': { + HILOG_INFO("aa ApplicationNotRespondin 'aa %{public}s' -p process.", cmd_.c_str()); + HILOG_INFO("aa ApplicationNotRespondin 'aa optarg = %{public}s'.", optarg); + pid = optarg; + HILOG_INFO("aa ApplicationNotRespondinr 'aa pid = %{public}s'.", pid.c_str()); + break; + } + case 0: { + HILOG_INFO("'aa %{public}s' with an unknown option.", cmd_.c_str()); + result = OHOS::ERR_INVALID_VALUE; + break; + } + default: { + HILOG_INFO("'aa %{public}s' with an unknown option.", cmd_.c_str()); + result = OHOS::ERR_INVALID_VALUE; + break; + } + } + } + + if (result == OHOS::ERR_OK) { + HILOG_INFO("'aa pid = %{public}d'.", atoi(pid.c_str())); + abilityMs_ = GetAbilityManagerService(); + if (abilityMs_ == nullptr) { + std::cout << "abilityMsObj is nullptr"; + } + abilityMs_->SendANRProcessID(atoi(pid.c_str())); + } else { + resultReceiver_.append(HELP_ApplicationNotRespondin+ "\n"); + result = OHOS::ERR_INVALID_VALUE; + } + return result; +} } // namespace AAFwk } // namespace OHOS diff --git a/tools/aa/src/test_observer.cpp b/tools/aa/src/test_observer.cpp index 293d6043cd286a6edb1ec2f165b8a5258f4d8d31..ca04d058b4dfac83589a24ae604d1ebbf955fc46 100644 --- a/tools/aa/src/test_observer.cpp +++ b/tools/aa/src/test_observer.cpp @@ -34,15 +34,14 @@ TestObserver::~TestObserver() void TestObserver::TestStatus(const std::string &msg, const int &resultCode) { HILOG_INFO("enter"); - std::cout << "TestStatus-resultCode: " + std::to_string(resultCode) << std::endl; - std::cout << "TestStatus-resultMsg: " + msg << std::endl; + std::cout << msg << std::endl; } void TestObserver::TestFinished(const std::string &msg, const int &resultCode) { HILOG_INFO("enter"); - std::cout << "TestFinished-resultCode: " + std::to_string(resultCode) << std::endl; - std::cout << "TestFinished-resultMsg: " + msg << std::endl; + std::cout << "TestFinished-ResultCode: " + std::to_string(resultCode) << std::endl; + std::cout << "TestFinished-ResultMsg: " + msg << std::endl; isFinished_ = true; } diff --git a/tools/test/mock/mock_ability_manager_stub.h b/tools/test/mock/mock_ability_manager_stub.h index 15e4358bf46a0f67c01d226d8c625c77502db367..68c86d0e0d5cadc0b5646c327b82deef7d13b716 100644 --- a/tools/test/mock/mock_ability_manager_stub.h +++ b/tools/test/mock/mock_ability_manager_stub.h @@ -46,6 +46,11 @@ public: MOCK_METHOD4(StartAbility, int(const Want &want, const sptr &callerToken, int32_t userId, int requestCode)); MOCK_METHOD3(TerminateAbility, int(const sptr &token, int resultCode, const Want *resultWant)); + virtual int CloseAbility(const sptr &token, int resultCode = DEFAULT_INVAL_VALUE, + const Want *resultWant = nullptr) override + { + return 0; + } virtual int MinimizeAbility(const sptr &token, bool fromUser = false) override { return 0; @@ -119,7 +124,7 @@ public: MOCK_METHOD1(SetShowOnLockScreen, int(bool isAllow)); MOCK_METHOD1(GetSystemMemoryAttr, void(AppExecFwk::SystemMemoryAttr &memoryInfo)); MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); - MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result)); + MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, int32_t result)); MOCK_METHOD5(ContinueMission, int(const std::string &srcDeviceId, const std::string &dstDeviceId, int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams)); MOCK_METHOD2(ContinueAbility, int(const std::string &deviceId, int32_t missionId)); @@ -135,6 +140,7 @@ public: MOCK_METHOD1(CleanMission, int(int32_t missionId)); MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); + MOCK_METHOD2(MoveMissionToFront, int(int32_t missionId, const StartOptions &startOptions)); MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD1(ClearUpApplicationData, int(const std::string &)); @@ -201,9 +207,9 @@ public: { return 0; } - virtual bool SendANRProcessID(int pid) + virtual int SendANRProcessID(int pid) { - return true; + return 0; } virtual int SetAbilityController(const sptr &abilityController, bool imAStabilityTest) override diff --git a/zidl/test/native/include/zidl_test_service_proxy.h b/zidl/test/native/include/zidl_test_service_proxy.h index 7e9ea4dcd58315a03ba8a4c7f7125bb3214e14f4..56a6dcef68c68525aebcce630ac661f606776469 100644 --- a/zidl/test/native/include/zidl_test_service_proxy.h +++ b/zidl/test/native/include/zidl_test_service_proxy.h @@ -16,9 +16,10 @@ #ifndef OHOS_ZIDLTESTSERVICEPROXY_H #define OHOS_ZIDLTESTSERVICEPROXY_H -#include "izidl_test_service.h" #include +#include "izidl_test_service.h" + namespace OHOS { class ZidlTestServiceProxy : public IRemoteProxy { public: diff --git a/zidl/test/native/include/zidl_test_service_stub.h b/zidl/test/native/include/zidl_test_service_stub.h index d88b615bb1f380471cc91f3488de49b4e37a9ca4..eed5cd8875acf4f1e1e41479ca8c74b852c109e4 100644 --- a/zidl/test/native/include/zidl_test_service_stub.h +++ b/zidl/test/native/include/zidl_test_service_stub.h @@ -16,9 +16,10 @@ #ifndef OHOS_ZIDLTESTSERVICESTUB_H #define OHOS_ZIDLTESTSERVICESTUB_H -#include "izidl_test_service.h" #include +#include "izidl_test_service.h" + namespace OHOS { class ZidlTestServiceStub : public IRemoteStub { public: