diff --git a/frameworks/kits/ability/native/BUILD.gn b/frameworks/kits/ability/native/BUILD.gn index 28ceb9c922eb5e4b3af657d56382bc4496484a87..410226df7c72419afbc649d024b4af9a4fad0b83 100755 --- a/frameworks/kits/ability/native/BUILD.gn +++ b/frameworks/kits/ability/native/BUILD.gn @@ -42,6 +42,7 @@ config("ability_config") { "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/include/task", "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/include/threading", "//foundation/appexecfwk/standard/kits/appkit/native/app/include/task", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common", ] cflags = [] @@ -64,6 +65,7 @@ config("ability_public_config") { "//foundation/aafwk/standard/interfaces/innerkits/base/include/ohos/aafwk/base", "//base/global/resmgr_standard/interfaces/innerkits/include", "//foundation/multimodalinput/input/interfaces/native/innerkits/event/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include/continuation/kits", ] } @@ -84,15 +86,20 @@ ohos_shared_library("abilitykit_native") { "${SUBSYSTEM_DIR}/src/ability_window.cpp", "${SUBSYSTEM_DIR}/src/data_ability_helper.cpp", "${SUBSYSTEM_DIR}/src/data_ability_impl.cpp", + "${SUBSYSTEM_DIR}/src/data_ability_operation.cpp", + "${SUBSYSTEM_DIR}/src/data_ability_operation_builder.cpp", + "${SUBSYSTEM_DIR}/src/data_ability_result.cpp", "${SUBSYSTEM_DIR}/src/data_uri_utils.cpp", "${SUBSYSTEM_DIR}/src/dummy_data_ability_predicates.cpp", "${SUBSYSTEM_DIR}/src/dummy_values_bucket.cpp", + "${SUBSYSTEM_DIR}/src/mission_information.cpp", "${SUBSYSTEM_DIR}/src/page_ability_impl.cpp", "${SUBSYSTEM_DIR}/src/service_ability_impl.cpp", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/want_wrapper.cpp", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.cpp", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.cpp", "//foundation/appexecfwk/standard/kits/appkit/native/app/src/ability_start_setting.cpp", "//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp", "//foundation/appexecfwk/standard/kits/appkit/native/app/src/context_container.cpp", diff --git a/frameworks/kits/ability/native/include/ability_context.h b/frameworks/kits/ability/native/include/ability_context.h index 9123f82f1b86c4b984fdc3e345eb9b03d3e8f313..dbabf9976952a48e5e4c4190f6c04a4c8cdca61b 100755 --- a/frameworks/kits/ability/native/include/ability_context.h +++ b/frameworks/kits/ability/native/include/ability_context.h @@ -656,6 +656,34 @@ public: */ std::shared_ptr GetGlobalTaskDispatcher(const TaskPriority &priority) override; + /** + * @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 MoveMissionToEnd(bool nonFirst) override; + + /** + * @brief Sets the application to start its ability in lock mission mode. + */ + void LockMission() override; + + /** + * @brief Unlocks this ability by exiting the lock mission mode. + */ + void UnlockMission() override; + + /** + * @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 SetMissionInformation(const MissionInformation &missionInformation) override; + friend DataAbilityHelper; public: diff --git a/frameworks/kits/ability/native/include/ability_thread.h b/frameworks/kits/ability/native/include/ability_thread.h index 4bcd53d5be1189f7824c51fcbf537d721845e0b0..8499c9442d422c3df73b5a409b0c9d1ec6d21c88 100644 --- a/frameworks/kits/ability/native/include/ability_thread.h +++ b/frameworks/kits/ability/native/include/ability_thread.h @@ -255,12 +255,6 @@ public: */ int BatchInsert(const Uri &uri, const std::vector &values); - /** - * @brief Displays a system-defined message to the user, prompting the user how to exit the lock mission mode. - * - */ - void DisplayUnlockMissionMessage(); - private: /** * @description: Create the abilityname. diff --git a/frameworks/kits/ability/native/include/continuation/kits/ability_continuation_interface.h b/frameworks/kits/ability/native/include/continuation/kits/ability_continuation_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..e7eba0bf2e95fba6f96b440933416891487c4327 --- /dev/null +++ b/frameworks/kits/ability/native/include/continuation/kits/ability_continuation_interface.h @@ -0,0 +1,40 @@ +/* + * 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_CONTINUATION_INTERFACE_H +#define FOUNDATION_APPEXECFWK_OHOS_ABILITY_CONTINUATION_INTERFACE_H + +#include "want_params.h" + +namespace OHOS { +namespace AppExecFwk { +class IAbilityContinuation { +public: + IAbilityContinuation() = default; + virtual ~IAbilityContinuation() = default; + + virtual bool OnStartContinuation() = 0; + + virtual bool OnSaveData(WantParams &saveData) = 0; + + virtual bool OnRestoreData(WantParams &restoreData) = 0; + + virtual void OnCompleteContinuation(int result) = 0; + + virtual void OnRemoteTerminated() = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_CONTINUATION_INTERFACE_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/data_ability_operation.h b/frameworks/kits/ability/native/include/data_ability_operation.h new file mode 100644 index 0000000000000000000000000000000000000000..9e40ee023286c17633bf40b3498ccad422b0fa31 --- /dev/null +++ b/frameworks/kits/ability/native/include/data_ability_operation.h @@ -0,0 +1,166 @@ +/* + * 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_DATA_ABILITY_OPERATION_H +#define FOUNDATION_APPEXECFWK_OHOS_DATA_ABILITY_OPERATION_H + +#include +#include +#include "dummy_data_ability_predicates.h" +#include "dummy_values_bucket.h" +#include "data_ability_operation_builder.h" +#include "uri.h" +#include "parcel.h" + +using Uri = OHOS::Uri; + +namespace OHOS { +namespace AppExecFwk { +class DataAbilityOperationBuilder; +class DataAbilityOperation final : public std::enable_shared_from_this { +public: + ~DataAbilityOperation(); + + DataAbilityOperation( + const std::shared_ptr &dataAbilityOperation, const std::shared_ptr &withUri); + DataAbilityOperation(Parcel &in); + DataAbilityOperation(const std::shared_ptr &builder); + DataAbilityOperation(); + /** + * @brief Creates an operation for inserting data. + * @param uri Indicates the path of data to operate. + * @return Returns an insert DataAbilityOperationBuilder object. + */ + static std::shared_ptr NewInsertBuilder(const std::shared_ptr &uri); + /** + * @brief Creates an operation for updating data. + * @param uri Indicates the path of data to operate. + * @return Returns an update DataAbilityOperationBuilder object. + */ + static std::shared_ptr NewUpdateBuilder(const std::shared_ptr &uri); + /** + * @brief Creates an operation for deleting data. + * @param uri Indicates the path of data to operate. + * @return Returns an delete DataAbilityOperationBuilder object. + */ + static std::shared_ptr NewDeleteBuilder(const std::shared_ptr &uri); + /** + * @brief Creates an operation for asserting data. + * @param uri Indicates the path of data to operate. + * @return Returns an assert DataAbilityOperationBuilder object. + */ + static std::shared_ptr NewAssertBuilder(const std::shared_ptr &uri); + /** + * @brief Obtains the value of the type attribute included in this DataAbilityOperation. + * @return Returns the type included in this DataAbilityOperation. + */ + int GetType() const; + /** + * @brief Obtains the value of the uri attribute included in this DataAbilityOperation. + * @return Returns the uri included in this DataAbilityOperation. + */ + std::shared_ptr GetUri() const; + /** + * @brief Obtains the value of the valuesBucket attribute included in this DataAbilityOperation. + * @return Returns the valuesBucket included in this DataAbilityOperation. + */ + std::shared_ptr GetValuesBucket() const; + /** + * @brief Obtains the value of the expectedCount attribute included in this DataAbilityOperation. + * @return Returns the expectedCount included in this DataAbilityOperation. + */ + int GetExpectedCount() const; + /** + * @brief Obtains the value of the dataAbilityPredicates attribute included in this DataAbilityOperation. + * @return Returns the dataAbilityPredicates included in this DataAbilityOperation. + */ + std::shared_ptr GetDataAbilityPredicates() const; + /** + * @brief Obtains the value of the valuesBucketReferences attribute included in this DataAbilityOperation. + * @return Returns the valuesBucketReferences included in this DataAbilityOperation. + */ + std::shared_ptr GetValuesBucketReferences() const; + /** + * @brief Obtains the value of the dataAbilityPredicatesBackReferences attribute included in this + * DataAbilityOperation. + * @return Returns the dataAbilityPredicatesBackReferences included in this DataAbilityOperation. + */ + std::map GetDataAbilityPredicatesBackReferences() const; + /** + * @brief Checks whether an insert operation is created. + * @return Returns true if it is an insert operation; returns false otherwise. + */ + bool IsInsertOperation() const; + /** + * @brief Checks whether an delete operation is created. + * @return Returns true if it is an delete operation; returns false otherwise. + */ + bool IsDeleteOperation() const; + /** + * @brief Checks whether an update operation is created. + * @return Returns true if it is an update operation; returns false otherwise. + */ + bool IsUpdateOperation() const; + /** + * @brief Checks whether an assert operation is created. + * @return Returns true if it is an assert operation; returns false otherwise. + */ + bool IsAssertOperation() const; + /** + * @brief Checks whether an operation can be interrupted. + * @return Returns true if the operation can be interrupted; returns false otherwise. + */ + bool IsInterruptionAllowed() const; + + bool operator==(const DataAbilityOperation &other) const; + DataAbilityOperation &operator=(const DataAbilityOperation &other); + bool Marshalling(Parcel &out) const; + static DataAbilityOperation *Unmarshalling(Parcel &in); + + /** + * @brief Creates a DataAbilityOperation instance based on the given Parcel object + * @param in Indicates the Parcel object. + * @return Returns the DataAbilityOperation object. + */ + static std::shared_ptr CreateFromParcel(Parcel &in); + +public: + static constexpr int TYPE_INSERT = 1; + static constexpr int TYPE_UPDATE = 2; + static constexpr int TYPE_DELETE = 3; + static constexpr int TYPE_ASSERT = 4; + +private: + void PutMap(Parcel &in); + bool ReadFromParcel(Parcel &in); + +private: + // no object in parcel + static constexpr int VALUE_NULL = 0; + // object exist in parcel + static constexpr int VALUE_OBJECT = 1; + static constexpr int REFERENCE_THRESHOLD = 3 * 1024 * 1024; + int type_; + int expectedCount_; + bool interrupted_; + std::shared_ptr uri_; + std::shared_ptr valuesBucket_; + std::shared_ptr dataAbilityPredicates_; + std::shared_ptr valuesBucketReferences_; + std::map dataAbilityPredicatesBackReferences_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_DATA_ABILITY_OPERATION_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/data_ability_operation_builder.h b/frameworks/kits/ability/native/include/data_ability_operation_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..31d27c7eb8dd3d8a87122754e26c430a7c69d029 --- /dev/null +++ b/frameworks/kits/ability/native/include/data_ability_operation_builder.h @@ -0,0 +1,98 @@ +/* + * 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_DATA_ABILITY_OPERATION_BUILDER_H +#define FOUNDATION_APPEXECFWK_OHOS_DATA_ABILITY_OPERATION_BUILDER_H + +#include +#include +#include "dummy_data_ability_predicates.h" +#include "dummy_values_bucket.h" +#include "data_ability_operation.h" +#include "uri.h" +#include "parcel.h" + +using Uri = OHOS::Uri; +namespace OHOS { +namespace AppExecFwk { +class DataAbilityOperation; +class DataAbilityOperationBuilder final : public std::enable_shared_from_this { + friend class DataAbilityOperation; + +public: + DataAbilityOperationBuilder(const int type, const std::shared_ptr &uri); + ~DataAbilityOperationBuilder(); + /** + * @brief Creates a DataAbilityOperation object. + * @return Returns the DataAbilityOperation object. + */ + std::shared_ptr Build(); + /** + * @brief Sets the data records to be inserted or updated. + * @param values Indicates the data values to be set. + * @return Returns a DataAbilityOperationBuilder object containing the given values parameter. + */ + std::shared_ptr WithValuesBucket(std::shared_ptr &values); + /** + * @brief Sets filter criteria used for deleting updating or assert query data. + * @param predicates Indicates the filter criteria to set. If this parameter is null, all data records will be + * operated by default. + * @return Returns an object containing the given filter criteria. + */ + std::shared_ptr WithPredicates(std::shared_ptr &predicates); + /** + * @brief Sets the expected number of rows to update ,delete or assert query. + * @param count Indicates the expected number of rows to update or delete. + * @return Returns a DataAbilityOperationBuilder object containing the given count parameter. + */ + std::shared_ptr WithExpectedCount(int count); + /** + * @brief Adds a back reference to be used as a filter criterion in withPredicates(DataAbilityPredicates). + * @param requestArgIndex Indicates the index referencing the predicate parameter whose value is to be replaced. + * @param previousResult Indicates the index referencing the historical DataAbilityResult used to replace the value + * of the specified predicate parameter. + * @return Returns a DataAbilityOperationBuilder object containing the given requestArgIndex and previousResult + * parameters. + */ + std::shared_ptr WithPredicatesBackReference(int requestArgIndex, int previousResult); + /** + * @brief Adds a back reference to be used in withValuesBucket(ValuesBucket). + * @param backReferences Indicates the ValuesBucket object containing a set of key-value pairs. In each pair, the + * key specifies the value to be updated and the value specifies the index referencing the DataAbilityResult used to + * replace the specified value. This parameter cannot be null. + * @return Returns a DataAbilityOperationBuilder object containing the given backReferences parameter. + */ + std::shared_ptr WithValueBackReferences(std::shared_ptr &backReferences); + /** + * @brief Sets an interrupt flag bit for a batch operation, which can be insert, update, delete, or assert. + * @param interrupted Specifies whether a batch operation can be interrupted. The value true indicates that the + * operation can be interrupted, and false indicates the opposite. + * @return Returns a DataAbilityOperationBuilder object containing the given interrupted parameter. + */ + std::shared_ptr WithInterruptionAllowed(bool interrupted); + +private: + int type_; + int expectedCount_; + bool interrupted_; + std::shared_ptr uri_; + std::shared_ptr valuesBucket_; + std::shared_ptr dataAbilityPredicates_; + std::shared_ptr valuesBucketReferences_; + std::map dataAbilityPredicatesBackReferences_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_DATA_ABILITY_OPERATION_BUILDER_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/data_ability_result.h b/frameworks/kits/ability/native/include/data_ability_result.h new file mode 100644 index 0000000000000000000000000000000000000000..465a1f445eff5b5d1c8bde0fc3d9378992cc2fd4 --- /dev/null +++ b/frameworks/kits/ability/native/include/data_ability_result.h @@ -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. + */ + +#ifndef FOUNDATION_APPEXECFWK_OHOS_DATA_ABILITY_RESULT_H +#define FOUNDATION_APPEXECFWK_OHOS_DATA_ABILITY_RESULT_H + +#include "uri.h" +#include "parcel.h" + +using Uri = OHOS::Uri; + +namespace OHOS { +namespace AppExecFwk { +class DataAbilityResult final : public Parcelable { +public: + /** + * @brief A constructor used to create a DataAbilityResult instance + * with the input parameter count specified. + */ + DataAbilityResult(int count); + + /** + * @brief A constructor used to create a DataAbilityResult instance + * with the input parameter uri specified + */ + DataAbilityResult(const Uri &uri); + + /** + * @brief A constructor used to create a DataAbilityResult instance + * with a Parcel object specified. + */ + DataAbilityResult(Parcel &parcel); + + /** + * @brief A constructor used to create a DataAbilityResult instance + * with input parameters uri, count, and failure specified. + */ + DataAbilityResult(const Uri &uri, int count); + + ~DataAbilityResult(); + + /** + * @brief Obtains the Uri object corresponding to the operation. + * @return Obtains the Uri object corresponding to the operation. + */ + Uri GetUri(); + + /** + * @brief Obtains the number of rows affected by the operation. + * @return Returns the number of rows affected by the operation. + */ + int GetCount(); + + /** + * @brief Prints out a string containing the class object information. + * @return Returns object information. + */ + std::string ToString(); + + /** + * @brief Marshals a DataAbilityResult object into a Parcel. + * @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; + + /** + * @brief Unmarshals a DataAbilityResult object from a Parcel. + * @param parcel Indicates the Parcel object for unmarshalling. + * @return Returns true if the unmarshalling is successful; returns false otherwise. + */ + static DataAbilityResult *Unmarshalling(Parcel &parcel); + + /** + * @brief Creates a DataAbilityResult instance based on the given Parcel object. + * Used to transfer DataAbilityResult object using Parcel. + * @param parcel Indicates the Parcel object. + * @return Returns the DataAbilityResult object. + */ + static DataAbilityResult *CreateFromParcel(Parcel &parcel); + +private: + Uri uri_; + int count_; + + bool ReadFromParcel(Parcel &parcel); + // no object in parcel + static constexpr int VALUE_NULL = -1; + // object exist in parcel + static constexpr int VALUE_OBJECT = 1; + +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_DATA_ABILITY_RESULT_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/dummy_data_ability_predicates.h b/frameworks/kits/ability/native/include/dummy_data_ability_predicates.h index 6596a5a43a59b1b521018e03899841f7872375a2..a0dc7bf2d3e39a49ce93b084cae29158c9243f23 100644 --- a/frameworks/kits/ability/native/include/dummy_data_ability_predicates.h +++ b/frameworks/kits/ability/native/include/dummy_data_ability_predicates.h @@ -29,6 +29,7 @@ public: DataAbilityPredicates() = default; DataAbilityPredicates(const std::string &testInf); ~DataAbilityPredicates() = default; + DataAbilityPredicates(const Parcel &parcel){}; bool ReadFromParcel(Parcel &parcel); virtual bool Marshalling(Parcel &parcel) const override; diff --git a/frameworks/kits/ability/native/include/dummy_values_bucket.h b/frameworks/kits/ability/native/include/dummy_values_bucket.h index 9ed95542075ae9c1c003101bf1c82cca105950f8..8f6515bcf9e2896dd76b35cc292a76ef8c1f1efd 100644 --- a/frameworks/kits/ability/native/include/dummy_values_bucket.h +++ b/frameworks/kits/ability/native/include/dummy_values_bucket.h @@ -29,11 +29,19 @@ public: ValuesBucket() = default; ValuesBucket(const std::string &testInf); ~ValuesBucket() = default; + ValuesBucket(const Parcel &parcel){}; bool ReadFromParcel(Parcel &parcel); virtual bool Marshalling(Parcel &parcel) const override; static ValuesBucket *Unmarshalling(Parcel &parcel); + bool IsEmpty() + { + return false; + }; + + void PutValues(std::shared_ptr &other){}; + private: std::string testInf_; }; diff --git a/frameworks/kits/ability/native/include/mission_information.h b/frameworks/kits/ability/native/include/mission_information.h new file mode 100644 index 0000000000000000000000000000000000000000..d79e55f380959cd2ff699d45e37b4691347e3392 --- /dev/null +++ b/frameworks/kits/ability/native/include/mission_information.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_OHOS_MISSION_INFORMATION_H +#define FOUNDATION_APPEXECFWK_OHOS_MISSION_INFORMATION_H + +#include + +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +struct MissionInformation : public Parcelable { + std::string label; + std::string iconPath; + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static MissionInformation *Unmarshalling(Parcel &parcel); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_MISSION_INFORMATION_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/ability_context.cpp b/frameworks/kits/ability/native/src/ability_context.cpp index aa1926e2a05c1510675cf0064c4b1028515b3657..0378df9e1e52cef76c3c18011f1b0dbb02b1576f 100755 --- a/frameworks/kits/ability/native/src/ability_context.cpp +++ b/frameworks/kits/ability/native/src/ability_context.cpp @@ -56,6 +56,7 @@ void AbilityContext::StartAbility(const AAFwk::Want &want, int requestCode) if (dms != nullptr) { AAFwk::Want innerWant; APP_LOGI("AbilityContext::StartAbility. try to StartRemoteAbility"); + want.DumpInfo(0); int result = dms->StartRemoteAbility(want, innerWant, requestCode); if (result != ERR_NONE) { APP_LOGE("AbilityContext::StartAbility start remote ability failed, the result is %{public}d", result); @@ -624,7 +625,7 @@ int AbilityContext::VerifyCallingOrSelfPermission(const std::string &permission) if (VerifyCallingPermission(permission) != AppExecFwk::Constants::PERMISSION_GRANTED) { return VerifySelfPermission(permission); } else { - return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; + return AppExecFwk::Constants::PERMISSION_GRANTED; } } @@ -988,6 +989,9 @@ bool AbilityContext::TerminateAbilityResult(int startId) } ErrCode errval = abilityClient->TerminateAbilityResult(token_, startId); + if (errval != ERR_OK) { + APP_LOGE("AbilityContext::TerminateAbilityResult TerminateAbilityResult retval is %d", errval); + } return (errval == ERR_OK) ? true : false; } @@ -1077,6 +1081,10 @@ bool AbilityContext::IsFirstInMission() return false; } ErrCode errval = abilityClient->IsFirstInMission(token_); + if (errval != ERR_OK) { + APP_LOGE("AbilityContext::IsFirstInMission IsFirstInMission retval is %d", errval); + } + return (errval == ERR_OK) ? true : false; } @@ -1173,5 +1181,45 @@ std::shared_ptr AbilityContext::GetGlobalTaskDispatcher(const Ta 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); +} + } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/src/ability_thread.cpp b/frameworks/kits/ability/native/src/ability_thread.cpp index 76efa56ffb741c363716490f9dc4e61be9bd6bbc..62491181f172041be4c9415f5034faa748a87787 100755 --- a/frameworks/kits/ability/native/src/ability_thread.cpp +++ b/frameworks/kits/ability/native/src/ability_thread.cpp @@ -403,6 +403,9 @@ void AbilityThread::ScheduleAbilityTransaction(const Want &want, const LifeCycle APP_LOGI("ScheduleAbilityTransaction::enter, targeState = %{public}d, isNewWant = %{public}d", lifeCycleStateInfo.state, lifeCycleStateInfo.isNewWant); + + want.DumpInfo(0); + if ((token_ == nullptr) || abilityImpl_ == nullptr) { APP_LOGE("ScheduleAbilityTransaction::failed"); return; @@ -727,11 +730,6 @@ int AbilityThread::BatchInsert(const Uri &uri, const std::vector & return ret; } -void AbilityThread::DisplayUnlockMissionMessage() -{ - APP_LOGI("DisplayUnlockMissionMessage..."); -} - /** * @description: Attach The ability thread to the main process. * @param application Indicates the main process. diff --git a/frameworks/kits/ability/native/src/data_ability_operation.cpp b/frameworks/kits/ability/native/src/data_ability_operation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4c00183ed5cdadde64eef86725882297c5bb9c14 --- /dev/null +++ b/frameworks/kits/ability/native/src/data_ability_operation.cpp @@ -0,0 +1,429 @@ +/* + * 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 "data_ability_operation.h" +#include "app_log_wrapper.h" +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +DataAbilityOperation::DataAbilityOperation( + const std::shared_ptr &dataAbilityOperation, const std::shared_ptr &withUri) +{ + uri_ = withUri; + if (dataAbilityOperation != nullptr) { + type_ = dataAbilityOperation->type_; + valuesBucket_ = dataAbilityOperation->valuesBucket_; + expectedCount_ = dataAbilityOperation->expectedCount_; + dataAbilityPredicates_ = dataAbilityOperation->dataAbilityPredicates_; + valuesBucketReferences_ = dataAbilityOperation->valuesBucketReferences_; + dataAbilityPredicatesBackReferences_ = dataAbilityOperation->dataAbilityPredicatesBackReferences_; + interrupted_ = dataAbilityOperation->interrupted_; + } else { + type_ = 0; + expectedCount_ = 0; + valuesBucket_ = std::make_shared(); + dataAbilityPredicates_ = std::make_shared(); + valuesBucketReferences_ = std::make_shared(); + dataAbilityPredicatesBackReferences_.clear(); + interrupted_ = false; + } +} +DataAbilityOperation::DataAbilityOperation(Parcel &in) +{ + type_ = in.ReadInt32(); + uri_ = (in.ReadInt32() != VALUE_NULL) ? std::shared_ptr(Uri::Unmarshalling(in)) : nullptr; + valuesBucket_ = (in.ReadInt32() != VALUE_NULL) ? std::make_shared(in) : nullptr; + int empty = in.ReadInt32(); + expectedCount_ = (empty != VALUE_NULL) ? empty : 0; + dataAbilityPredicates_ = (in.ReadInt32() != VALUE_NULL) ? std::make_shared(in) : nullptr; + valuesBucketReferences_ = (in.ReadInt32() != VALUE_NULL) ? std::make_shared(in) : nullptr; + dataAbilityPredicatesBackReferences_.clear(); + PutMap(in); + interrupted_ = in.ReadBool(); +} +DataAbilityOperation::DataAbilityOperation(const std::shared_ptr &builder) +{ + if (builder != nullptr) { + type_ = builder->type_; + uri_ = builder->uri_; + valuesBucket_ = builder->valuesBucket_; + expectedCount_ = builder->expectedCount_; + dataAbilityPredicates_ = builder->dataAbilityPredicates_; + valuesBucketReferences_ = builder->valuesBucketReferences_; + dataAbilityPredicatesBackReferences_ = builder->dataAbilityPredicatesBackReferences_; + interrupted_ = builder->interrupted_; + } +} + +DataAbilityOperation::DataAbilityOperation() +{ + type_ = 0; + uri_ = nullptr; + expectedCount_ = 0; + valuesBucket_ = std::make_shared(); + dataAbilityPredicates_ = std::make_shared(); + valuesBucketReferences_ = std::make_shared(); + dataAbilityPredicatesBackReferences_.clear(); + interrupted_ = false; +} + +DataAbilityOperation::~DataAbilityOperation() +{ + dataAbilityPredicatesBackReferences_.clear(); +} + +bool DataAbilityOperation::operator==(const DataAbilityOperation &other) const +{ + if (type_ != other.type_) { + return false; + } + if ((uri_ != nullptr) && (other.uri_ != nullptr) && (uri_->ToString() != other.uri_->ToString())) { + return false; + } + if (expectedCount_ != other.expectedCount_) { + return false; + } + if (valuesBucket_ != other.valuesBucket_) { + return false; + } + if (dataAbilityPredicates_ != other.dataAbilityPredicates_) { + return false; + } + if (valuesBucketReferences_ != other.valuesBucketReferences_) { + return false; + } + int backReferencesCount = dataAbilityPredicatesBackReferences_.size(); + int otherBackReferencesCount = other.dataAbilityPredicatesBackReferences_.size(); + if (backReferencesCount != otherBackReferencesCount) { + return false; + } + + std::map::const_iterator it = dataAbilityPredicatesBackReferences_.begin(); + while (it != dataAbilityPredicatesBackReferences_.end()) { + std::map::const_iterator otherIt = other.dataAbilityPredicatesBackReferences_.find(it->first); + if (otherIt != other.dataAbilityPredicatesBackReferences_.end()) { + if (otherIt->second != it->second) { + return false; + } + } else { + return false; + } + it++; + } + + if (interrupted_ != other.interrupted_) { + return false; + } + return true; +} + +DataAbilityOperation &DataAbilityOperation::operator=(const DataAbilityOperation &other) +{ + if (this != &other) { + type_ = other.type_; + uri_ = other.uri_; + expectedCount_ = other.expectedCount_; + valuesBucket_ = other.valuesBucket_; + dataAbilityPredicates_ = other.dataAbilityPredicates_; + valuesBucketReferences_ = other.valuesBucketReferences_; + dataAbilityPredicatesBackReferences_ = other.dataAbilityPredicatesBackReferences_; + interrupted_ = other.interrupted_; + } + return *this; +} + +std::shared_ptr DataAbilityOperation::NewInsertBuilder(const std::shared_ptr &uri) +{ + APP_LOGD("DataAbilityOperation::NewInsertBuilder start"); + if (uri == nullptr) { + APP_LOGE("DataAbilityOperation::NewInsertBuilder uri is nullptr"); + return nullptr; + } + std::shared_ptr builder = + std::make_shared(TYPE_INSERT, uri); + APP_LOGD("DataAbilityOperation::NewInsertBuilder end"); + return builder; +} + +std::shared_ptr DataAbilityOperation::NewUpdateBuilder(const std::shared_ptr &uri) +{ + APP_LOGD("DataAbilityOperation::NewUpdateBuilder start"); + if (uri == nullptr) { + APP_LOGE("DataAbilityOperation::NewUpdateBuilder uri is nullptr"); + return nullptr; + } + std::shared_ptr builder = + std::make_shared(TYPE_UPDATE, uri); + APP_LOGD("DataAbilityOperation::NewUpdateBuilder end"); + return builder; +} + +std::shared_ptr DataAbilityOperation::NewDeleteBuilder(const std::shared_ptr &uri) +{ + APP_LOGD("DataAbilityOperation::NewDeleteBuilder start"); + if (uri == nullptr) { + APP_LOGE("DataAbilityOperation::NewDeleteBuilder uri is nullptr"); + return nullptr; + } + std::shared_ptr builder = + std::make_shared(TYPE_DELETE, uri); + APP_LOGD("DataAbilityOperation::NewDeleteBuilder end"); + return builder; +} + +std::shared_ptr DataAbilityOperation::NewAssertBuilder(const std::shared_ptr &uri) +{ + APP_LOGD("DataAbilityOperation::NewAssertBuilder start"); + if (uri == nullptr) { + APP_LOGE("DataAbilityOperation::NewAssertBuilder uri is nullptr"); + return nullptr; + } + std::shared_ptr builder = + std::make_shared(TYPE_ASSERT, uri); + APP_LOGD("DataAbilityOperation::NewAssertBuilder end"); + return builder; +} + +int DataAbilityOperation::GetType() const +{ + APP_LOGD("DataAbilityOperation::GetType"); + return type_; +} + +std::shared_ptr DataAbilityOperation::GetUri() const +{ + APP_LOGD("DataAbilityOperation::GetUri"); + return uri_; +} + +std::shared_ptr DataAbilityOperation::GetValuesBucket() const +{ + APP_LOGD("DataAbilityOperation::GetValuesBucket"); + return valuesBucket_; +} + +int DataAbilityOperation::GetExpectedCount() const +{ + APP_LOGD("DataAbilityOperation::GetExpectedCount"); + return expectedCount_; +} + +std::shared_ptr DataAbilityOperation::GetDataAbilityPredicates() const +{ + APP_LOGD("DataAbilityOperation::GetDataAbilityPredicates"); + return dataAbilityPredicates_; +} + +std::shared_ptr DataAbilityOperation::GetValuesBucketReferences() const +{ + APP_LOGD("DataAbilityOperation::GetValuesBucketReferences"); + return valuesBucketReferences_; +} +std::map DataAbilityOperation::GetDataAbilityPredicatesBackReferences() const +{ + APP_LOGD("DataAbilityOperation::GetDataAbilityPredicatesBackReferences"); + return dataAbilityPredicatesBackReferences_; +} +bool DataAbilityOperation::IsInsertOperation() const +{ + APP_LOGD("DataAbilityOperation::IsInsertOperation:%d", type_ == TYPE_INSERT); + return type_ == TYPE_INSERT; +} +bool DataAbilityOperation::IsUpdateOperation() const +{ + APP_LOGD("DataAbilityOperation::IsUpdateOperation:%d", type_ == TYPE_UPDATE); + return type_ == TYPE_UPDATE; +} +bool DataAbilityOperation::IsDeleteOperation() const +{ + APP_LOGD("DataAbilityOperation::IsDeleteOperation:%d", type_ == TYPE_DELETE); + return type_ == TYPE_DELETE; +} +bool DataAbilityOperation::IsAssertOperation() const +{ + APP_LOGD("DataAbilityOperation::IsAssertOperation:%d", type_ == TYPE_ASSERT); + return type_ == TYPE_ASSERT; +} +bool DataAbilityOperation::IsInterruptionAllowed() const +{ + APP_LOGD("DataAbilityOperation::IsInterruptionAllowed:%d", interrupted_); + return interrupted_; +} +bool DataAbilityOperation::Marshalling(Parcel &out) const +{ + APP_LOGD("DataAbilityOperation::Marshalling start"); + if (!out.WriteInt32(type_)) { + return false; + } + if (uri_ != nullptr) { + if (!out.WriteInt32(VALUE_OBJECT)) { + return false; + } + + out.WriteParcelable(uri_.get()); + } else { + if (!out.WriteInt32(VALUE_NULL)) { + return false; + } + } + + if (valuesBucket_ != nullptr) { + if (!out.WriteInt32(VALUE_OBJECT) || !valuesBucket_->Marshalling(out)) { + return false; + } + } else { + if (!out.WriteInt32(VALUE_NULL)) { + return false; + } + } + + if (!out.WriteInt32(VALUE_OBJECT) || !out.WriteInt32(expectedCount_)) { + return false; + } + + if (dataAbilityPredicates_ != nullptr) { + if (!out.WriteInt32(VALUE_OBJECT) || !dataAbilityPredicates_->Marshalling(out)) { + return false; + } + } else { + if (!out.WriteInt32(VALUE_NULL)) { + return false; + } + } + + if (valuesBucketReferences_ != nullptr) { + if (!out.WriteInt32(VALUE_OBJECT) || !valuesBucketReferences_->Marshalling(out)) { + return false; + } + } else { + if (!out.WriteInt32(VALUE_NULL)) { + return false; + } + } + + if (!dataAbilityPredicatesBackReferences_.empty()) { + int referenceSize = dataAbilityPredicatesBackReferences_.size(); + if (!out.WriteInt32(VALUE_OBJECT) || !out.WriteInt32(referenceSize)) { + return false; + } + if (referenceSize >= REFERENCE_THRESHOLD) { + if (!out.WriteBool(interrupted_)) { + return false; + } + return true; + } + for (auto it = dataAbilityPredicatesBackReferences_.begin(); it != dataAbilityPredicatesBackReferences_.end(); + it++) { + if (!out.WriteInt32(it->first) || !out.WriteInt32(it->second)) { + return false; + } + } + } else { + APP_LOGD("DataAbilityOperation::Marshalling dataAbilityPredicatesBackReferences_ is empty"); + if (!out.WriteInt32(VALUE_NULL)) { + return false; + } + } + if (!out.WriteBool(interrupted_)) { + return false; + } + APP_LOGD("DataAbilityOperation::Marshalling end"); + return true; +} +DataAbilityOperation *DataAbilityOperation::Unmarshalling(Parcel &in) +{ + APP_LOGD("DataAbilityOperation::Unmarshalling start"); + DataAbilityOperation *dataAbilityOperation = new (std::nothrow) DataAbilityOperation(); + if (dataAbilityOperation != nullptr && !dataAbilityOperation->ReadFromParcel(in)) { + delete dataAbilityOperation; + dataAbilityOperation = nullptr; + } + APP_LOGD("DataAbilityOperation::Unmarshalling end"); + return dataAbilityOperation; +} +bool DataAbilityOperation::ReadFromParcel(Parcel &in) +{ + APP_LOGD("DataAbilityOperation::ReadFromParcel start"); + if (!in.ReadInt32(type_)) { + return false; + } + int empty; + if (in.ReadInt32(empty)) { + return false; + } + uri_ = (empty == VALUE_OBJECT) ? std::shared_ptr(Uri::Unmarshalling(in)) : nullptr; + + empty = VALUE_NULL; + if (in.ReadInt32(empty)) { + return false; + } + valuesBucket_ = (empty == VALUE_OBJECT) ? std::make_shared(in) : nullptr; + + empty = VALUE_NULL; + if (in.ReadInt32(empty)) { + return false; + } + expectedCount_ = (empty == VALUE_OBJECT) ? empty : 0; + + empty = VALUE_NULL; + if (in.ReadInt32(empty)) { + return false; + } + dataAbilityPredicates_ = (empty == VALUE_OBJECT) ? std::make_shared(in) : nullptr; + + empty = VALUE_NULL; + if (in.ReadInt32(empty)) { + return false; + } + valuesBucketReferences_ = (empty == VALUE_OBJECT) ? std::make_shared(in) : nullptr; + + empty = VALUE_NULL; + if (in.ReadInt32(empty)) { + return false; + } + if (empty == VALUE_OBJECT) { + if (empty > 0 && empty < REFERENCE_THRESHOLD) { + for (int i = 0; i < empty; ++i) { + dataAbilityPredicatesBackReferences_.insert(std::make_pair(in.ReadInt32(), in.ReadInt32())); + } + } + } else { + dataAbilityPredicatesBackReferences_.clear(); + } + interrupted_ = in.ReadBool(); + APP_LOGD("DataAbilityOperation::ReadFromParcel end"); + return true; +} +std::shared_ptr DataAbilityOperation::CreateFromParcel(Parcel &in) +{ + APP_LOGD("DataAbilityOperation::CreateFromParcel start"); + std::shared_ptr operation = std::make_shared(in); + APP_LOGD("DataAbilityOperation::CreateFromParcel end"); + return operation; +} +void DataAbilityOperation::PutMap(Parcel &in) +{ + APP_LOGD("DataAbilityOperation::PutMap start"); + int count = in.ReadInt32(); + if (count > 0 && count < REFERENCE_THRESHOLD) { + for (int i = 0; i < count; ++i) { + dataAbilityPredicatesBackReferences_.insert(std::make_pair(in.ReadInt32(), in.ReadInt32())); + } + } + APP_LOGD("DataAbilityOperation::PutMap end"); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/data_ability_operation_builder.cpp b/frameworks/kits/ability/native/src/data_ability_operation_builder.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a0c4b003b926654206db1663e1bf3ad48ad2dda7 --- /dev/null +++ b/frameworks/kits/ability/native/src/data_ability_operation_builder.cpp @@ -0,0 +1,158 @@ +/* + * 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 "data_ability_operation_builder.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +DataAbilityOperationBuilder::DataAbilityOperationBuilder(const int type, const std::shared_ptr &uri) +{ + type_ = type; + uri_ = uri; + expectedCount_ = 0; + valuesBucket_ = nullptr; + dataAbilityPredicates_ = nullptr; + valuesBucketReferences_ = nullptr; + dataAbilityPredicatesBackReferences_.clear(); +} +DataAbilityOperationBuilder::~DataAbilityOperationBuilder() +{ + dataAbilityPredicatesBackReferences_.clear(); +} + +std::shared_ptr DataAbilityOperationBuilder::Build() +{ + APP_LOGD("DataAbilityOperationBuilder::Build start"); + if (type_ != DataAbilityOperation::TYPE_UPDATE || (valuesBucket_ != nullptr && !valuesBucket_->IsEmpty())) { + std::shared_ptr operation = std::make_shared(shared_from_this()); + APP_LOGD("DataAbilityOperationBuilder::Build end"); + return operation; + } + APP_LOGE("DataAbilityOperationBuilder::Build return nullptr"); + return nullptr; +} +std::shared_ptr DataAbilityOperationBuilder::WithValuesBucket( + std::shared_ptr &values) +{ + APP_LOGD("DataAbilityOperationBuilder::WithValuesBucket start"); + // APP_LOGI("DataAbilityOperationBuilder::WithValuesBucket valuesBucket:%{public}s", values->ToString()); + if (type_ != DataAbilityOperation::TYPE_INSERT && type_ != DataAbilityOperation::TYPE_UPDATE && + type_ != DataAbilityOperation::TYPE_ASSERT) { + APP_LOGE("DataAbilityOperationBuilder::WithValuesBucket only inserts, updates can have values, type=%{public}d", + type_); + return nullptr; + } + if (valuesBucket_ == nullptr) { + valuesBucket_ = std::make_shared(); + } + + valuesBucket_->PutValues(values); + APP_LOGD("DataAbilityOperationBuilder::WithValuesBucket end"); + return shared_from_this(); +} + +std::shared_ptr DataAbilityOperationBuilder::WithPredicates( + std::shared_ptr &predicates) +{ + APP_LOGD("DataAbilityOperationBuilder::WithPredicates start"); + // APP_LOGI("DataAbilityOperationBuilder::WithPredicates order:%{public}s, group:%{public}s, index:%{public}s, " + // "whereClause:%{public}s, limit:%{public}d, offset:%{public}d, distinct:%{public}d", + // predicates->GetOrder(), + // predicates->GetGroup(), + // predicates->GetIndex(), + // predicates->GetWhereClause(), + // predicates->GetLimit(), + // predicates->GetOffset(), + // predicates->isDistinct()); + if (type_ != DataAbilityOperation::TYPE_DELETE && type_ != DataAbilityOperation::TYPE_UPDATE && + type_ != DataAbilityOperation::TYPE_ASSERT) { + APP_LOGE( + "DataAbilityOperationBuilder::withPredicates only deletes and updates can have selections, type=%{public}d", + type_); + return nullptr; + } + dataAbilityPredicates_ = predicates; + APP_LOGD("DataAbilityOperationBuilder::WithPredicates end"); + return shared_from_this(); +} +std::shared_ptr DataAbilityOperationBuilder::WithExpectedCount(int count) +{ + APP_LOGD("DataAbilityOperationBuilder::WithExpectedCount start"); + APP_LOGI("DataAbilityOperationBuilder::WithExpectedCount expectedCount:%{public}d", count); + if (type_ != DataAbilityOperation::TYPE_UPDATE && type_ != DataAbilityOperation::TYPE_DELETE && + type_ != DataAbilityOperation::TYPE_ASSERT) { + APP_LOGE("DataAbilityOperationBuilder::withExpectedCount only updates, deletes can have expected counts, " + "type=%{public}d", + type_); + return nullptr; + } + expectedCount_ = count; + APP_LOGD("DataAbilityOperationBuilder::WithExpectedCount end"); + return shared_from_this(); +} +std::shared_ptr DataAbilityOperationBuilder::WithPredicatesBackReference( + int requestArgIndex, int previousResult) +{ + APP_LOGD("DataAbilityOperationBuilder::WithPredicatesBackReference start"); + APP_LOGI("DataAbilityOperationBuilder::WithPredicatesBackReference requestArgIndex:%{public}d, " + "previousResult:%{public}d", + requestArgIndex, + previousResult); + if (type_ != DataAbilityOperation::TYPE_UPDATE && type_ != DataAbilityOperation::TYPE_DELETE && + type_ != DataAbilityOperation::TYPE_ASSERT) { + APP_LOGE("DataAbilityOperationBuilder::withPredicatesBackReference only updates, deletes, and asserts can have " + "select back-references, type=%{public}d", + type_); + return nullptr; + } + dataAbilityPredicatesBackReferences_.insert(std::make_pair(requestArgIndex, previousResult)); + APP_LOGD("DataAbilityOperationBuilder::WithPredicatesBackReference end"); + return shared_from_this(); +} +std::shared_ptr DataAbilityOperationBuilder::WithValueBackReferences( + std::shared_ptr &backReferences) +{ + APP_LOGD("DataAbilityOperationBuilder::WithValueBackReferences start"); + // APP_LOGI("DataAbilityOperationBuilder::WithValueBackReferences backReferences:%{public}s", + // backReferences->ToString()); + if (type_ != DataAbilityOperation::TYPE_INSERT && type_ != DataAbilityOperation::TYPE_UPDATE && + type_ != DataAbilityOperation::TYPE_ASSERT) { + APP_LOGE("DataAbilityOperationBuilder::withValueBackReferences only inserts, updates, and asserts can have " + "value back-references, type=%{public}d", + type_); + return nullptr; + } + valuesBucketReferences_ = backReferences; + APP_LOGD("DataAbilityOperationBuilder::WithValueBackReferences end"); + return shared_from_this(); +} +std::shared_ptr DataAbilityOperationBuilder::WithInterruptionAllowed(bool interrupted) +{ + APP_LOGD("DataAbilityOperationBuilder::WithInterruptionAllowed start"); + APP_LOGI("DataAbilityOperationBuilder::WithInterruptionAllowed interrupted=%{public}d", interrupted); + if (type_ != DataAbilityOperation::TYPE_INSERT && type_ != DataAbilityOperation::TYPE_UPDATE && + type_ != DataAbilityOperation::TYPE_ASSERT && type_ != DataAbilityOperation::TYPE_DELETE) { + APP_LOGE("DataAbilityOperationBuilder::withInterruptionAllowed only inserts, updates, delete, and asserts can " + "have value back-references, type=%{public}d", + type_); + return nullptr; + } + interrupted_ = interrupted; + APP_LOGD("DataAbilityOperationBuilder::WithInterruptionAllowed end"); + return shared_from_this(); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/src/data_ability_result.cpp b/frameworks/kits/ability/native/src/data_ability_result.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4431789dae3614314c7c37381b74fc31dd782689 --- /dev/null +++ b/frameworks/kits/ability/native/src/data_ability_result.cpp @@ -0,0 +1,178 @@ +/* + * 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 "data_ability_result.h" +#include +#include +#include "parcel_macro.h" + +namespace OHOS { +namespace AppExecFwk { + +/** + * @brief A constructor used to create a DataAbilityResult instance + * with the input parameter count specified. + */ +DataAbilityResult::DataAbilityResult(int count) : uri_("") +{ + count_ = count; +} + +/** + * @brief A constructor used to create a DataAbilityResult instance + * with a Parcel object specified. + */ +DataAbilityResult::DataAbilityResult(Parcel &parcel) : uri_(""), count_(0) +{ + ReadFromParcel(parcel); +} + +/** + * @brief A constructor used to create a DataAbilityResult instance + * with the input parameter uri specified + */ +DataAbilityResult::DataAbilityResult(const Uri &uri) : uri_(uri.ToString()), count_(0) +{} + +/** + * @brief A constructor used to create a DataAbilityResult instance + * with input parameters uri, count, and failure specified. + */ +DataAbilityResult::DataAbilityResult(const Uri &uri, int count) : uri_(uri.ToString()) +{ + count_ = count; +} + +DataAbilityResult::~DataAbilityResult() +{} + +/** + * @brief Obtains the Uri object corresponding to the operation. + * @return Obtains the Uri object corresponding to the operation. + */ +Uri DataAbilityResult::GetUri() +{ + return uri_; +} + +/** + * @brief Obtains the number of rows affected by the operation. + * @return Returns the number of rows affected by the operation. + */ +int DataAbilityResult::GetCount() +{ + return count_; +} + +/** + * @brief Creates a DataAbilityResult instance based on the given Parcel object. + * Used to transfer DataAbilityResult object using Parcel. + * @param parcel Indicates the Parcel object. + * @return Returns the DataAbilityResult object. + */ +DataAbilityResult *DataAbilityResult::CreateFromParcel(Parcel &parcel) +{ + DataAbilityResult *dataAbilityResult = new (std::nothrow) DataAbilityResult(parcel); + return dataAbilityResult; +} + +/** + * @brief Prints out a string containing the class object information. + * @return Returns object information. + */ +std::string DataAbilityResult::ToString() +{ + std::string stringBuilder = "DataAbilityResult("; + stringBuilder.append("uri=").append(uri_.ToString()).append(" "); + stringBuilder.append("count=").append(std::to_string(count_)).append(" "); + stringBuilder.erase(stringBuilder.length() - 1 , 1); + stringBuilder.append(")"); + return stringBuilder; +} + +/** + * @brief Marshals a DataAbilityResult object into a Parcel. + * @param parcel Indicates the Parcel object for marshalling. + * @return Returns true if the marshalling is successful; returns false otherwise. + */ +bool DataAbilityResult::Marshalling(Parcel &parcel) const +{ + //uri_ + if (uri_.ToString().empty()) { + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, VALUE_NULL); + } else { + if (!parcel.WriteInt32(VALUE_OBJECT)) { + return false; + } + if (!parcel.WriteParcelable(&uri_)) { + return false; + } + } + + //count_ + if (!parcel.WriteInt32(count_)) { + return false; + } + + return true; +} + +/** + * @brief Unmarshals a DataAbilityResult object from a Parcel. + * @param parcel Indicates the Parcel object for unmarshalling. + * @return Returns true if the unmarshalling is successful; returns false otherwise. + */ +DataAbilityResult *DataAbilityResult::Unmarshalling(Parcel &parcel) +{ + DataAbilityResult *dataAbilityResult = new (std::nothrow) DataAbilityResult(0); + if (dataAbilityResult != nullptr ) { + if(!dataAbilityResult->ReadFromParcel(parcel)){ + delete dataAbilityResult; + dataAbilityResult = nullptr; + } + } + + return dataAbilityResult; +} + +bool DataAbilityResult::ReadFromParcel(Parcel &parcel) +{ + //uri_ + int32_t empty = VALUE_NULL; + if (!parcel.ReadInt32(empty)) { + return false; + } + + if (empty == VALUE_OBJECT) { + auto uri = parcel.ReadParcelable(); + if (uri != nullptr) { + uri_ = *uri; + delete uri; + uri = nullptr; + } else { + return false; + } + } + + //count_ + if (!parcel.ReadInt32(count_)) { + return false; + } + + return true; +} + +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/kits/ability/native/src/mission_information.cpp b/frameworks/kits/ability/native/src/mission_information.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b24c1bdeae80aa13826dbe29e47f0cb1fc919b8 --- /dev/null +++ b/frameworks/kits/ability/native/src/mission_information.cpp @@ -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. + */ + +#include "string_ex.h" + +#include "mission_information.h" + +namespace OHOS { +namespace AppExecFwk { +bool MissionInformation::ReadFromParcel(Parcel &parcel) +{ + label = Str16ToStr8(parcel.ReadString16()); + iconPath = Str16ToStr8(parcel.ReadString16()); + + return true; +} +bool MissionInformation::Marshalling(Parcel &parcel) const +{ + parcel.WriteString16(Str8ToStr16(label)); + parcel.WriteString16(Str8ToStr16(iconPath)); + + return true; +} +MissionInformation *MissionInformation::Unmarshalling(Parcel &parcel) +{ + MissionInformation *info = new (std::nothrow) MissionInformation(); + if (info == nullptr) { + return nullptr; + } + + if (!info->ReadFromParcel(parcel)) { + delete info; + info = nullptr; + } + return info; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/test/BUILD.gn b/frameworks/kits/ability/native/test/BUILD.gn index b354a934d5148c1c65b6740a291c4c6a9fb010c8..229430987b57033ceff59b8663564a7736e62a7a 100755 --- a/frameworks/kits/ability/native/test/BUILD.gn +++ b/frameworks/kits/ability/native/test/BUILD.gn @@ -381,6 +381,36 @@ ohos_unittest("data_ability_helper_test") { ] } +ohos_unittest("data_ability_operation_test") { + module_out_path = module_output_path + sources = [ "unittest/data_ability_operation_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "${INNERKITS_PATH}/want:want", + "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//foundation/multimodalinput/input/interfaces/native/innerkits/event:mmi_event", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + ohos_unittest("ability_impl_active_test") { module_out_path = module_output_path sources = [ @@ -788,6 +818,25 @@ ohos_unittest("task_handler_client_test") { external_deps = [ "hiviewdfx_hilog_native:libhilog" ] } +ohos_unittest("data_ability_result_test") { + module_out_path = module_output_path + sources = [ "//foundation/aafwk/standard/frameworks/kits/ability/native/test/unittest/data_ability_result_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + ############################################################################### group("unittest") { @@ -807,6 +856,8 @@ group("unittest") { ":data_ability_impl_file_secondpart_test", ":data_ability_impl_file_test", ":data_ability_impl_test", + ":data_ability_operation_test", + ":data_ability_result_test", ":data_uri_utils_test", ":pac_map_test", ":page_ability_impl_test", 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 ecce96234803a8f977f5b6699876028fec2c7e50..610fd1598d989c7f748323c966169a312cfb6d61 100644 --- 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 @@ -133,9 +133,6 @@ public: { return "Type1"; } - - void DisplayUnlockMissionMessage() - {} }; } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client_interface1.cpp b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client_interface1.cpp index 5e21fe18c6bb7a6992221cde42286f542fc49661..14c5c1d6631c039ef282c0732b191fc93408ead9 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client_interface1.cpp +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client_interface1.cpp @@ -35,6 +35,8 @@ MockAbilityManagerClient::MockAbilityManagerClient() removeMissionsE_ = ERR_INVALID_OPERATION; terminateAbilityValue_ = 0; removeMissions_ = 0; + missionId_ = -1; + moveMissionToEnd_ = false; } MockAbilityManagerClient::~MockAbilityManagerClient() {} @@ -56,9 +58,6 @@ void MockAbilityManagerClient::SetInstanceNull(bool flag) mock_intanceIsNull_ = flag; } -std::shared_ptr AbilityManagerClient::instance_ = nullptr; -std::mutex AbilityManagerClient::mutex_; - std::shared_ptr AbilityManagerClient::GetInstance() { if (instance_ == nullptr) { @@ -73,9 +72,6 @@ std::shared_ptr AbilityManagerClient::GetInstance() return nullptr; } -AbilityManagerClient::AbilityManagerClient() -{} - AbilityManagerClient::~AbilityManagerClient() {} @@ -220,6 +216,31 @@ ErrCode AbilityManagerClient::IsFirstInMission(const sptr &token) return MockAbilityManagerClient::GetInstance()->GetIsFirstInMission(); } +ErrCode AbilityManagerClient::MoveMissionToEnd(const sptr &token, const bool nonFirst) +{ + MockAbilityManagerClient::GetInstance()->SetMockMoveMissionToEnd( + !MockAbilityManagerClient::GetInstance()->GetMockMoveMissionToEnd()); + return ERR_OK; +} + +ErrCode AbilityManagerClient::LockMission(int missionId) +{ + MockAbilityManagerClient::GetInstance()->SetMockMissionId(missionId); + return ERR_OK; +} + +ErrCode AbilityManagerClient::UnlockMission(int missionId) +{ + MockAbilityManagerClient::GetInstance()->SetMockMissionId(missionId); + return ERR_OK; +} + +ErrCode AbilityManagerClient::SetMissionDescriptionInfo( + const sptr &token, const MissionDescriptionInfo &missionDescriptionInfo) +{ + return ERR_OK; +} + ErrCode MockAbilityManagerClient::GetStartAbility() { return startAbility_; @@ -279,6 +300,24 @@ void MockAbilityManagerClient::ChangeRemoveMissionsValue() ++removeMissions_; } +int MockAbilityManagerClient::GetMockMissionId() +{ + return missionId_; +} +void MockAbilityManagerClient::SetMockMissionId(int missionId) +{ + missionId_ = missionId; +} + +bool MockAbilityManagerClient::GetMockMoveMissionToEnd() +{ + return moveMissionToEnd_; +} +void MockAbilityManagerClient::SetMockMoveMissionToEnd(bool flag) +{ + moveMissionToEnd_ = flag; +} + } // namespace AAFwk } // namespace OHOS @@ -321,5 +360,10 @@ void MockAbilityContextTest::SetStartAbilityRunCount(size_t nCount) startAbilityRunCount_ = nCount; } +void MockAbilityContextTest::SetToken(const sptr token) +{ + token_ = token; +} + } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client_interface1.h b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client_interface1.h index d10d62f5188bde121dc2e90c07de47f562c0ba2c..24be4d90614f1f005a4938db3ae6c5b4f5d946b6 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client_interface1.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client_interface1.h @@ -25,11 +25,60 @@ #include "want.h" #include "iremote_object.h" +#include "iremote_stub.h" #include "ability_manager_client.h" +namespace OHOS { +namespace AppExecFwk { + +class IAbilityMock : public OHOS::IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.aafwk.AbilityMock"); +}; + +class MockAbilityStub : public IRemoteStub { +public: + MockAbilityStub() = default; + virtual ~MockAbilityStub() = default; + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override + { + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + }; +}; + +class MockAbilityContextDeal : public ContextDeal { +public: + MockAbilityContextDeal(); + virtual ~MockAbilityContextDeal(); + + std::shared_ptr GetHapModuleInfo(); + + std::shared_ptr hapModInfo_; +}; + +class MockAbilityContextTest : public AbilityContext { +public: + MockAbilityContextTest(); + ~MockAbilityContextTest(); + + void StartAbility(const AAFwk::Want &want, int requestCode); + + void SetToken(const sptr token); + + size_t GetStartAbilityRunCount(); + void SetStartAbilityRunCount(size_t nCount); + + size_t startAbilityRunCount_; +}; + +} // namespace AppExecFwk +} // namespace OHOS + namespace OHOS { namespace AAFwk { + class MockAbilityManagerClient : public AbilityManagerClient { public: MockAbilityManagerClient(); @@ -53,6 +102,12 @@ public: int GetRemoveMissionsValue(); void ChangeRemoveMissionsValue(); + int GetMockMissionId(); + void SetMockMissionId(int missionId); + + bool GetMockMoveMissionToEnd(); + void SetMockMoveMissionToEnd(bool flag); + static std::shared_ptr mock_instance_; static bool mock_intanceIsNull_; @@ -68,38 +123,12 @@ private: int terminateAbilityValue_; int removeMissions_; + int missionId_; + bool moveMissionToEnd_; }; -} // namespace AAFwk -} // namespace OHOS - -namespace OHOS { -namespace AppExecFwk { +}; // namespace AAFwk -class MockAbilityContextDeal : public ContextDeal { -public: - MockAbilityContextDeal(); - virtual ~MockAbilityContextDeal(); - - std::shared_ptr GetHapModuleInfo(); - - std::shared_ptr hapModInfo_; -}; - -class MockAbilityContextTest : public AbilityContext { -public: - MockAbilityContextTest(); - ~MockAbilityContextTest(); - - void StartAbility(const AAFwk::Want &want, int requestCode); - - size_t GetStartAbilityRunCount(); - void SetStartAbilityRunCount(size_t nCount); - - size_t startAbilityRunCount_; -}; - -} // namespace AppExecFwk } // namespace OHOS #endif // OHOS_AAFWK_ABILITY_MANAGER_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 908a4aa6b567d6a744746d6c69418b18fa446651..78da73670653dc17413cc366cb9c5406b0a4eea7 100755 --- 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 @@ -70,6 +70,17 @@ public: return 0; }; + int SetMissionDescriptionInfo( + const sptr &token, const MissionDescriptionInfo &missionDescriptionInfo) override + { + return 0; + }; + + int GetMissionLockModeState() + { + return 0; + } + MOCK_METHOD1(GetAllStackInfo, int(StackInfo &stackInfo)); MOCK_METHOD2( GetWantSender, sptr(const WantSenderInfo &wantSenderInfo, const sptr &callerToken)); diff --git a/frameworks/kits/ability/native/test/unittest/ability_context_interface1_test.cpp b/frameworks/kits/ability/native/test/unittest/ability_context_interface1_test.cpp index 9390c7e7d8a4b3ba62d1b801698dfa50e05d3c98..75fe6708480e5c64c2992697303b9faf6e944bde 100644 --- a/frameworks/kits/ability/native/test/unittest/ability_context_interface1_test.cpp +++ b/frameworks/kits/ability/native/test/unittest/ability_context_interface1_test.cpp @@ -633,5 +633,102 @@ HWTEST_F(AbilityContextInterfaceTest, AaFwk_Ability_TerminateAndRemoveMission_02 GTEST_LOG_(INFO) << "AaFwk_Ability_TerminateAndRemoveMission_0200 end"; } +HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_MoveMissionToEnd_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityContext_MoveMissionToEnd_0100 start"; + std::shared_ptr abilityContext = std::make_shared(); + const sptr token(new (std::nothrow) MockAbilityStub()); + bool testValue = OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->GetMockMoveMissionToEnd(); + + abilityContext->SetToken(token); + EXPECT_TRUE(abilityContext->MoveMissionToEnd(!testValue)); + + if (testValue) { + EXPECT_FALSE(OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->GetMockMoveMissionToEnd()); + } else { + EXPECT_TRUE(OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->GetMockMoveMissionToEnd()); + } + + GTEST_LOG_(INFO) << "AaFwk_AbilityContext_MoveMissionToEnd_0100 end"; +} + +HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_LockMission_0100, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityContext_LockMission_0100 start"; + std::shared_ptr abilityContext = std::make_shared(); + std::shared_ptr contextDeal = std::make_shared(); + + int testValue = OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->GetMockMissionId(); + testValue++; + AAFwk::LifeCycleStateInfo lifeInfo; + lifeInfo.missionId = testValue; + contextDeal->SetLifeCycleStateInfo(lifeInfo); + abilityContext->AttachBaseContext(contextDeal); + + abilityContext->LockMission(); + + EXPECT_EQ(testValue, OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->GetMockMissionId()); + + GTEST_LOG_(INFO) << "AaFwk_AbilityContext_LockMission_0100 end"; +} + +HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_UnlockMission_0100, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityContext_UnlockMission_0100 start"; + std::shared_ptr abilityContext = std::make_shared(); + std::shared_ptr contextDeal = std::make_shared(); + + int testValue = OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->GetMockMissionId(); + testValue++; + AAFwk::LifeCycleStateInfo lifeInfo; + lifeInfo.missionId = testValue; + contextDeal->SetLifeCycleStateInfo(lifeInfo); + abilityContext->AttachBaseContext(contextDeal); + + abilityContext->UnlockMission(); + + EXPECT_EQ(testValue, OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->GetMockMissionId()); + + GTEST_LOG_(INFO) << "AaFwk_AbilityContext_UnlockMission_0100 end"; +} + +HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_GetMissionId_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetMissionId_0100 start"; + std::shared_ptr abilityContext = std::make_shared(); + std::shared_ptr contextDeal = std::make_shared(); + const int testValue = 1; + + EXPECT_NE(testValue, abilityContext->GetMissionId()); + + abilityContext->AttachBaseContext(contextDeal); + + EXPECT_NE(testValue, abilityContext->GetMissionId()); + + AAFwk::LifeCycleStateInfo lifeInfo; + lifeInfo.missionId = testValue; + contextDeal->SetLifeCycleStateInfo(lifeInfo); + + EXPECT_EQ(testValue, abilityContext->GetMissionId()); + + GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetMissionId_0100 end"; +} + +HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_SetMissionInformation_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityContext_SetMissionInformation_0100 start"; + std::shared_ptr abilityContext = std::make_shared(); + const sptr token(new (std::nothrow) MockAbilityStub()); + AppExecFwk::MissionInformation missionInformation; + + EXPECT_FALSE(abilityContext->SetMissionInformation(missionInformation)); + + abilityContext->SetToken(token); + + EXPECT_TRUE(abilityContext->SetMissionInformation(missionInformation)); + + GTEST_LOG_(INFO) << "AaFwk_AbilityContext_SetMissionInformation_0100 end"; +} + } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/kits/ability/native/test/unittest/data_ability_operation_test.cpp b/frameworks/kits/ability/native/test/unittest/data_ability_operation_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4d9bcfae098590c01207c37636272aef7b4b136e --- /dev/null +++ b/frameworks/kits/ability/native/test/unittest/data_ability_operation_test.cpp @@ -0,0 +1,734 @@ +/* + * 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 "data_ability_operation.h" +#include "data_ability_operation_builder.h" +#include +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +static const std::string URI = "dataability://ohos.demo.TestDataAbilityOperation"; +class DataAbilityOperationTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + void CreateBuilder(int type, std::shared_ptr &uri); + std::shared_ptr builder = nullptr; +}; + +void DataAbilityOperationTest::SetUpTestCase(void) +{} + +void DataAbilityOperationTest::TearDownTestCase(void) +{} + +void DataAbilityOperationTest::SetUp(void) +{} + +void DataAbilityOperationTest::TearDown(void) +{ + builder = nullptr; +} + +void DataAbilityOperationTest::CreateBuilder(int type, std::shared_ptr &uri) +{ + builder = std::make_shared(type, uri); +} + +/** + * @tc.number: AaFwk_DataAbilityOperation_Create_0100 + * @tc.name: Constructor + * @tc.desc: Test the dataabilityoperation object. + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_Create_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_Create_0100 start"; + std::shared_ptr dataAbilityOperation = std::make_shared(); + EXPECT_EQ(dataAbilityOperation->GetUri(), nullptr); + EXPECT_EQ(dataAbilityOperation->GetType(), 0); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_Create_0100 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityOperation_Create_0200 + * @tc.name: Constructor + * @tc.desc: Test the dataabilityoperation object. + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_Create_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_Create_0200 start"; + Parcel in; + std::shared_ptr dataAbilityOperation = std::make_shared(in); + EXPECT_EQ(dataAbilityOperation->GetUri(), nullptr); + EXPECT_EQ(dataAbilityOperation->GetType(), 0); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_Create_0200 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityOperation_Create_0300 + * @tc.name: Constructor + * @tc.desc: Test the dataabilityoperation object. + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_Create_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_Create_0300 start"; + std::shared_ptr uri = std::make_shared(URI); + std::unique_ptr dataAbilityOperation = std::make_unique(nullptr, uri); + EXPECT_EQ(dataAbilityOperation->GetUri()->ToString(), URI); + EXPECT_EQ(dataAbilityOperation->GetType(), 0); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_Create_0300 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityOperation_Create_0400 + * @tc.name: Constructor + * @tc.desc: Test the dataabilityoperation object. + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_Create_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_Create_0400 start"; + Parcel in; + std::shared_ptr dataAbilityOperation = std::make_shared(in); + std::shared_ptr uri = std::make_shared(URI); + std::unique_ptr operation = std::make_unique(dataAbilityOperation, uri); + EXPECT_EQ(operation->GetUri()->ToString(), URI); + EXPECT_EQ(operation->GetType(), 0); + dataAbilityOperation.reset(); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_Create_0400 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityOperation_Create_0500 + * @tc.name: Constructor/GetUri + * @tc.desc: Test the dataabilityoperation object. + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_Create_0500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_Create_0500 start"; + std::shared_ptr uri = std::make_shared(URI); + std::shared_ptr builder = + std::make_shared(DataAbilityOperation::TYPE_INSERT, uri); + + std::unique_ptr dataAbilityOperation = std::make_unique(builder); + EXPECT_EQ(dataAbilityOperation->GetUri()->ToString(), URI); + EXPECT_EQ(dataAbilityOperation->GetType(), 1); + dataAbilityOperation.reset(); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_Create_0500 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityOperation_NewInsertBuilder_0100 + * @tc.name: NewInsertBuilder + * @tc.desc: Test whether the return value of NewInsertBuilder is DataAbilityOperationBuilder + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_NewInsertBuilder_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_NewInsertBuilder_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + + std::shared_ptr builder = DataAbilityOperation::NewInsertBuilder(uri); + EXPECT_NE(builder, nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_NewInsertBuilder_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_NewInsertBuilder_0200 + * @tc.name: NewInsertBuilder + * @tc.desc: Test whether the return value of NewInsertBuilder is DataAbilityOperationBuilder + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_NewInsertBuilder_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_NewInsertBuilder_0200 start"; + std::shared_ptr builder = DataAbilityOperation::NewInsertBuilder(nullptr); + EXPECT_EQ(builder, nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_NewInsertBuilder_0200 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityOperation_NewUpdateBuilder_0100 + * @tc.name: NewUpdateBuilder + * @tc.desc: Test whether the return value of NewUpdateBuilder is DataAbilityOperationBuilder + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_NewUpdateBuilder_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_NewUpdateBuilder_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + + std::shared_ptr builder = DataAbilityOperation::NewUpdateBuilder(uri); + EXPECT_NE(builder, nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_NewUpdateBuilder_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_NewUpdateBuilder_0200 + * @tc.name: NewUpdateBuilder + * @tc.desc: Test whether the return value of NewUpdateBuilder is DataAbilityOperationBuilder + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_NewUpdateBuilder_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_NewUpdateBuilder_0200 start"; + std::shared_ptr builder = DataAbilityOperation::NewUpdateBuilder(nullptr); + EXPECT_EQ(builder, nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_NewUpdateBuilder_0200 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityOperation_NewDeleteBuilder_0100 + * @tc.name: NewDeleteBuilder + * @tc.desc: Test whether the return value of NewDeleteBuilder is DataAbilityOperationBuilder + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_NewDeleteBuilder_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_NewDeleteBuilder_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + + std::shared_ptr builder = DataAbilityOperation::NewDeleteBuilder(uri); + EXPECT_NE(builder, nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_NewDeleteBuilder_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_NewDeleteBuilder_0200 + * @tc.name: NewDeleteBuilder + * @tc.desc: Test whether the return value of NewDeleteBuilder is DataAbilityOperationBuilder + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_NewDeleteBuilder_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_NewDeleteBuilder_0200 start"; + std::shared_ptr builder = DataAbilityOperation::NewDeleteBuilder(nullptr); + EXPECT_EQ(builder, nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_NewDeleteBuilder_0200 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityOperation_NewAssertBuilder_0100 + * @tc.name: NewAssertBuilder + * @tc.desc: Test whether the return value of NewAssertBuilder is DataAbilityOperationBuilder + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_NewAssertBuilder_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_NewAssertBuilder_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + + std::shared_ptr builder = DataAbilityOperation::NewAssertBuilder(uri); + EXPECT_NE(builder, nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_NewAssertBuilder_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_NewAssertBuilder_0200 + * @tc.name: NewAssertBuilder + * @tc.desc: Test whether the return value of NewAssertBuilder is DataAbilityOperationBuilder + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_NewAssertBuilder_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_NewAssertBuilder_0200 start"; + std::shared_ptr builder = DataAbilityOperation::NewAssertBuilder(nullptr); + EXPECT_EQ(builder, nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_NewAssertBuilder_0200 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityOperation_GetType_0100 + * @tc.name: GetType + * @tc.desc: Test whether the return value of GetType is 3 + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_GetType_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetType_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_DELETE, uri); + std::unique_ptr dataAbilityOperation = std::make_unique(builder); + EXPECT_EQ(dataAbilityOperation->GetType(), 3); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetType_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_GetValuesBucket_0100 + * @tc.name: GetValuesBucket + * @tc.desc: Test whether the return value of GetValuesBucket is nullptr + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_GetValuesBucket_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetValuesBucket_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_DELETE, uri); + std::unique_ptr dataAbilityOperation = std::make_unique(builder); + EXPECT_EQ(dataAbilityOperation->GetValuesBucket(), nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetValuesBucket_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_GetValuesBucket_0200 + * @tc.name: GetValuesBucket + * @tc.desc: Test whether the return value of GetValuesBucket is not nullptr + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_GetValuesBucket_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetValuesBucket_0200 start"; + std::shared_ptr uri = std::make_shared(URI); + std::shared_ptr values = std::make_shared(); + std::shared_ptr dataAbilityOperation = + DataAbilityOperation::NewAssertBuilder(uri)->WithValuesBucket(values)->Build(); + EXPECT_NE(dataAbilityOperation->GetValuesBucket(), nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetValuesBucket_0200 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_GetExpectedCount_0100 + * @tc.name: GetExpectedCount + * @tc.desc: Test whether the return value of GetExpectedCount is 0 + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_GetExpectedCount_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetExpectedCount_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_DELETE, uri); + std::unique_ptr dataAbilityOperation = std::make_unique(builder); + EXPECT_EQ(dataAbilityOperation->GetExpectedCount(), 0); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetExpectedCount_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_GetExpectedCount_0200 + * @tc.name: GetExpectedCount + * @tc.desc: Test whether the return value of GetExpectedCount is 10 + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_GetExpectedCount_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetExpectedCount_0200 start"; + std::shared_ptr uri = std::make_shared(URI); + std::shared_ptr dataAbilityOperation = + DataAbilityOperation::NewAssertBuilder(uri)->WithExpectedCount(10)->Build(); + // CreateBuilder(DataAbilityOperation::TYPE_UPDATE, uri); + // // builder = builder->WithExpectedCount(10); + // // EXPECT_NE(builder, nullptr); + // std::shared_ptr dataAbilityOperation = builder->WithExpectedCount(10)->Build(); + EXPECT_EQ(dataAbilityOperation->GetExpectedCount(), 10); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetExpectedCount_0200 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_GetDataAbilityPredicates_0100 + * @tc.name: GetDataAbilityPredicates + * @tc.desc: Test whether the return value of GetDataAbilityPredicates is nullptr + */ +HWTEST_F( + DataAbilityOperationTest, AaFwk_DataAbilityOperation_GetDataAbilityPredicates_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetDataAbilityPredicates_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_DELETE, uri); + std::unique_ptr dataAbilityOperation = std::make_unique(builder); + EXPECT_EQ(dataAbilityOperation->GetDataAbilityPredicates(), nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetDataAbilityPredicates_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_GetDataAbilityPredicates_0200 + * @tc.name: GetDataAbilityPredicates + * @tc.desc: Test whether the return value of GetDataAbilityPredicates is not nullptr + */ +HWTEST_F( + DataAbilityOperationTest, AaFwk_DataAbilityOperation_GetDataAbilityPredicates_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetDataAbilityPredicates_0200 start"; + std::shared_ptr uri = std::make_shared(URI); + std::shared_ptr predicates = std::make_shared(); + std::shared_ptr dataAbilityOperation = + DataAbilityOperation::NewAssertBuilder(uri)->WithPredicates(predicates)->Build(); + EXPECT_NE(dataAbilityOperation->GetDataAbilityPredicates(), nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetDataAbilityPredicates_0200 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_GetValuesBucketReferences_0100 + * @tc.name: GetValuesBucketReferences + * @tc.desc: Test whether the return value of GetValuesBucketReferences is nullptr + */ +HWTEST_F( + DataAbilityOperationTest, AaFwk_DataAbilityOperation_GetValuesBucketReferences_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetValuesBucketReferences_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_DELETE, uri); + + std::unique_ptr dataAbilityOperation = std::make_unique(builder); + EXPECT_EQ(dataAbilityOperation->GetValuesBucketReferences(), nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetValuesBucketReferences_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_GetValuesBucketReferences_0200 + * @tc.name: GetValuesBucketReferences + * @tc.desc: Test whether the return value of GetValuesBucketReferences is not nullptr + */ +HWTEST_F( + DataAbilityOperationTest, AaFwk_DataAbilityOperation_GetValuesBucketReferences_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetValuesBucketReferences_0200 start"; + std::shared_ptr uri = std::make_shared(URI); + std::shared_ptr backReferences = std::make_shared(); + std::shared_ptr dataAbilityOperation = + DataAbilityOperation::NewAssertBuilder(uri)->WithValueBackReferences(backReferences)->Build(); + EXPECT_NE(dataAbilityOperation->GetValuesBucketReferences(), nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetValuesBucketReferences_0200 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_GetDataAbilityPredicatesBackReferences_0100 + * @tc.name: GetDataAbilityPredicatesBackReferences + * @tc.desc: Test whether the return value of GetDataAbilityPredicatesBackReferences is empty + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_GetDataAbilityPredicatesBackReferences_0100, + Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetDataAbilityPredicatesBackReferences_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_DELETE, uri); + + std::unique_ptr dataAbilityOperation = std::make_unique(builder); + std::map map = dataAbilityOperation->GetDataAbilityPredicatesBackReferences(); + EXPECT_TRUE(map.empty()); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetDataAbilityPredicatesBackReferences_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_GetDataAbilityPredicatesBackReferences_0200 + * @tc.name: GetDataAbilityPredicatesBackReferences + * @tc.desc: Test whether the value of the return value is 5 + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_GetDataAbilityPredicatesBackReferences_0200, + Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetDataAbilityPredicatesBackReferences_0200 start"; + std::shared_ptr uri = std::make_shared(URI); + std::shared_ptr dataAbilityOperation = + DataAbilityOperation::NewAssertBuilder(uri)->WithPredicatesBackReference(2, 5)->Build(); + std::map map = dataAbilityOperation->GetDataAbilityPredicatesBackReferences(); + std::map::iterator iter; + iter = map.find(2); + EXPECT_EQ(iter->second, 5); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_GetDataAbilityPredicatesBackReferences_0200 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_IsInsertOperation_0100 + * @tc.name: IsInsertOperation + * @tc.desc: Test whether the return value of IsInsertOperation is true + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_IsInsertOperation_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_IsInsertOperation_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_INSERT, uri); + + std::unique_ptr dataAbilityOperation = std::make_unique(builder); + EXPECT_TRUE(dataAbilityOperation->IsInsertOperation()); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_IsInsertOperation_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_IsInsertOperation_0200 + * @tc.name: IsInsertOperation + * @tc.desc: Test whether the return value of IsInsertOperation is false + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_IsInsertOperation_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_IsInsertOperation_0200 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_UPDATE, uri); + + std::unique_ptr dataAbilityOperation = std::make_unique(builder); + EXPECT_FALSE(dataAbilityOperation->IsInsertOperation()); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_IsInsertOperation_0200 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_IsUpdateOperation_0100 + * @tc.name: IsUpdateOperation + * @tc.desc: Test whether the return value of IsUpdateOperation is true + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_IsUpdateOperation_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_IsUpdateOperation_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_UPDATE, uri); + + std::unique_ptr dataAbilityOperation = std::make_unique(builder); + EXPECT_TRUE(dataAbilityOperation->IsUpdateOperation()); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_IsUpdateOperation_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_IsUpdateOperation_0200 + * @tc.name: IsUpdateOperation + * @tc.desc: Test whether the return value of IsUpdateOperation is false + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_IsUpdateOperation_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_IsUpdateOperation_0200 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_DELETE, uri); + + std::unique_ptr dataAbilityOperation = std::make_unique(builder); + EXPECT_FALSE(dataAbilityOperation->IsUpdateOperation()); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_IsUpdateOperation_0200 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_IsDeleteOperation_0100 + * @tc.name: IsDeleteOperation + * @tc.desc: Test whether the return value of IsDeleteOperation is true + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_IsDeleteOperation_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_IsDeleteOperation_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_DELETE, uri); + + std::unique_ptr dataAbilityOperation = std::make_unique(builder); + EXPECT_TRUE(dataAbilityOperation->IsDeleteOperation()); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_IsDeleteOperation_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_IsDeleteOperation_0200 + * @tc.name: IsDeleteOperation + * @tc.desc: Test whether the return value of IsDeleteOperation is false + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_IsDeleteOperation_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_IsDeleteOperation_0200 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_ASSERT, uri); + + std::unique_ptr dataAbilityOperation = std::make_unique(builder); + EXPECT_FALSE(dataAbilityOperation->IsDeleteOperation()); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_IsDeleteOperation_0200 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityOperation_IsAssertOperation_0100 + * @tc.name: IsAssertOperation + * @tc.desc: Test whether the return value of IsAssertOperation is true + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_IsAssertOperation_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_IsAssertOperation_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_ASSERT, uri); + + std::unique_ptr dataAbilityOperation = std::make_unique(builder); + EXPECT_TRUE(dataAbilityOperation->IsAssertOperation()); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_IsAssertOperation_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_IsAssertOperation_0200 + * @tc.name: IsAssertOperation + * @tc.desc: Test whether the return value of IsAssertOperation is false + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_IsAssertOperation_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_IsAssertOperation_0200 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_DELETE, uri); + + std::unique_ptr dataAbilityOperation = std::make_unique(builder); + EXPECT_FALSE(dataAbilityOperation->IsAssertOperation()); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_IsAssertOperation_0200 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_IsInterruptionAllowed_0100 + * @tc.name: IsInterruptionAllowed + * @tc.desc: Test whether the return value of IsInterruptionAllowed is false + */ +HWTEST_F( + DataAbilityOperationTest, AaFwk_DataAbilityOperation_IsInterruptionAllowed_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_IsInterruptionAllowed_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_DELETE, uri); + + std::unique_ptr dataAbilityOperation = std::make_unique(builder); + EXPECT_FALSE(dataAbilityOperation->IsInterruptionAllowed()); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_IsInterruptionAllowed_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_IsInterruptionAllowed_0200 + * @tc.name: IsInterruptionAllowed + * @tc.desc: Test whether the return value of IsInterruptionAllowed is true + */ +HWTEST_F( + DataAbilityOperationTest, AaFwk_DataAbilityOperation_IsInterruptionAllowed_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_IsInterruptionAllowed_0200 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_DELETE, uri); + builder = builder->WithInterruptionAllowed(true); + EXPECT_NE(builder, nullptr); + std::unique_ptr dataAbilityOperation = std::make_unique(builder); + EXPECT_TRUE(dataAbilityOperation->IsInterruptionAllowed()); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_IsInterruptionAllowed_0200 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityOperation_CreateFromParcel_0100 + * @tc.name: CreateFromParcel + * @tc.desc: Test whether the return value of CreateFromParcel is not nullptr + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_CreateFromParcel_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_CreateFromParcel_0100 start"; + Parcel in; + std::shared_ptr dataAbilityOperation = DataAbilityOperation::CreateFromParcel(in); + EXPECT_NE(dataAbilityOperation, nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_CreateFromParcel_0100 end"; +} + +/** + * @tc.number: AaFwk_DataAbilityOperation_Marshalling_0100 + * @tc.name: Marshalling + * @tc.desc: Validation serialization. + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_Marshalling_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_Marshalling_0100 start"; + + std::shared_ptr uri = std::make_shared(URI); + std::shared_ptr dataAbilityOperation = DataAbilityOperation::NewAssertBuilder(uri) + ->WithInterruptionAllowed(true) + ->WithPredicatesBackReference(0, 0) + ->Build(); + std::map references = dataAbilityOperation->GetDataAbilityPredicatesBackReferences(); + for (int i = 0; i < 3 * 1024 * 1024 + 1; i++) { + references.insert(std::make_pair(i, i)); + } + + Parcel out; + dataAbilityOperation->Marshalling(out); + + EXPECT_TRUE(out.GetReadableBytes() < 3 * 1024 * 1024); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_Marshalling_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperation_Unmarshalling_0100 + * @tc.name: Unmarshalling + * @tc.desc: Validation serialization. + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_Unmarshalling_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_Unmarshalling_0100 start"; + Parcel in; + for (int i = 0; i < 6; i++) { + in.WriteInt32(0); + } + in.WriteInt32(1); + in.WriteInt32(3 * 1024 * 1024 + 1); + in.WriteBool(false); + + std::shared_ptr uri = std::make_shared(URI); + std::shared_ptr dataAbilityOperation = DataAbilityOperation::NewAssertBuilder(uri) + ->WithInterruptionAllowed(true) + ->WithPredicatesBackReference(0, 0) + ->Build(); + DataAbilityOperation::Unmarshalling(in); + std::map references = dataAbilityOperation->GetDataAbilityPredicatesBackReferences(); + EXPECT_TRUE(references.size() == 1); + + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_Unmarshalling_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperationBuilder_WithValuesBucket_0100 + * @tc.name: WithValuesBucket + * @tc.desc: Test whether the return value of WithValuesBucket is nullptr + */ +HWTEST_F( + DataAbilityOperationTest, AaFwk_DataAbilityOperationBuilder_WithValuesBucket_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperationBuilder_WithValuesBucket_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_DELETE, uri); + std::shared_ptr values = std::make_shared(); + builder = builder->WithValuesBucket(values); + EXPECT_EQ(builder, nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperationBuilder_WithValuesBucket_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperationBuilder_WithPredicates_0100 + * @tc.name: WithPredicates + * @tc.desc: Test whether the return value of WithPredicates is nullptr + */ +HWTEST_F( + DataAbilityOperationTest, AaFwk_DataAbilityOperationBuilder_WithPredicates_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperationBuilder_WithPredicates_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_INSERT, uri); + std::shared_ptr predicates = std::make_shared(); + builder = builder->WithPredicates(predicates); + EXPECT_EQ(builder, nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperationBuilder_WithPredicates_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperationBuilder_WithExpectedCount_0100 + * @tc.name: WithExpectedCount + * @tc.desc: Test whether the return value of WithExpectedCount is nullptr + */ +HWTEST_F( + DataAbilityOperationTest, AaFwk_DataAbilityOperationBuilder_WithExpectedCount_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperationBuilder_WithExpectedCount_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_INSERT, uri); + builder = builder->WithExpectedCount(1); + EXPECT_EQ(builder, nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperationBuilder_WithExpectedCount_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperationBuilder_WithPredicatesBackReference_0100 + * @tc.name: WithPredicatesBackReference + * @tc.desc: Test whether the return value of WithPredicatesBackReference is nullptr + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperationBuilder_WithPredicatesBackReference_0100, + Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperationBuilder_WithPredicatesBackReference_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_INSERT, uri); + builder = builder->WithPredicatesBackReference(1, 1); + EXPECT_EQ(builder, nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperationBuilder_WithPredicatesBackReference_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperationBuilder_WithValueBackReferences_0100 + * @tc.name: WithValueBackReferences + * @tc.desc: Test whether the return value of WithValueBackReferences is nullptr + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperationBuilder_WithValueBackReferences_0100, + Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperationBuilder_WithValueBackReferences_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(DataAbilityOperation::TYPE_DELETE, uri); + std::shared_ptr backReferences = std::make_shared(); + builder = builder->WithValueBackReferences(backReferences); + EXPECT_EQ(builder, nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperationBuilder_WithValueBackReferences_0100 end"; +} +/** + * @tc.number: AaFwk_DataAbilityOperationBuilder_WithInterruptionAllowed_0100 + * @tc.name: WithInterruptionAllowed + * @tc.desc: Test whether the return value of WithInterruptionAllowed is nullptr + */ +HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperationBuilder_WithInterruptionAllowed_0100, + Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperationBuilder_WithInterruptionAllowed_0100 start"; + std::shared_ptr uri = std::make_shared(URI); + CreateBuilder(0, uri); + builder = builder->WithInterruptionAllowed(false); + EXPECT_EQ(builder, nullptr); + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperationBuilder_WithInterruptionAllowed_0100 end"; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file 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 new file mode 100644 index 0000000000000000000000000000000000000000..72c6f315f6f9a59e56de1ba375f96586ff0e0372 --- /dev/null +++ b/frameworks/kits/ability/native/test/unittest/data_ability_result_test.cpp @@ -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. + */ +#include +#include "data_ability_result.h" + +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace AppExecFwk { + +static const int COUNT_NULL = 0; +static const int SET_COUNT = 1; +static const Uri uri("scheme://authority/path1/path2/path3?id = 1&name = mingming&old#fragment"); +class DataAbilityResultTest : public testing::Test { +public: + DataAbilityResultTest() + {} + ~DataAbilityResultTest() + {} + + std::shared_ptr Base_ = nullptr; + + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void DataAbilityResultTest::SetUpTestCase(void) +{} + +void DataAbilityResultTest::TearDownTestCase(void) +{} + +void DataAbilityResultTest::SetUp(void) +{ + Base_ = std::make_shared(COUNT_NULL); +} + +void DataAbilityResultTest::TearDown(void) +{} + + +/** + * @tc.number: + * @tc.name: + * @tc.desc: + */ +HWTEST_F(DataAbilityResultTest, AppExecFwk_DataAbilityResult_DataAbilityResult0100, Function | MediumTest | Level1) +{ + DataAbilityResult test1(SET_COUNT); + EXPECT_EQ(SET_COUNT, test1.GetCount()); + EXPECT_EQ(std::string(""), test1.GetUri().ToString()); + + DataAbilityResult test2(uri); + EXPECT_EQ(COUNT_NULL, test2.GetCount()); + EXPECT_EQ(uri.ToString(), test2.GetUri().ToString()); + + DataAbilityResult test3(uri,SET_COUNT); + EXPECT_EQ(SET_COUNT, test3.GetCount()); + EXPECT_EQ(uri.ToString(), test3.GetUri().ToString()); + + *Base_ = test3; + if(Base_){ + Parcel in; + Base_->Marshalling(in); + DataAbilityResult test4(in); + EXPECT_EQ(SET_COUNT, test4.GetCount()); + EXPECT_EQ(uri.ToString(), test4.GetUri().ToString()); + } +} + +/** + * @tc.number: + * @tc.name: + * @tc.desc: + */ +HWTEST_F(DataAbilityResultTest, AppExecFwk_DataAbilityResult_DataAbilityResult0200, Function | MediumTest | Level1) +{ + DataAbilityResult test1(COUNT_NULL); + EXPECT_EQ(COUNT_NULL, test1.GetCount()); + EXPECT_EQ(std::string(""), test1.GetUri().ToString()); + + Uri zero(""); + DataAbilityResult test2(zero); + EXPECT_EQ(COUNT_NULL, test2.GetCount()); + EXPECT_EQ(zero.ToString(), test2.GetUri().ToString()); + + DataAbilityResult test3(uri,SET_COUNT); + EXPECT_EQ(SET_COUNT, test3.GetCount()); + EXPECT_EQ(uri.ToString(), test3.GetUri().ToString()); + + Parcel in; + test3.Marshalling(in); + DataAbilityResult test4(in); + EXPECT_EQ(SET_COUNT, test4.GetCount()); + EXPECT_EQ(uri.ToString(), test4.GetUri().ToString()); +} + +/** + * @tc.number: + * @tc.name: + * @tc.desc: + */ +HWTEST_F(DataAbilityResultTest, AppExecFwk_DataAbilityResult_Get0100, Function | MediumTest | Level1) +{ + // Uri uri("abc"); + DataAbilityResult test(uri,SET_COUNT); + EXPECT_EQ(SET_COUNT, test.GetCount()); + EXPECT_EQ(uri.ToString(), test.GetUri().ToString()); +} + +/** + * @tc.number: + * @tc.name: + * @tc.desc: + */ +HWTEST_F(DataAbilityResultTest, AppExecFwk_DataAbilityResult_Get0200, Function | MediumTest | Level1) +{ + EXPECT_EQ(true, Base_->GetUri().ToString().empty()); + EXPECT_EQ(COUNT_NULL, Base_->GetCount()); +} + +/** + * @tc.number: + * @tc.name: + * @tc.desc: + */ +HWTEST_F(DataAbilityResultTest, AppExecFwk_DataAbilityResult_CreateFromParcel0100, Function | MediumTest | Level1) +{ + Parcel in; + Base_->Marshalling(in); + DataAbilityResult *ptr = Base_->CreateFromParcel(in); + + if (ptr != nullptr) { + EXPECT_EQ(true, ptr->GetUri().ToString().empty()); + EXPECT_EQ(COUNT_NULL, ptr->GetCount()); + } +} + +/** + * @tc.number: + * @tc.name: + * @tc.desc: + */ +HWTEST_F(DataAbilityResultTest, AppExecFwk_DataAbilityResult_ToString0100, Function | MediumTest | Level1) +{ + std::string search = "DataAbilityResult("; + std::size_t pos = 0; + std::size_t result = 0; + + DataAbilityResult dataAbilityResult(uri,SET_COUNT); + std::string str = dataAbilityResult.ToString(); + + result = str.find(search, pos); + EXPECT_EQ(result, pos); + if (result != std::string::npos) { + pos += search.length() - 1; + } + + search = std::string("uri=") + uri.ToString() + std::string(" "); + result = str.find(search, pos); + + EXPECT_NE(result, std::string::npos); + EXPECT_GE(result, pos); + if (result != std::string::npos) { + pos += search.length(); + } + + search = std::string("count=") + std::to_string(dataAbilityResult.GetCount()) + std::string(")"); + result = str.find(search, pos); + EXPECT_NE(result, std::string::npos); + EXPECT_GE(result, pos); + if (result != std::string::npos) { + pos += search.length() + 1; + } + + EXPECT_EQ(str.length(), pos); +} + +/** + * @tc.number: + * @tc.name: + * @tc.desc: + */ +HWTEST_F(DataAbilityResultTest, AppExecFwk_DataAbilityResult_ToString0200, Function | MediumTest | Level1) +{ + + std::string search = "DataAbilityResult("; + std::size_t pos = 0; + std::size_t result = 0; + + DataAbilityResult dataAbilityResult(COUNT_NULL); + std::string str = dataAbilityResult.ToString(); + + result = str.find(search, pos); + EXPECT_EQ(result, pos); + if (result != std::string::npos) { + pos += search.length() - 1; + } + + search = std::string("uri=") + dataAbilityResult.GetUri().ToString() + std::string(" "); + result = str.find(search, pos); + + EXPECT_NE(result, std::string::npos); + EXPECT_GE(result, pos); + if (result != std::string::npos) { + pos += search.length(); + } + + search = std::string("count=") + std::to_string(dataAbilityResult.GetCount()) + std::string(")"); + result = str.find(search, pos); + EXPECT_NE(result, std::string::npos); + EXPECT_GE(result, pos); + if (result != std::string::npos) { + pos += search.length() + 1; + } + + EXPECT_EQ(str.length(), pos); +} + +/** + * @tc.number: + * @tc.name: Marshalling/Unmarshalling + * @tc.desc: marshalling + */ +HWTEST_F(DataAbilityResultTest, AppExecFwk_DataAbilityResult_Parcelable_0100, Function | MediumTest | Level1) +{ + std::shared_ptr ResultIn_ = std::make_shared(COUNT_NULL); + if (ResultIn_ == nullptr) { + return; + } + + + Parcel in; + ResultIn_->Marshalling(in); + std::shared_ptr ResultOut_(DataAbilityResult::Unmarshalling(in)); + + if (ResultOut_ != nullptr) { + EXPECT_EQ(ResultIn_->GetUri().ToString(), ResultOut_->GetUri().ToString()); + EXPECT_EQ(ResultIn_->GetCount(), ResultOut_->GetCount()); + } +} + +/** + * @tc.number: + * @tc.name: Marshalling/Unmarshalling + * @tc.desc: + */ +HWTEST_F(DataAbilityResultTest, AppExecFwk_DataAbilityResult_Parcelable_0200, Function | MediumTest | Level1) +{ + std::shared_ptr ResultIn_ = std::make_shared(uri); + if (ResultIn_ == nullptr) { + return; + } + + Parcel in; + ResultIn_->Marshalling(in); + std::shared_ptr ResultOut_(DataAbilityResult::Unmarshalling(in)); + + if (ResultOut_ != nullptr) { + EXPECT_EQ(ResultIn_->GetUri().ToString(), ResultOut_->GetUri().ToString()); + EXPECT_EQ(ResultIn_->GetCount(), ResultOut_->GetCount()); + } +} + +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/content/cpp/src/ohos/aafwk/content/operation.cpp b/frameworks/kits/content/cpp/src/ohos/aafwk/content/operation.cpp index 0b85ed28260a21f084daccbdb6ae8b96954b1c6f..5b8c2f57e2c44ac05aeefa632365966e0a1a8e69 100755 --- a/frameworks/kits/content/cpp/src/ohos/aafwk/content/operation.cpp +++ b/frameworks/kits/content/cpp/src/ohos/aafwk/content/operation.cpp @@ -370,5 +370,24 @@ void Operation::SetEntities(const std::vector &entities) entities_.clear(); entities_ = entities; } + +void Operation::DumpInfo(int level) const +{ + APP_LOGI("=======Operation::DumpInfo level: %{public}d start=============", level); + + APP_LOGI("===Operation::abilityName_ %{public}s =============", abilityName_.c_str()); + APP_LOGI("===Operation::action_ %{public}s =============", action_.c_str()); + APP_LOGI("===Operation::bundleName_ %{public}s =============", bundleName_.c_str()); + APP_LOGI("===Operation::deviceId_ %{public}s =============", deviceId_.c_str()); + long entities_count = entities_.size(); + APP_LOGI("===Operation::entities_: count %{public}ld =============", entities_count); + for (long i = 0; i < entities_count; i++) { + APP_LOGI("=Operation::entities_[%{public}ld]:%{public}s =============", i, entities_[i].c_str()); + } + APP_LOGI("===Operation::flags_ %{public}ud =============", flags_); + APP_LOGI("===Operation::uri_ %{public}s =============", uri_.ToString().c_str()); + + APP_LOGI("=======Operation::DumpInfo level: %{public}d end=============", level); +} } // namespace AAFwk } // namespace OHOS \ No newline at end of file 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 cecb3dfecd37475f78b5d0f9d4abadb9f9bb6165..cf72743e4821bf53e2b98f0c59d30ef94534bce7 100755 --- a/frameworks/kits/content/cpp/src/ohos/aafwk/content/want.cpp +++ b/frameworks/kits/content/cpp/src/ohos/aafwk/content/want.cpp @@ -1855,5 +1855,17 @@ bool Want::CheckAndSetParameters(Want &want, const std::string &key, std::string return true; } +void Want::DumpInfo(int level) const +{ + APP_LOGI("==================Want::DumpInfo level: %{public}d start=============", level); + operation_.DumpInfo(level); + parameters_.DumpInfo(level); + + if (picker_ != nullptr) { + picker_->DumpInfo(level + 1); + } + APP_LOGI("==================Want::DumpInfo level: %{public}d end=============", level); +} + } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/content/cpp/src/ohos/aafwk/content/want_params.cpp b/frameworks/kits/content/cpp/src/ohos/aafwk/content/want_params.cpp index 384f9301537170c759362fd899f2977f2f0c68de..bb5cabb75565a5bfda40797aa68518c687b0edc7 100755 --- a/frameworks/kits/content/cpp/src/ohos/aafwk/content/want_params.cpp +++ b/frameworks/kits/content/cpp/src/ohos/aafwk/content/want_params.cpp @@ -29,6 +29,9 @@ #include "ohos/aafwk/base/string_wrapper.h" #include "want_params_wrapper.h" #include "ohos/aafwk/base/zchar_wrapper.h" +#include "app_log_wrapper.h" + +using namespace OHOS::AppExecFwk; namespace OHOS { namespace AAFwk { @@ -54,6 +57,8 @@ std::string WantParams::GetStringByType(const sptr iIt, int typeId) return static_cast(IString::Query(iIt))->ToString(); } else if (typeId == VALUE_TYPE_ARRAY) { return static_cast(IArray::Query(iIt))->ToString(); + } else if (typeId == VALUE_TYPE_WANTPARAMS) { + return static_cast(IWantParams::Query(iIt))->ToString(); } else { return ""; } @@ -1041,5 +1046,25 @@ WantParams *WantParams::Unmarshalling(Parcel &parcel) } return wantParams; } + +void WantParams::DumpInfo(int level) const +{ + APP_LOGI("=======WantParams::DumpInfo level: %{public}d start=============", level); + + int params_size = params_.size(); + APP_LOGI("===WantParams::params_: count %{public}d =============", params_size); + int typeId = VALUE_TYPE_NULL; + for (auto it : params_) { + typeId = VALUE_TYPE_NULL; + typeId = WantParams::GetDataType(it.second); + if (typeId != VALUE_TYPE_NULL) { + std::string value = WantParams::GetStringByType(it.second, typeId); + APP_LOGI("=WantParams::params_[%{public}s] : %{public}s =============", it.first.c_str(), value.c_str()); + } else { + APP_LOGI("=WantParams::params_[%{public}s] : type error =============", it.first.c_str()); + } + } + APP_LOGI("=======WantParams::DumpInfo level: %{public}d end=============", level); +} } // namespace AAFwk } // namespace OHOS diff --git a/frameworks/kits/content/cpp/test/BUILD.gn b/frameworks/kits/content/cpp/test/BUILD.gn index 73a02b3e815656451a347153e82c0bcc19254532..eef0ff06d6a7d55ef011010172d8d6be7c669a03 100755 --- a/frameworks/kits/content/cpp/test/BUILD.gn +++ b/frameworks/kits/content/cpp/test/BUILD.gn @@ -273,7 +273,10 @@ ohos_unittest("want_params_test") { "//utils/native/base:utils", ] - external_deps = [ "appexecfwk_standard:appexecfwk_base" ] + external_deps = [ + "appexecfwk_standard:appexecfwk_base", + "hiviewdfx_hilog_native:libhilog", + ] } ohos_unittest("want_params_wrapper_test") { @@ -289,11 +292,16 @@ ohos_unittest("want_params_wrapper_test") { deps = [ "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] - external_deps = [ "appexecfwk_standard:appexecfwk_base" ] + external_deps = [ + "appexecfwk_standard:appexecfwk_base", + "hiviewdfx_hilog_native:libhilog", + ] } ohos_unittest("want_test") { diff --git a/frameworks/kits/test/BUILD.gn b/frameworks/kits/test/BUILD.gn index a111e0dad9bd0590b4c8f98fb9ed9061d6d63b4c..d8aa70497a0c5921b304b38a413d71c7bf45537c 100755 --- a/frameworks/kits/test/BUILD.gn +++ b/frameworks/kits/test/BUILD.gn @@ -152,6 +152,67 @@ ohos_moduletest("ability_conetxt_test") { ] } +ohos_moduletest("data_ability_operation_moduletest") { + module_out_path = module_output_path + sources = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native/src/data_ability_operation.cpp", + "//foundation/aafwk/standard/frameworks/kits/ability/native/src/data_ability_operation_builder.cpp", + "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.cpp", + "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/sys_mgr_client_mock.cpp", + "//foundation/aafwk/standard/frameworks/kits/test/mock/AMS/mock_ability_manager_client.cpp", + "//foundation/aafwk/standard/frameworks/kits/test/mock/AMS/mock_ability_manager_service.cpp", + "//foundation/aafwk/standard/frameworks/kits/test/mock/DemoAbility/demo_ability_test.cpp", + "//foundation/aafwk/standard/frameworks/kits/test/mock/DemoAbility/mock_lifecycle_observer.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/ability_connect_callback_stub.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/ability_manager_proxy.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/ability_manager_stub.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/ability_mission_info.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/ability_record_info.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/ability_scheduler_proxy.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/ability_scheduler_stub.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/caller_info.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/image_info.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/lifecycle_state_info.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/mission_description_info.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/mission_record_info.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/mission_snapshot_info.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/mission_stack_info.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/sender_info.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/stack_info.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/want_sender_info.cpp", + "//foundation/aafwk/standard/services/abilitymgr/src/wants_info.cpp", + "moduletest/cpp/abilitytest/data_ability_operation_module_test.cpp", + ] + + configs = [ + ":module_private_config", + "//foundation/aafwk/standard/interfaces/innerkits/want:want_public_config", + "//foundation/aafwk/standard/frameworks/kits/ability/native:ability_config", + ] + + deps = [ + "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + ################################################################################ group("moduletest") { testonly = true @@ -162,6 +223,7 @@ group("moduletest") { deps += [ ":ability_conetxt_test", ":ability_moduletest", + ":data_ability_operation_moduletest", ] } } 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 5f04e325cd845c309e6ed997d198b2870f3ca2f3..286c4445cc2139bfef279d52019fd6954b0b031b 100644 --- a/frameworks/kits/test/mock/AMS/mock_ability_manager_service.h +++ b/frameworks/kits/test/mock/AMS/mock_ability_manager_service.h @@ -101,6 +101,15 @@ public: { return 0; }; + int SetMissionDescriptionInfo( + const sptr &token, const MissionDescriptionInfo &missionDescriptionInfo) override + { + return 0; + }; + int GetMissionLockModeState() + { + return 0; + } AbilityLifeCycleState curstate_ = AbilityLifeCycleState::ABILITY_STATE_INITIAL; sptr abilityScheduler_; // kit interface used to schedule ability life diff --git a/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.h b/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.h index 03eeb2d422c7ac1a3e6f511a565eaf36864b66da..9db181de2472ef551dacdac732cd004a16446fc8 100644 --- a/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.h +++ b/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.h @@ -87,11 +87,21 @@ public: int LockMission(int missionId) override { return 0; - }; + } int UnlockMission(int missionId) override { return 0; - }; + } + int SetMissionDescriptionInfo( + const sptr &token, const MissionDescriptionInfo &missionDescriptionInfo) override + { + return 0; + } + int GetMissionLockModeState() + { + return 0; + } + sptr AcquireDataAbility( const Uri &uri, bool tryBind, const sptr &callerToken) override { 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 new file mode 100644 index 0000000000000000000000000000000000000000..11462db916eee1575f519a65ca63017dcb024aa3 --- /dev/null +++ b/frameworks/kits/test/moduletest/cpp/abilitytest/data_ability_operation_module_test.cpp @@ -0,0 +1,257 @@ +/* + * 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 +#include "ability_thread.h" +#include "ability_local_record.h" +#include "ability_loader.h" +#include "ability_impl_factory.h" +#include "data_ability_helper.h" +#include "context_deal.h" +#include "ohos_application.h" +#include "sys_mgr_client.h" +#include "ability_manager_interface.h" +#include "ability_manager_client.h" +#include "system_ability_definition.h" +#include "demo_ability_test.h" +#include "mock_bundle_manager.h" +#include "mock_ability_manager_service.h" +#include "data_ability_operation.h" +#include "data_ability_operation_builder.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace AAFwk; +using OHOS::AppExecFwk::ElementName; +using namespace OHOS::AppExecFwk; +/* + * Parameters: + * Action + * Entity + * Flag + * ElementName + */ +// const std::string ABILITY_NAME("DemoAbility"); +class DataAbilityOperationModuleTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + OHOS::sptr abilityObject_; + // static constexpr int TEST_WAIT_TIME = 500 * 1000; // 500 ms + // static const int RESULT_CODE = 1992; +}; + +void DataAbilityOperationModuleTest::SetUpTestCase(void) +{} + +void DataAbilityOperationModuleTest::TearDownTestCase(void) +{} + +void DataAbilityOperationModuleTest::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; + } + + sysMgr->RegisterSystemAbility(OHOS::ABILITY_MGR_SERVICE_ID, abilityObject_); + sysMgr->RegisterSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject); +} + +void DataAbilityOperationModuleTest::TearDown(void) +{} + +/** + * @tc.number: AaFwk_DataAbilityOperation_InsertBuilder_0100 + * @tc.name: DataAbilityOperation + * @tc.desc: Get the file types in the dataability. + + */ +HWTEST_F(DataAbilityOperationModuleTest, AaFwk_DataAbilityOperation_InsertBuilder_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_InsertBuilder_0100"; + + std::shared_ptr application = std::make_shared(); + sptr abilityToken = sptr(new AbilityThread()); + EXPECT_NE(abilityToken, nullptr); + if (abilityToken != nullptr) { + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AppExecFwk::AbilityType::DATA; + abilityInfo->name = "DemoAbility"; + std::shared_ptr abilityRecord = + std::make_shared(abilityInfo, abilityToken); + + AbilityThread::AbilityThreadMain(application, abilityRecord); + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); + std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); + + EXPECT_NE(helper, nullptr); + std::shared_ptr values = std::make_shared(); + std::shared_ptr operation = + DataAbilityOperation::NewInsertBuilder(uri)->WithValuesBucket(values)->Build(); + EXPECT_NE(operation, nullptr); + + bool isInsertOperation = operation->IsInsertOperation(); + EXPECT_TRUE(isInsertOperation); + + std::shared_ptr operationUri = operation->GetUri(); + EXPECT_EQ(operationUri->ToString(), "dataability://com.example.myapplication5.DataAbilityTest"); + + int type = operation->GetType(); + EXPECT_EQ(type, DataAbilityOperation::TYPE_INSERT); + } + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_InsertBuilder_0100"; +} + +/** + * @tc.number: AaFwk_DataAbilityOperation_UpdateBuilder_0100 + * @tc.name: DataAbilityOperation + * @tc.desc: Get the file types in the dataability. + + */ +HWTEST_F(DataAbilityOperationModuleTest, AaFwk_DataAbilityOperation_UpdateBuilder_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_UpdateBuilder_0100"; + + std::shared_ptr application = std::make_shared(); + sptr abilityToken = sptr(new AbilityThread()); + EXPECT_NE(abilityToken, nullptr); + if (abilityToken != nullptr) { + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AppExecFwk::AbilityType::DATA; + abilityInfo->name = "DemoAbility"; + std::shared_ptr abilityRecord = + std::make_shared(abilityInfo, abilityToken); + + AbilityThread::AbilityThreadMain(application, abilityRecord); + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); + std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); + + EXPECT_NE(helper, nullptr); + std::shared_ptr values = std::make_shared(); + std::shared_ptr predicates = std::make_shared(); + std::shared_ptr operation = DataAbilityOperation::NewUpdateBuilder(uri) + ->WithValuesBucket(values) + ->WithPredicatesBackReference(0, 0) + ->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); + } + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_UpdateBuilder_0100"; +} + +/** + * @tc.number: AaFwk_DataAbilityOperation_AssertBuilder_0100 + * @tc.name: DataAbilityOperation + * @tc.desc: Get the file types in the dataability. + + */ +HWTEST_F(DataAbilityOperationModuleTest, AaFwk_DataAbilityOperation_AssertBuilder_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_AssertBuilder_0100"; + + std::shared_ptr application = std::make_shared(); + sptr abilityToken = sptr(new AbilityThread()); + EXPECT_NE(abilityToken, nullptr); + if (abilityToken != nullptr) { + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AppExecFwk::AbilityType::DATA; + abilityInfo->name = "DemoAbility"; + std::shared_ptr abilityRecord = + std::make_shared(abilityInfo, abilityToken); + + AbilityThread::AbilityThreadMain(application, abilityRecord); + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); + std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); + + EXPECT_NE(helper, nullptr); + + std::shared_ptr operation = + DataAbilityOperation::NewAssertBuilder(uri)->WithExpectedCount(2)->Build(); + EXPECT_NE(operation, nullptr); + + bool isAssertOperation = operation->IsAssertOperation(); + EXPECT_TRUE(isAssertOperation); + + int count = operation->GetExpectedCount(); + EXPECT_EQ(count, 2); + } + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_AssertBuilder_0100"; +} + +/** + * @tc.number: AaFwk_DataAbilityOperation_DeleteBuilder_0100 + * @tc.name: DataAbilityOperation + * @tc.desc: Get the file types in the dataability. + + */ +HWTEST_F(DataAbilityOperationModuleTest, AaFwk_DataAbilityOperation_DeleteBuilder_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_DeleteBuilder_0100"; + + std::shared_ptr application = std::make_shared(); + sptr abilityToken = sptr(new AbilityThread()); + EXPECT_NE(abilityToken, nullptr); + if (abilityToken != nullptr) { + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AppExecFwk::AbilityType::DATA; + abilityInfo->name = "DemoAbility"; + std::shared_ptr abilityRecord = + std::make_shared(abilityInfo, abilityToken); + + AbilityThread::AbilityThreadMain(application, abilityRecord); + + std::shared_ptr context = std::make_shared(); + std::shared_ptr uri = std::make_shared("dataability://com.example.myapplication5.DataAbilityTest"); + std::shared_ptr helper = DataAbilityHelper::Creator(context, uri, true); + EXPECT_NE(helper, nullptr); + std::shared_ptr predicates = std::make_shared(); + EXPECT_NE(predicates, nullptr); + std::shared_ptr builder = DataAbilityOperation::NewDeleteBuilder(uri); + EXPECT_NE(builder, nullptr); + std::shared_ptr operation = builder->WithPredicates(predicates)->Build(); + EXPECT_NE(operation, nullptr); + bool isDeleteOperation = operation->IsDeleteOperation(); + EXPECT_TRUE(isDeleteOperation); + } + GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_DeleteBuilder_0100"; +} + +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/ability_manager/include/ability_manager_client.h b/interfaces/innerkits/ability_manager/include/ability_manager_client.h index fd2d98b2aa0a7b502b76a853759929aae50789da..f5955a07581f19ad2dd6380b6e39e12d3ff643a6 100644 --- a/interfaces/innerkits/ability_manager/include/ability_manager_client.h +++ b/interfaces/innerkits/ability_manager/include/ability_manager_client.h @@ -307,6 +307,23 @@ public: */ ErrCode UnlockMission(int missionId); + /** + * Sets description information about the mission containing this ability. + * + * @param missionDescriptionInfo Indicates the object containing information about the + * mission. This parameter cannot be null. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode SetMissionDescriptionInfo( + const sptr &token, const MissionDescriptionInfo &missionDescriptionInfo); + + /** + * get current system mission lock mode state. + * + * @return Returns 0: LOCK_MISSION_STATE_NONE, 1: LOCK_MISSION_STATE_LOCKED + */ + int GetMissionLockModeState(); + sptr GetWantSender(const WantSenderInfo &wantSenderInfo, const sptr &callerToken); ErrCode SendWantSender(const sptr &target, const SenderInfo &senderInfo); diff --git a/interfaces/innerkits/ability_manager/include/ability_manager_errors.h b/interfaces/innerkits/ability_manager/include/ability_manager_errors.h index 9ed5c9b3c058c24ca1ae47035abb9129ddb3be1c..90e10ab1b1fb81a4f64cd6e5194448c0684b491a 100644 --- a/interfaces/innerkits/ability_manager/include/ability_manager_errors.h +++ b/interfaces/innerkits/ability_manager/include/ability_manager_errors.h @@ -199,6 +199,16 @@ enum { * Result(2097191) for unlock mission errors. */ UNLOCK_MISSION_DENY_FAILED, + + /** + * Result(2097192) for set mission info errors. + */ + SET_MISSION_INFO_FAILED, + + /** + * Result(2097193) for system is lock mission state. + */ + LOCK_MISSION_STATE_DENY_REQUEST, }; enum { diff --git a/interfaces/innerkits/ability_manager/include/ability_manager_interface.h b/interfaces/innerkits/ability_manager/include/ability_manager_interface.h index a63b4d9ae33bca4e379602a92a8338b13595d321..17930e108b3b139ee07527c388f42bca2fbc70c0 100644 --- a/interfaces/innerkits/ability_manager/include/ability_manager_interface.h +++ b/interfaces/innerkits/ability_manager/include/ability_manager_interface.h @@ -330,6 +330,23 @@ public: */ virtual int UnlockMission(int missionId) = 0; + /** + * Sets description information about the mission containing this ability. + * + * @param missionDescriptionInfo Indicates the object containing information about the + * mission. This parameter cannot be null. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int SetMissionDescriptionInfo( + const sptr &token, const MissionDescriptionInfo &missionDescriptionInfo) = 0; + + /** + * get current system mission lock mode state. + * + * @return Returns 0: LOCK_MISSION_STATE_NONE, 1: LOCK_MISSION_STATE_LOCKED + */ + virtual int GetMissionLockModeState() = 0; + virtual sptr GetWantSender( const WantSenderInfo &wantSenderInfo, const sptr &callerToken) = 0; @@ -433,6 +450,12 @@ public: // ipc id for unluck mission (34) UNLUCK_MISSION, + // ipc id for set mission info (35) + SET_MISSION_INFO, + + // ipc id for get mission lock mode state (36) + GET_MISSION_LOCK_MODE_STATE, + // 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 99c98545fc8dbb4abbb5cda4bcadbd353e6fa076..989987c702157c7297fa647283d6c6ca0ef02b82 100644 --- a/interfaces/innerkits/ability_manager/include/ability_scheduler_interface.h +++ b/interfaces/innerkits/ability_manager/include/ability_scheduler_interface.h @@ -196,12 +196,6 @@ public: */ virtual int BatchInsert(const Uri &uri, const std::vector &values) = 0; - /** - * @brief Displays a system-defined message to the user, prompting the user how to exit the lock mission mode. - * - */ - virtual void DisplayUnlockMissionMessage() = 0; - enum { // ipc id for scheduling ability to a state of life cycle SCHEDULE_ABILITY_TRANSACTION = 0, diff --git a/interfaces/innerkits/want/include/ohos/aafwk/content/operation.h b/interfaces/innerkits/want/include/ohos/aafwk/content/operation.h index d5bf165d979f927a67a51aa44c7e979cba862b00..5ae563f548ae6d03bb128025541ec9d589c71428 100644 --- a/interfaces/innerkits/want/include/ohos/aafwk/content/operation.h +++ b/interfaces/innerkits/want/include/ohos/aafwk/content/operation.h @@ -82,6 +82,8 @@ public: bool Marshalling(Parcel &parcel) const; static Operation *Unmarshalling(Parcel &parcel); + void DumpInfo(int level) const; + private: /** * @description: Sets a flag in a Want. diff --git a/interfaces/innerkits/want/include/ohos/aafwk/content/want.h b/interfaces/innerkits/want/include/ohos/aafwk/content/want.h index c71b6c21ec975ce9062c1d2f73d70dc4167c2aed..e62364b6927dacf6a716793d4e4d8af92d313aeb 100755 --- a/interfaces/innerkits/want/include/ohos/aafwk/content/want.h +++ b/interfaces/innerkits/want/include/ohos/aafwk/content/want.h @@ -747,6 +747,8 @@ public: */ static Want *Unmarshalling(Parcel &parcel); + void DumpInfo(int level) const; + public: // action definition static const std::string ACTION_PLAY; diff --git a/interfaces/innerkits/want/include/ohos/aafwk/content/want_params.h b/interfaces/innerkits/want/include/ohos/aafwk/content/want_params.h index e5a77a31e6556a9e9ecb9a8ca9909ec25be6a050..eaea0d693496198b2aad35953c4348e53123b2d8 100755 --- a/interfaces/innerkits/want/include/ohos/aafwk/content/want_params.h +++ b/interfaces/innerkits/want/include/ohos/aafwk/content/want_params.h @@ -64,6 +64,8 @@ public: static WantParams *Unmarshalling(Parcel &parcel); + void DumpInfo(int level) const; + private: enum { VALUE_TYPE_NULL = -1, diff --git a/interfaces/kits/napi/BUILD.gn b/interfaces/kits/napi/BUILD.gn old mode 100644 new mode 100755 index 40cb8e18ca42a42b2d7fcf1a42d00e7be3ec08b8..ca3fe779c285fddeebde61c146065dfc72253ad3 --- a/interfaces/kits/napi/BUILD.gn +++ b/interfaces/kits/napi/BUILD.gn @@ -18,6 +18,7 @@ group("napi_packages") { "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/abilityManager:abilitymanager", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/dataUriUtils:datauriutils", "//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/wantConstant:wantconstant", ] } diff --git a/interfaces/kits/napi/aafwk/dataUriUtils/BUILD.gn b/interfaces/kits/napi/aafwk/dataUriUtils/BUILD.gn old mode 100644 new mode 100755 index cb4a8f942afe6cf1196ea72d4927a69af5005b08..4150e48cc61edf7f8bf6f4b5d8030002b3343362 --- a/interfaces/kits/napi/aafwk/dataUriUtils/BUILD.gn +++ b/interfaces/kits/napi/aafwk/dataUriUtils/BUILD.gn @@ -20,6 +20,7 @@ ohos_shared_library("datauriutils") { "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/dataUriUtils", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility", "//third_party/node/src", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common", ] sources = [ diff --git a/interfaces/kits/napi/aafwk/featureAbility/BUILD.gn b/interfaces/kits/napi/aafwk/featureAbility/BUILD.gn old mode 100644 new mode 100755 index 21e7d63a49581b6ea05ceda7861ee74538c51e11..89e899452f7e6a706cf9bebc801055c24420e320 --- a/interfaces/kits/napi/aafwk/featureAbility/BUILD.gn +++ b/interfaces/kits/napi/aafwk/featureAbility/BUILD.gn @@ -20,6 +20,7 @@ ohos_shared_library("featureability") { "//third_party/libuv/include", "//foundation/aafwk/standard/frameworks/kits/ability/native/include", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common", ] sources = [ @@ -27,12 +28,12 @@ ohos_shared_library("featureability") { "napi_context.cpp", "napi_data_ability_helper.cpp", "native_module.cpp", - "want_wrapper.cpp", ] deps = [ "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", "//foundation/ace/napi:ace_napi", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", diff --git a/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp b/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp old mode 100644 new mode 100755 index 7fc77c40ce793ab34acfbb38cc7af2d75a8bbfb5..dad2a33f8ccc52c37608cdfac623957371c69164 --- a/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp +++ b/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp @@ -18,7 +18,6 @@ #include #include "securec.h" #include "ability_process.h" -#include "want_wrapper.h" #include "hilog_wrapper.h" #include "napi_context.h" #include "element_name.h" @@ -170,13 +169,13 @@ napi_value StartAbilityAsync( AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; napi_value callback = 0; napi_value undefined = 0; - napi_value result[ARGS2] = {0}; + napi_value result[ARGS_TWO] = {0}; napi_value callResult = 0; napi_get_undefined(env, &undefined); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); napi_create_int32(env, 0, &result[PARAM1]); napi_get_reference_value(env, asyncCallbackInfo->cbInfo.callback, &callback); - napi_call_function(env, undefined, callback, ARGS2, &result[PARAM0], &callResult); + napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); if (asyncCallbackInfo->cbInfo.callback != nullptr) { napi_delete_reference(env, asyncCallbackInfo->cbInfo.callback); @@ -347,13 +346,13 @@ napi_value StartAbilityForResultAsync( AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; napi_value callback = 0; napi_value undefined = 0; - napi_value result[ARGS2] = {0}; + napi_value result[ARGS_TWO] = {0}; napi_value callResult = 0; napi_get_undefined(env, &undefined); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); napi_create_int32(env, 0, &result[PARAM1]); napi_get_reference_value(env, asyncCallbackInfo->cbInfo.callback, &callback); - napi_call_function(env, undefined, callback, ARGS2, &result[PARAM0], &callResult); + napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); if (asyncCallbackInfo->cbInfo.callback != nullptr) { napi_delete_reference(env, asyncCallbackInfo->cbInfo.callback); @@ -508,7 +507,7 @@ napi_value SetResultAsync( [](napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_SetResult, main event thread complete."); AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; - napi_value result[ARGS2] = {0}; + napi_value result[ARGS_TWO] = {0}; napi_value callback = 0; napi_value undefined = 0; napi_value callResult = 0; @@ -516,7 +515,7 @@ napi_value SetResultAsync( result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); napi_get_null(env, &result[PARAM1]); napi_get_reference_value(env, asyncCallbackInfo->cbInfo.callback, &callback); - napi_call_function(env, undefined, callback, ARGS2, &result[PARAM0], &callResult); + napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); if (asyncCallbackInfo->cbInfo.callback != nullptr) { napi_delete_reference(env, asyncCallbackInfo->cbInfo.callback); @@ -669,13 +668,13 @@ napi_value TerminateAbilityAsync( AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; napi_value callback = 0; napi_value undefined = 0; - napi_value result[ARGS2] = {0}; + napi_value result[ARGS_TWO] = {0}; napi_value callResult = 0; napi_get_undefined(env, &undefined); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); napi_get_null(env, &result[PARAM1]); napi_get_reference_value(env, asyncCallbackInfo->cbInfo.callback, &callback); - napi_call_function(env, undefined, callback, ARGS2, &result[PARAM0], &callResult); + napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); if (asyncCallbackInfo->cbInfo.callback != nullptr) { napi_delete_reference(env, asyncCallbackInfo->cbInfo.callback); @@ -847,13 +846,13 @@ napi_value GetContextAsync( AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; napi_value callback = 0; napi_value undefined = 0; - napi_value result[ARGS2] = {0}; + napi_value result[ARGS_TWO] = {0}; napi_value callResult = 0; napi_get_undefined(env, &undefined); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); napi_new_instance(env, g_classContext, 0, nullptr, &result[PARAM1]); napi_get_reference_value(env, asyncCallbackInfo->cbInfo.callback, &callback); - napi_call_function(env, undefined, callback, ARGS2, &result[PARAM0], &callResult); + napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); if (asyncCallbackInfo->cbInfo.callback != nullptr) { napi_delete_reference(env, asyncCallbackInfo->cbInfo.callback); @@ -975,13 +974,13 @@ napi_value HasWindowFocusAsync( AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; napi_value callback = 0; napi_value undefined = 0; - napi_value result[ARGS2] = {0}; + napi_value result[ARGS_TWO] = {0}; napi_value callResult = 0; napi_get_undefined(env, &undefined); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); napi_get_boolean(env, asyncCallbackInfo->native_result, &result[PARAM1]); napi_get_reference_value(env, asyncCallbackInfo->cbInfo.callback, &callback); - napi_call_function(env, undefined, callback, ARGS2, &result[PARAM0], &callResult); + napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); if (asyncCallbackInfo->cbInfo.callback != nullptr) { napi_delete_reference(env, asyncCallbackInfo->cbInfo.callback); @@ -1077,7 +1076,7 @@ void CallOnAbilityResult(int requestCode, int resultCode, const Want &resultData HILOG_INFO("CallOnAbilityResult, uv_queue_work"); // JS Thread OnAbilityCallback *event = (OnAbilityCallback *)work->data; - napi_value result[ARGS2] = {0}; + napi_value result[ARGS_TWO] = {0}; result[PARAM0] = GetCallbackErrorValue(event->cb.env, NO_ERROR); napi_create_object(event->cb.env, &result[PARAM1]); @@ -1089,7 +1088,7 @@ void CallOnAbilityResult(int requestCode, int resultCode, const Want &resultData napi_create_int32(event->cb.env, event->resultCode, &jsValue); napi_set_named_property(event->cb.env, result[PARAM1], "resultCode", jsValue); // create want - napi_value jsWant = WrapWant(event->resultData, event->cb.env); + napi_value jsWant = WrapWant(event->cb.env, event->resultData); napi_set_named_property(event->cb.env, result[PARAM1], "want", jsWant); napi_value callback = 0; napi_value undefined = 0; @@ -1097,7 +1096,7 @@ void CallOnAbilityResult(int requestCode, int resultCode, const Want &resultData napi_value callResult = 0; napi_get_reference_value(event->cb.env, event->cb.callback, &callback); - napi_call_function(event->cb.env, undefined, callback, ARGS2, &result[PARAM0], &callResult); + napi_call_function(event->cb.env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); if (event->cb.callback != nullptr) { napi_delete_reference(event->cb.env, event->cb.callback); } @@ -1108,6 +1107,23 @@ void CallOnAbilityResult(int requestCode, int resultCode, const Want &resultData return; } +bool InnerUnwrapWant(napi_env env, napi_value args, Want &want) +{ + HILOG_INFO("%{public}s called", __func__); + napi_valuetype valueType = napi_undefined; + NAPI_CALL_BASE(env, napi_typeof(env, args, &valueType), false); + if (valueType != napi_object) { + return false; + } + + napi_value jsWant = GetPropertyValueByPropertyName(env, args, "want", napi_object); + if (jsWant == nullptr) { + return false; + } + + return UnwrapWant(env, jsWant, want); +} + /** * @brief Parse the parameters. * @@ -1124,7 +1140,7 @@ napi_value UnwrapParam(CallAbilityParam ¶m, napi_env env, napi_value args) napi_valuetype valueType = napi_undefined; // unwrap the param : want object - UnwrapWant(param.want, env, args); + InnerUnwrapWant(env, args, param.want); // unwrap the param : requestCode (optional) napi_value requestCodeProp = nullptr; @@ -1181,7 +1197,7 @@ napi_value UnwrapAbilityResult(CallAbilityParam ¶m, napi_env env, napi_value HILOG_INFO("%{public}s, requestCode=%{public}d.", __func__, param.requestCode); // unwrap the param : want object - UnwrapWant(param.want, env, args); + InnerUnwrapWant(env, args, param.want); napi_value result; NAPI_CALL(env, napi_create_int32(env, 1, &result)); @@ -1251,13 +1267,13 @@ napi_value GetWantAsync( AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; napi_value callback = 0; napi_value undefined = 0; - napi_value result[ARGS2] = {0}; + napi_value result[ARGS_TWO] = {0}; napi_value callResult = 0; napi_get_undefined(env, &undefined); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); - result[PARAM1] = WrapWant(asyncCallbackInfo->param.want, env); + result[PARAM1] = WrapWant(env, asyncCallbackInfo->param.want); napi_get_reference_value(env, asyncCallbackInfo->cbInfo.callback, &callback); - napi_call_function(env, undefined, callback, ARGS2, &result[PARAM0], &callResult); + napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); if (asyncCallbackInfo->cbInfo.callback != nullptr) { napi_delete_reference(env, asyncCallbackInfo->cbInfo.callback); @@ -1307,7 +1323,7 @@ napi_value GetWantPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) [](napi_env env, napi_status status, void *data) { HILOG_INFO("GetWantPromise, main event thread complete."); AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; - napi_value result = WrapWant(asyncCallbackInfo->param.want, env); + napi_value result = WrapWant(env, asyncCallbackInfo->param.want); napi_resolve_deferred(env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; @@ -1605,13 +1621,13 @@ void GetAppInfoAsyncCompleteCB(napi_env env, napi_status status, void *data) AppInfoCB *appInfoCB = (AppInfoCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; - napi_value result[ARGS2] = {nullptr}; + napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); result[PARAM1] = WrapAppInfo(env, appInfoCB->appInfo); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, appInfoCB->cbBase.cbInfo.callback, &callback)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS2, &result[PARAM0], &callResult)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (appInfoCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, appInfoCB->cbBase.cbInfo.callback)); @@ -1901,7 +1917,7 @@ void GetAppTypeAsyncCompleteCB(napi_env env, napi_status status, void *data) AppTypeCB *appTypeCB = (AppTypeCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; - napi_value result[ARGS2] = {nullptr}; + napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); @@ -1912,7 +1928,7 @@ void GetAppTypeAsyncCompleteCB(napi_env env, napi_status status, void *data) env, appTypeCB->cbBase.ability->GetAppType().c_str(), NAPI_AUTO_LENGTH, &result[PARAM1])); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, appTypeCB->cbBase.cbInfo.callback, &callback)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS2, &result[PARAM0], &callResult)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (appTypeCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, appTypeCB->cbBase.cbInfo.callback)); @@ -2141,13 +2157,13 @@ void GetElementNameAsyncCompleteCB(napi_env env, napi_status status, void *data) ElementNameCB *elementNameCB = (ElementNameCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; - napi_value result[ARGS2] = {nullptr}; + napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); result[PARAM1] = WrapElementName(env, elementNameCB); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, elementNameCB->cbBase.cbInfo.callback, &callback)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS2, &result[PARAM0], &callResult)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (elementNameCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, elementNameCB->cbBase.cbInfo.callback)); @@ -2939,13 +2955,13 @@ void GetAbilityNameAsyncCompleteCB(napi_env env, napi_status status, void *data) AbilityNameCB *abilityNameCB = (AbilityNameCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; - napi_value result[ARGS2] = {nullptr}; + napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); result[PARAM1] = WrapAbilityName(env, abilityNameCB); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, abilityNameCB->cbBase.cbInfo.callback, &callback)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS2, &result[PARAM0], &callResult)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (abilityNameCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, abilityNameCB->cbBase.cbInfo.callback)); } @@ -2966,14 +2982,14 @@ void GetProcessInfoAsyncCompleteCB(napi_env env, napi_status status, void *data) ProcessInfoCB *processInfoCB = (ProcessInfoCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; - napi_value result[ARGS2] = {nullptr}; + napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); result[PARAM1] = WrapProcessInfo(env, processInfoCB); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, processInfoCB->cbBase.cbInfo.callback, &callback)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS2, &result[PARAM0], &callResult)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (processInfoCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, processInfoCB->cbBase.cbInfo.callback)); @@ -2995,13 +3011,13 @@ void GetProcessNameAsyncCompleteCB(napi_env env, napi_status status, void *data) ProcessNameCB *processNameCB = (ProcessNameCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; - napi_value result[ARGS2] = {nullptr}; + napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); result[PARAM1] = WrapProcessName(env, processNameCB); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, processNameCB->cbBase.cbInfo.callback, &callback)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS2, &result[PARAM0], &callResult)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (processNameCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, processNameCB->cbBase.cbInfo.callback)); @@ -3023,13 +3039,13 @@ void GetCallingBundleAsyncCompleteCB(napi_env env, napi_status status, void *dat CallingBundleCB *callingBundleCB = (CallingBundleCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; - napi_value result[ARGS2] = {nullptr}; + napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); result[PARAM1] = WrapCallingBundle(env, callingBundleCB); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, callingBundleCB->cbBase.cbInfo.callback, &callback)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS2, &result[PARAM0], &callResult)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (callingBundleCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, callingBundleCB->cbBase.cbInfo.callback)); @@ -3401,13 +3417,13 @@ void GetAbilityInfoAsyncCompleteCB(napi_env env, napi_status status, void *data) AbilityInfoCB *abilityInfoCB = (AbilityInfoCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; - napi_value result[ARGS2] = {nullptr}; + napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); result[PARAM1] = WrapAbilityInfo(env, abilityInfoCB->abilityInfo); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, abilityInfoCB->cbBase.cbInfo.callback, &callback)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS2, &result[PARAM0], &callResult)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (abilityInfoCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, abilityInfoCB->cbBase.cbInfo.callback)); @@ -3752,13 +3768,13 @@ void GetHapModuleInfoAsyncCompleteCB(napi_env env, napi_status status, void *dat HapModuleInfoCB *hapModuleInfoCB = (HapModuleInfoCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; - napi_value result[ARGS2] = {nullptr}; + napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); result[PARAM1] = WrapHapModuleInfo(env, *hapModuleInfoCB); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, hapModuleInfoCB->cbBase.cbInfo.callback, &callback)); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS2, &result[PARAM0], &callResult)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (hapModuleInfoCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, hapModuleInfoCB->cbBase.cbInfo.callback)); @@ -3996,7 +4012,7 @@ void GetDataAbilityHelperAsyncCompleteCB(napi_env env, napi_status status, void napi_value uri = nullptr; napi_value callback = nullptr; napi_value undefined = nullptr; - napi_value result[ARGS2] = {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, dataAbilityHelperCB->uri, &uri)); @@ -4005,7 +4021,7 @@ void GetDataAbilityHelperAsyncCompleteCB(napi_env env, napi_status status, void result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); result[PARAM1] = dataAbilityHelperCB->result; - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS2, &result[PARAM0], &callResult)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); if (dataAbilityHelperCB->cbBase.cbInfo.callback != nullptr) { NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, dataAbilityHelperCB->cbBase.cbInfo.callback)); diff --git a/interfaces/kits/napi/aafwk/featureAbility/feature_ability_common.h b/interfaces/kits/napi/aafwk/featureAbility/feature_ability_common.h old mode 100644 new mode 100755 index 3ca200ca5cdd1cd7cdbe75ddf91d3c2c879b5322..51d3eeab10c68374f94ab9b0bc09648b5ad66961 --- a/interfaces/kits/napi/aafwk/featureAbility/feature_ability_common.h +++ b/interfaces/kits/napi/aafwk/featureAbility/feature_ability_common.h @@ -19,6 +19,7 @@ #include "napi/native_node_api.h" #include "ability.h" #include "want.h" +#include "../inner/napi_common/napi_common.h" #include "dummy_values_bucket.h" #include "dummy_data_ability_predicates.h" @@ -30,14 +31,6 @@ namespace OHOS { namespace AppExecFwk { class FeatureAbility; -#define ARGS_MAX_COUNT 10 -#define ARGS_ASYNC_COUNT 1 -#define ARGS1 1 -#define ARGS2 2 -#define ARGS3 3 -#define PARAM0 0 -#define PARAM1 1 -#define PARAM2 2 #define NO_ERROR 0 struct CallAbilityParam { @@ -47,10 +40,6 @@ struct CallAbilityParam { std::shared_ptr setting = nullptr; }; -struct CallbackInfo { - napi_env env; - napi_ref callback = 0; -}; struct OnAbilityCallback { int requestCode = 0; @@ -211,29 +200,8 @@ struct DAHelperInsertCB { static inline std::string NapiValueToStringUtf8(napi_env env, napi_value value) { std::string result = ""; - size_t size = 0; - - if (napi_get_value_string_utf8(env, value, nullptr, 0, &size) != napi_ok || size == 0) { - return ""; - } - - result.resize(size + 1); - if (napi_get_value_string_utf8(env, value, &result[0], result.size(), &size) != napi_ok) { - return ""; - } - return result; -} - -static inline napi_value GetCallbackErrorValue(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; + return UnwrapStringFromJS(env, value, result); } - } // namespace AppExecFwk } // namespace OHOS #endif /* OHOS_APPEXECFWK_FEATURE_ABILITY_COMMON_H */ diff --git a/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp b/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp old mode 100644 new mode 100755 index 629c029b4ec9f2482a6353b938b1c6bb0a565966..07096633dbe937efeaa809e3928b556d25030d2e --- a/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp +++ b/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp @@ -18,70 +18,17 @@ #include "napi_context.h" #include "hilog_wrapper.h" #include "ability_process.h" -#include "napi_error.h" #include "feature_ability_common.h" using namespace OHOS::AAFwk; using namespace OHOS::AppExecFwk; -#define PERMISSOIN_EVENT_VERIFYSELFPERMISSION 1 -#define PERMISSION_EVENT_REQUEST_PERMISSION 2 - namespace OHOS { namespace AppExecFwk { napi_value g_classContext; CallbackInfo aceCallbackInfoPermission; -static void VerifySelfPermissionExecuteCallback(napi_env env, void *data); -static void RequestPermissionsFromUserExecuteCallback(napi_env env, void *data); -static void RequestPermissionsFromUserExecutePromise(napi_env env, void *data); -static napi_value NAPI_RequestPermissionsFromUserWrap( - napi_env env, napi_callback_info info, AsyncPermissionCallbackInfo *asyncCallbackInfo); -static napi_value NAPI_VerifySelfPermissionWrap( - napi_env env, napi_callback_info info, AsyncPermissionCallbackInfo *asyncCallbackInfo); -static napi_value NAPI_VerifySelfPermission(napi_env env, napi_callback_info info); -static napi_value NAPI_RequestPermissionsFromUser(napi_env env, napi_callback_info info); -static napi_value NAPI_OnRequestPermissionsFromUserResultWrap( - napi_env env, napi_callback_info info, AsyncPermissionCallbackInfo *asyncCallbackInfo); -static napi_value NAPI_OnRequestPermissionsFromUserResult(napi_env env, napi_callback_info info); -static void GetBundleNameExecuteCallback(napi_env env, void *data); -static napi_value NAPI_GetBundleNameWrap( - napi_env env, napi_callback_info info, AsyncPermissionCallbackInfo *asyncCallbackInfo); -static napi_value NAPI_GetBundleName(napi_env env, napi_callback_info info); - -/** - * @brief Context 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 ContextPermissionInit(napi_env env, napi_value exports) -{ - HILOG_INFO("Context::ContextPermissionInit called."); - - napi_property_descriptor properties[] = { - DECLARE_NAPI_FUNCTION("verifySelfPermission", NAPI_VerifySelfPermission), - DECLARE_NAPI_FUNCTION("requestPermissionsFromUser", NAPI_RequestPermissionsFromUser), - DECLARE_NAPI_FUNCTION("onRequestPermissionsFromUserResult", NAPI_OnRequestPermissionsFromUserResult), - DECLARE_NAPI_FUNCTION("getBundleName", NAPI_GetBundleName), - }; - - NAPI_CALL(env, - napi_define_class(env, - "context", - NAPI_AUTO_LENGTH, - ContextConstructor, - nullptr, - sizeof(properties) / sizeof(*properties), - properties, - &g_classContext)); - - return exports; -} - napi_value ContextConstructor(napi_env env, napi_callback_info info) { napi_value jsthis = nullptr; @@ -89,366 +36,54 @@ napi_value ContextConstructor(napi_env env, napi_callback_info info) return jsthis; } -void ClearNativeData(ThreadReturnData *data) -{ - if (data != nullptr) { - data->data_type = NVT_NONE; - data->int32_value = 0; - data->bool_value = false; - data->str_value = ""; - } -} - -/** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * - * @return Return a pointer to AsyncPermissionCallbackInfo on success, nullptr on failure - */ -AsyncPermissionCallbackInfo *CreateAsyncPermissionCallbackInfo(napi_env env) +bool UnwrapParamVerifySelfPermission( + napi_env env, size_t argc, napi_value *argv, AsyncJSCallbackInfo *asyncCallbackInfo) { - napi_value global = 0; - NAPI_CALL(env, napi_get_global(env, &global)); - - napi_value abilityObj = 0; - NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); + HILOG_INFO("%{public}s called, argc=%{public}d", __func__, argc); - Ability *ability = nullptr; - NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); - - AsyncPermissionCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncPermissionCallbackInfo{ - .env = env, - .asyncWork = nullptr, - .deferred = nullptr, - .ability = ability, - .aceCallback = nullptr, - }; - if (asyncCallbackInfo != nullptr) { - ClearNativeData(&asyncCallbackInfo->native_data); + const size_t argcMax = 2; + if (argc > argcMax || argc < argcMax - 1) { + HILOG_INFO("%{public}s called, Params is invalid.", __func__); + return false; } - return asyncCallbackInfo; -} -/** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * @param argc Number of parameters. - * @param startIndex The position of the first event parameter. - * @param args Parameter list. - * @param callback Point to asynchronous processing of data. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value CreateAsyncCallback( - napi_env env, size_t argc, size_t startIndex, napi_value *args, AsyncPermissionCallbackInfo *callback) -{ - if (args == nullptr) { - return nullptr; - } - - size_t argCount = (argc - startIndex > PERMISSION_EVENT_SIZE) ? (startIndex + PERMISSION_EVENT_SIZE) : argc; - - for (size_t i = startIndex; i < argCount; i++) { - napi_valuetype valueType = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[i], &valueType)); - NAPI_ASSERT(env, valueType == napi_function, "Wrong argument type. Function expected."); - NAPI_CALL(env, napi_create_reference(env, args[i], 1, &callback->callback[i - startIndex])); - } - - napi_value result = 0; - NAPI_CALL(env, napi_create_int32(env, 1, &result)); - return result; -} - -/** - * @brief Parse JS string parameters. - * - * @param env The environment that the Node-API call is invoked under. - * @param value Return stirng value. - * @param args Parameter list. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value UnwrapParamString(std::vector &value, napi_env env, napi_value args) -{ - HILOG_INFO("Context::UnwrapParamString in."); - char buf[PERMISSION_C_BUFFER_SIZE] = {0}; - size_t len = 0; - - // unwrap the param : permission - memset_s(buf, sizeof(buf), 0x0, sizeof(buf)); - NAPI_CALL(env, napi_get_value_string_utf8(env, args, buf, PERMISSION_C_BUFFER_SIZE, &len)); - value.push_back(std::string(buf)); - HILOG_INFO("Context::UnwrapParamString permission=%{public}s.", buf); - - // create result code - napi_value result = 0; - NAPI_CALL(env, napi_create_int32(env, 1, &result)); - return result; -} - -/** - * @brief Parse JS numeric parameters. - * - * @param env The environment that the Node-API call is invoked under. - * @param value Return integer value. - * @param args Parameter list. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value UnwrapParamInt(int *value, napi_env env, napi_value args) -{ - if (value == nullptr) { - HILOG_INFO("Invalid param(value = nullptr)"); - return nullptr; - } - - napi_valuetype valueType = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args, &valueType)); - NAPI_ASSERT(env, valueType == napi_number, "property type mismatch! Expected to be a int32"); - - int32_t value32 = 0; - NAPI_CALL(env, napi_get_value_int32(env, args, &value32)); - HILOG_INFO("UnwrapParamInt value=%{public}d", value32); - *value = value32; - napi_value result = 0; - NAPI_CALL(env, napi_create_int32(env, 1, &result)); - return result; -} - -/** - * @brief Parse JS array of string parameters. - * - * @param env The environment that the Node-API call is invoked under. - * @param value Return array of stirng value. - * @param args Parameter list. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value UnwrapParamArrayString(std::vector &value, napi_env env, napi_value args) -{ - value.clear(); - char buf[PERMISSION_C_BUFFER_SIZE] = {0}; - size_t len = 0; - napi_valuetype valueType = napi_undefined; - - bool isArray = false; - uint32_t arrayLength = 0; - napi_value valueArray = 0; - - NAPI_CALL(env, napi_is_array(env, args, &isArray)); - if (!isArray) { - HILOG_INFO("property type mismatch"); - return nullptr; + if (argc == argcMax) { + if (!CreateAsyncCallback(env, argv[PARAM1], asyncCallbackInfo)) { + HILOG_INFO("%{public}s called, the second parameter is invalid.", __func__); + return false; + } } - NAPI_CALL(env, napi_get_array_length(env, args, &arrayLength)); - HILOG_INFO("property is array, length=%{public}d", arrayLength); - - for (uint32_t i = 0; i < arrayLength; i++) { - memset_s(buf, sizeof(buf), 0x0, sizeof(buf)); - - NAPI_CALL(env, napi_get_element(env, args, i, &valueArray)); - NAPI_CALL(env, napi_typeof(env, valueArray, &valueType)); - NAPI_ASSERT(env, valueType == napi_string, "property value type mismatch, Expected to be a string!"); - - NAPI_CALL(env, napi_get_value_string_utf8(env, valueArray, buf, PERMISSION_C_BUFFER_SIZE, &len)); - HILOG_INFO("UnwrapParamInt array string value=%{public}s", buf); - - value.emplace_back(std::string(buf)); + std::string permission(""); + if (!UnwrapStringFromJS2(env, argv[PARAM0], permission)) { + HILOG_INFO("%{public}s called, the first parameter is invalid.", __func__); + return false; } - napi_value result = 0; - NAPI_CALL(env, napi_create_int32(env, 1, &result)); - return result; + asyncCallbackInfo->param.paramArgs.PutStringValue("permission", permission); + return true; } -/** - * @brief Convert local data to JS data. - * - * @param env The environment that the Node-API call is invoked under. - * @param data The local data. - * @param value the JS data. - * - * @return The return value from NAPI C++ to JS for the module. - */ -void NAPI_GetNapiValue(napi_env env, const ThreadReturnData *data, napi_value *value) +void VerifySelfPermissionExecuteCallbackWork(napi_env env, void *data) { - if (data == nullptr || value == nullptr) { - return; - } - switch (data->data_type) { - case NVT_INT32: - napi_create_int32(env, data->int32_value, value); - break; - case NVT_BOOL: - napi_create_int32(env, data->bool_value ? 1 : 0, value); - break; - case NVT_STRING: - napi_create_string_utf8(env, data->str_value.c_str(), NAPI_AUTO_LENGTH, value); - break; - default: - napi_get_null(env, value); - break; - } -} + HILOG_INFO("%{public}s called.", __func__); -/** - * @brief VerifySelfPermission asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void VerifySelfPermissionExecuteCallback(napi_env env, void *data) -{ - HILOG_INFO("Context::NAPI_VerifySelfPermission worker pool thread execute."); - - AsyncPermissionCallbackInfo *asyncCallbackInfo = (AsyncPermissionCallbackInfo *)data; - if (asyncCallbackInfo != nullptr) { - int rev = -1; - if (asyncCallbackInfo->ability != nullptr && asyncCallbackInfo->param.permission_list.size() > 0) { - rev = asyncCallbackInfo->ability->VerifySelfPermission(asyncCallbackInfo->param.permission_list[0]); - } - - asyncCallbackInfo->native_data.data_type = NVT_INT32; - asyncCallbackInfo->native_data.int32_value = rev; - - asyncCallbackInfo->run_status = (rev == 0) ? true : false; - if (asyncCallbackInfo->run_status == false) { - asyncCallbackInfo->error_code = NAPI_ERR_NO_PERMISSION; - } - } -} - -/** - * @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 AsyncCompleteCallback(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("main event thread complete."); - AsyncPermissionCallbackInfo *asyncCallbackInfo = (AsyncPermissionCallbackInfo *)data; + AsyncJSCallbackInfo *asyncCallbackInfo = (AsyncJSCallbackInfo *)data; if (asyncCallbackInfo == nullptr) { + HILOG_INFO("%{public}s called. asyncCallbackInfo is null", __func__); return; } - napi_value callback = 0; - napi_value undefined = 0; - napi_get_undefined(env, &undefined); - napi_value callResult = 0; - napi_value rev[ARGS2] = {nullptr}; - - rev[PARAM0] = GetCallbackErrorValue(env, asyncCallbackInfo->error_code); - NAPI_GetNapiValue(env, &asyncCallbackInfo->native_data, &rev[PARAM1]); - if (asyncCallbackInfo->callback[0] != nullptr) { - napi_get_reference_value(env, asyncCallbackInfo->callback[0], &callback); - napi_call_function(env, undefined, callback, ARGS2, rev, &callResult); - napi_delete_reference(env, asyncCallbackInfo->callback[0]); - } + asyncCallbackInfo->error_code = NAPI_ERR_NO_ERROR; + asyncCallbackInfo->native_data.data_type = NVT_NONE; - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; -} - -/** - * @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 PromiseCompleteCallback(napi_env env, napi_status status, void *data) -{ - AsyncPermissionCallbackInfo *asyncCallbackInfo = (AsyncPermissionCallbackInfo *)data; - if (asyncCallbackInfo != nullptr) { - napi_value result = 0; - NAPI_GetNapiValue(env, &asyncCallbackInfo->native_data, &result); - napi_resolve_deferred(env, asyncCallbackInfo->deferred, result); - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; - } -} - -/** - * @brief Asynchronous callback processing. - * - * @param env The environment that the Node-API call is invoked under. - * @param args list of JS of param. - * @param asyncCallbackInfo Process data asynchronously. - * @param param other param. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value ExecuteAsyncCallback( - napi_env env, napi_value *args, AsyncPermissionCallbackInfo *asyncCallbackInfo, const AsyncParamEx *param) -{ - if (param == nullptr) { - return nullptr; - } - - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, param->resource.c_str(), NAPI_AUTO_LENGTH, &resourceName)); - if (CreateAsyncCallback(env, param->argc, param->startIndex, args, asyncCallbackInfo) == nullptr) { - return nullptr; - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - param->execute, - param->complete, - (void *)asyncCallbackInfo, - &asyncCallbackInfo->asyncWork)); - - NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); - - // create result code - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - - return result; -} - -/** - * @brief Asynchronous promise processing. - * - * @param env The environment that the Node-API call is invoked under. - * @param args list of JS of param. - * @param asyncCallbackInfo Process data asynchronously. - * @param param other param. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value ExecutePromiseCallback( - napi_env env, napi_value *args, AsyncPermissionCallbackInfo *asyncCallbackInfo, const AsyncParamEx *param) -{ - if (args == nullptr) { - return nullptr; + if (asyncCallbackInfo->ability == nullptr) { + asyncCallbackInfo->error_code = NAPI_ERR_ACE_ABILITY; + return; } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, param->resource.c_str(), NAPI_AUTO_LENGTH, &resourceName)); - - napi_deferred deferred = 0; - 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, - param->execute, - param->complete, - (void *)asyncCallbackInfo, - &asyncCallbackInfo->asyncWork)); - - NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); - return promise; + std::string permission(asyncCallbackInfo->param.paramArgs.GetStringValue("permission")); + asyncCallbackInfo->native_data.int32_value = asyncCallbackInfo->ability->VerifySelfPermission(permission); } /** @@ -459,41 +94,36 @@ napi_value ExecutePromiseCallback( * * @return Return JS data successfully, otherwise return nullptr. */ -napi_value NAPI_VerifySelfPermissionWrap( - napi_env env, napi_callback_info info, AsyncPermissionCallbackInfo *asyncCallbackInfo) +napi_value NAPI_VerifySelfPermissionWrap(napi_env env, napi_callback_info info, AsyncJSCallbackInfo *asyncCallbackInfo) { - size_t argc = 3; - const size_t argCount = 1; - napi_value args[PERMISSION_ARGS_SIZE] = {nullptr}; + HILOG_INFO("%{public}s called.", __func__); + size_t argc = ARGS_MAX_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; napi_value jsthis = 0; void *data = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &jsthis, &data)); - CallAbilityPermissionParam param; - if (UnwrapParamString(param.permission_list, env, args[0]) == nullptr) { + if (!UnwrapParamVerifySelfPermission(env, argc, args, asyncCallbackInfo)) { + HILOG_INFO("%{public}s called. Invoke UnwrapParamVerifySelfPermission fail", __func__); return nullptr; } - asyncCallbackInfo->param = param; AsyncParamEx asyncParamEx; - asyncParamEx.argc = argc; - - if (argc > argCount) { - HILOG_INFO("Context::NAPI_VerifySelfPermission asyncCallback."); - asyncParamEx.resource = "NAPI_VerifySelfPermission1"; - asyncParamEx.startIndex = PERMISSOIN_EVENT_VERIFYSELFPERMISSION; - asyncParamEx.execute = VerifySelfPermissionExecuteCallback; - asyncParamEx.complete = AsyncCompleteCallback; - return ExecuteAsyncCallback(env, args, asyncCallbackInfo, &asyncParamEx); + if (asyncCallbackInfo->cbInfo.callback != nullptr) { + HILOG_INFO("%{public}s called. asyncCallback.", __func__); + asyncParamEx.resource = "NAPI_VerifySelfPermissionCallback"; + asyncParamEx.execute = VerifySelfPermissionExecuteCallbackWork; + asyncParamEx.complete = CompleteAsyncCallbackWork; + + return ExecuteAsyncCallbackWork(env, asyncCallbackInfo, &asyncParamEx); } else { - HILOG_INFO("Context::NAPI_VerifySelfPermission promise."); - asyncParamEx.resource = "NAPI_VerifySelfPermission2"; - asyncParamEx.startIndex = 0; - asyncParamEx.execute = VerifySelfPermissionExecuteCallback; - asyncParamEx.complete = PromiseCompleteCallback; + HILOG_INFO("%{public}s called. promise.", __func__); + asyncParamEx.resource = "NAPI_VerifySelfPermissionPromise"; + asyncParamEx.execute = VerifySelfPermissionExecuteCallbackWork; + asyncParamEx.complete = CompletePromiseCallbackWork; - return ExecutePromiseCallback(env, args, asyncCallbackInfo, &asyncParamEx); + return ExecutePromiseCallbackWork(env, asyncCallbackInfo, &asyncParamEx); } } @@ -510,9 +140,9 @@ napi_value NAPI_VerifySelfPermissionWrap( */ napi_value NAPI_VerifySelfPermission(napi_env env, napi_callback_info info) { - HILOG_INFO("Context::NAPI_VerifySelfPermission. called."); + HILOG_INFO("%{public}s called.", __func__); - AsyncPermissionCallbackInfo *asyncCallbackInfo = CreateAsyncPermissionCallbackInfo(env); + AsyncJSCallbackInfo *asyncCallbackInfo = CreateAsyncJSCallbackInfo(env); if (asyncCallbackInfo == nullptr) { return nullptr; } @@ -521,40 +151,102 @@ napi_value NAPI_VerifySelfPermission(napi_env env, napi_callback_info info) if (rev == nullptr) { delete asyncCallbackInfo; asyncCallbackInfo = nullptr; - NAPI_CALL(env, napi_get_null(env, &rev)); + rev = WrapVoidToJS(env); } return rev; } -/** - * @brief RequestPermissionsFromUser asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void RequestPermissionsFromUserExecuteCallback(napi_env env, void *data) +bool UnwrapRequestPermissionsFromUser( + napi_env env, size_t argc, napi_value *argv, AsyncJSCallbackInfo *asyncCallbackInfo) { - HILOG_INFO("Context::NAPI_VerifySelfPermission worker pool thread execute."); - AsyncPermissionCallbackInfo *asyncCallbackInfo = (AsyncPermissionCallbackInfo *)data; - if (asyncCallbackInfo != nullptr) { - AbilityProcess::GetInstance()->RequestPermissionsFromUser( - asyncCallbackInfo->ability, asyncCallbackInfo->param, *asyncCallbackInfo->aceCallback); - asyncCallbackInfo->run_status = true; - asyncCallbackInfo->native_data.data_type = NVT_INT32; - asyncCallbackInfo->native_data.int32_value = 1; + HILOG_INFO("%{public}s called, argc=%{public}d", __func__, argc); + + const size_t argcMax = 3; + if (argc > argcMax || argc < argcMax - 1) { + HILOG_INFO("%{public}s called, parameters is invalid", __func__); + return false; + } + + if (argc == argcMax) { + if (!CreateAsyncCallback(env, argv[PARAM2], asyncCallbackInfo)) { + HILOG_INFO("%{public}s called, the second parameter is invalid.", __func__); + return false; + } + } + + std::vector permissionList; + if (!UnwrapArrayStringFromJS(env, argv[PARAM0], permissionList)) { + HILOG_INFO("%{public}s called, the first parameter is invalid.", __func__); + return false; + } + + int requestCode = 0; + if (!UnwrapInt32FromJS2(env, argv[PARAM1], requestCode)) { + HILOG_INFO("%{public}s called, the second parameter is invalid.", __func__); + return false; } + + asyncCallbackInfo->param.paramArgs.PutIntValue("requestCode", requestCode); + asyncCallbackInfo->param.paramArgs.PutStringValueArray("permissionList", permissionList); + return true; } -void RequestPermissionsFromUserExecutePromise(napi_env env, void *data) +void RequestPermissionsFromUserExecuteCallbackWork(napi_env env, void *data) { - HILOG_INFO("Context::NAPI_VerifySelfPermission worker pool thread execute."); - AsyncPermissionCallbackInfo *asyncCallbackInfo = (AsyncPermissionCallbackInfo *)data; - if (asyncCallbackInfo != nullptr) { - AbilityProcess::GetInstance()->RequestPermissionsFromUser( - asyncCallbackInfo->ability, asyncCallbackInfo->param, *asyncCallbackInfo->aceCallback); - asyncCallbackInfo->run_status = true; - asyncCallbackInfo->native_data.data_type = NVT_NONE; + HILOG_INFO("%{public}s called.", __func__); + AsyncJSCallbackInfo *asyncCallbackInfo = (AsyncJSCallbackInfo *)data; + if (asyncCallbackInfo == nullptr) { + HILOG_INFO("%{public}s called. asyncCallbackInfo is null", __func__); + return; } + + asyncCallbackInfo->error_code = NAPI_ERR_NO_ERROR; + asyncCallbackInfo->native_data.data_type = NVT_NONE; + if (asyncCallbackInfo->ability == nullptr) { + asyncCallbackInfo->error_code = NAPI_ERR_ACE_ABILITY; + return; + } + + CallAbilityPermissionParam permissionParam; + permissionParam.requestCode = asyncCallbackInfo->param.paramArgs.GetIntValue("requestCode"); + asyncCallbackInfo->param.paramArgs.GetStringValueArray("permissionList", permissionParam.permission_list); + if (permissionParam.permission_list.size() == 0) { + asyncCallbackInfo->error_code = NAPI_ERR_PARAM_INVALID; + return; + } + + AbilityProcess::GetInstance()->RequestPermissionsFromUser( + asyncCallbackInfo->ability, permissionParam, *asyncCallbackInfo->aceCallback); + asyncCallbackInfo->native_data.data_type = NVT_INT32; + asyncCallbackInfo->native_data.int32_value = 1; +} + +void RequestPermissionsFromUserExecutePromiseWork(napi_env env, void *data) +{ + HILOG_INFO("%{public}s called.", __func__); + AsyncJSCallbackInfo *asyncCallbackInfo = (AsyncJSCallbackInfo *)data; + if (asyncCallbackInfo == nullptr) { + HILOG_INFO("%{public}s called. asyncCallbackInfo is null", __func__); + return; + } + + asyncCallbackInfo->error_code = NAPI_ERR_NO_ERROR; + asyncCallbackInfo->native_data.data_type = NVT_NONE; + if (asyncCallbackInfo->ability == nullptr) { + asyncCallbackInfo->error_code = NAPI_ERR_ACE_ABILITY; + return; + } + + CallAbilityPermissionParam permissionParam; + permissionParam.requestCode = asyncCallbackInfo->param.paramArgs.GetIntValue("requestCode"); + asyncCallbackInfo->param.paramArgs.GetStringValueArray("permissionList", permissionParam.permission_list); + if (permissionParam.permission_list.size() == 0) { + asyncCallbackInfo->error_code = NAPI_ERR_PARAM_INVALID; + return; + } + + AbilityProcess::GetInstance()->RequestPermissionsFromUser( + asyncCallbackInfo->ability, permissionParam, *asyncCallbackInfo->aceCallback); } /** @@ -566,43 +258,37 @@ void RequestPermissionsFromUserExecutePromise(napi_env env, void *data) * @return Return JS data successfully, otherwise return nullptr. */ napi_value NAPI_RequestPermissionsFromUserWrap( - napi_env env, napi_callback_info info, AsyncPermissionCallbackInfo *asyncCallbackInfo) + napi_env env, napi_callback_info info, AsyncJSCallbackInfo *asyncCallbackInfo) { - size_t argc = 4; - const size_t argCount = 2; - napi_value args[PERMISSION_ARGS_SIZE] = {nullptr}; + HILOG_INFO("%{public}s called.", __func__); + size_t argc = ARGS_MAX_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; napi_value jsthis = 0; void *data = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &jsthis, &data)); - CallAbilityPermissionParam param; - if (UnwrapParamArrayString(param.permission_list, env, args[0]) == nullptr) { + if (!UnwrapRequestPermissionsFromUser(env, argc, args, asyncCallbackInfo)) { + HILOG_INFO("%{public}s called. Invoke UnwrapRequestPermissionsFromUser failed.", __func__); return nullptr; } - if (UnwrapParamInt(¶m.requestCode, env, args[1]) == nullptr) { - return nullptr; - } - - asyncCallbackInfo->param = param; asyncCallbackInfo->aceCallback = &aceCallbackInfoPermission; AsyncParamEx asyncParamEx; - asyncParamEx.argc = argc; - if (argc > argCount) { - HILOG_INFO("Context::NAPI_RequestPermissionsFromUser asyncCallback."); - asyncParamEx.resource = "NAPI_RequestPermissionsFromUser_Callback"; - asyncParamEx.startIndex = PERMISSION_EVENT_REQUEST_PERMISSION; - asyncParamEx.execute = RequestPermissionsFromUserExecuteCallback; - asyncParamEx.complete = AsyncCompleteCallback; - return ExecuteAsyncCallback(env, args, asyncCallbackInfo, &asyncParamEx); + if (asyncCallbackInfo->cbInfo.callback != nullptr) { + HILOG_INFO("%{public}s called. asyncCallback.", __func__); + asyncParamEx.resource = "NAPI_RequestPermissionsFromUserCallback"; + asyncParamEx.execute = RequestPermissionsFromUserExecuteCallbackWork; + asyncParamEx.complete = CompleteAsyncCallbackWork; + + return ExecuteAsyncCallbackWork(env, asyncCallbackInfo, &asyncParamEx); } else { - HILOG_INFO("Context::NAPI_RequestPermissionsFromUser promise."); - asyncParamEx.resource = "NAPI_RequestPermissionsFromUser_Promise"; - asyncParamEx.startIndex = 0; - asyncParamEx.execute = RequestPermissionsFromUserExecutePromise; - asyncParamEx.complete = PromiseCompleteCallback; - return ExecutePromiseCallback(env, args, asyncCallbackInfo, &asyncParamEx); + HILOG_INFO("%{public}s called. promise.", __func__); + asyncParamEx.resource = "NAPI_RequestPermissionsFromUserPromise"; + asyncParamEx.execute = RequestPermissionsFromUserExecutePromiseWork; + asyncParamEx.complete = CompletePromiseCallbackWork; + + return ExecutePromiseCallbackWork(env, asyncCallbackInfo, &asyncParamEx); } } @@ -616,17 +302,19 @@ napi_value NAPI_RequestPermissionsFromUserWrap( */ napi_value NAPI_RequestPermissionsFromUser(napi_env env, napi_callback_info info) { - HILOG_INFO("Context::NAPI_RequestPermissionsFromUser. called."); - AsyncPermissionCallbackInfo *asyncCallbackInfo = CreateAsyncPermissionCallbackInfo(env); + HILOG_INFO("%{public}s called.", __func__); + + AsyncJSCallbackInfo *asyncCallbackInfo = CreateAsyncJSCallbackInfo(env); if (asyncCallbackInfo == nullptr) { - return nullptr; + HILOG_INFO("%{public}s called. Invoke CreateAsyncJSCallbackInfo failed.", __func__); + return WrapVoidToJS(env); } napi_value rev = NAPI_RequestPermissionsFromUserWrap(env, info, asyncCallbackInfo); if (rev == nullptr) { delete asyncCallbackInfo; asyncCallbackInfo = nullptr; - NAPI_CALL(env, napi_get_null(env, &rev)); + rev = WrapVoidToJS(env); } return rev; } @@ -640,17 +328,18 @@ napi_value NAPI_RequestPermissionsFromUser(napi_env env, napi_callback_info info * @return Return JS data successfully, otherwise return nullptr. */ napi_value NAPI_OnRequestPermissionsFromUserResultWrap( - napi_env env, napi_callback_info info, AsyncPermissionCallbackInfo *asyncCallbackInfo) + napi_env env, napi_callback_info info, AsyncJSCallbackInfo *asyncCallbackInfo) { - size_t argc = 1; - napi_value args[PERMISSION_ARGS_SIZE] = {nullptr}; + HILOG_INFO("%{public}s called", __func__); + size_t argc = ARGS_MAX_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; napi_value jsthis = 0; void *data = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &jsthis, &data)); if (argc > 0) { - HILOG_INFO("Context::NAPI_OnRequestPermissionsFromUserResult"); + HILOG_INFO("%{public}s called, argc=%{public}d", __func__, argc); napi_value resourceName = 0; NAPI_CALL(env, @@ -658,9 +347,9 @@ napi_value NAPI_OnRequestPermissionsFromUserResultWrap( aceCallbackInfoPermission.env = env; napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, args[0], 1, &aceCallbackInfoPermission.callback); + napi_create_reference(env, args[PARAM0], 1, &aceCallbackInfoPermission.callback); NAPI_CALL(env, napi_create_async_work( @@ -673,7 +362,7 @@ napi_value NAPI_OnRequestPermissionsFromUserResultWrap( [](napi_env env, napi_status status, void *data) { HILOG_INFO("Conext::NAPI_OnRequestPermissionsFromUserResult main event thread complete."); - AsyncPermissionCallbackInfo *asyncCallbackInfo = (AsyncPermissionCallbackInfo *)data; + AsyncJSCallbackInfo *asyncCallbackInfo = (AsyncJSCallbackInfo *)data; if (asyncCallbackInfo != nullptr) { napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; @@ -685,10 +374,7 @@ napi_value NAPI_OnRequestPermissionsFromUserResultWrap( NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); } - // create result code - napi_value result = 0; - NAPI_CALL(env, napi_create_int32(env, 1, &result)); - return result; + return WrapInt32ToJS(env, 1); } /** @@ -700,18 +386,19 @@ napi_value NAPI_OnRequestPermissionsFromUserResultWrap( */ napi_value NAPI_OnRequestPermissionsFromUserResult(napi_env env, napi_callback_info info) { - HILOG_INFO("Context::NAPI_OnRequestPermissionsFromUserResult. called."); + HILOG_INFO("%{public}s called.", __func__); - AsyncPermissionCallbackInfo *asyncCallbackInfo = CreateAsyncPermissionCallbackInfo(env); + AsyncJSCallbackInfo *asyncCallbackInfo = CreateAsyncJSCallbackInfo(env); if (asyncCallbackInfo == nullptr) { - return nullptr; + HILOG_INFO("%{public}s called. Invoke CreateAsyncJSCallbackInfo failed.", __func__); + return WrapVoidToJS(env); } napi_value rev = NAPI_OnRequestPermissionsFromUserResultWrap(env, info, asyncCallbackInfo); if (rev == nullptr) { delete asyncCallbackInfo; asyncCallbackInfo = nullptr; - NAPI_CALL(env, napi_get_null(env, &rev)); + rev = WrapVoidToJS(env); } return rev; } @@ -755,7 +442,7 @@ void CallOnRequestPermissionsFromUserResult(int requestCode, const std::vectorcb.env, 0); napi_create_object(event->cb.env, &result[PARAM1]); @@ -792,7 +479,7 @@ void CallOnRequestPermissionsFromUserResult(int requestCode, const std::vectorcb.env, event->cb.callback, &callback); - napi_call_function(event->cb.env, undefined, callback, ARGS2, &result[PARAM0], &callResult); + napi_call_function(event->cb.env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); if (event->cb.callback != nullptr) { napi_delete_reference(event->cb.env, event->cb.callback); @@ -810,16 +497,23 @@ void CallOnRequestPermissionsFromUserResult(int requestCode, const std::vectorability != nullptr) { - asyncCallbackInfo->native_data.data_type = NVT_STRING; - asyncCallbackInfo->native_data.str_value = asyncCallbackInfo->ability->GetBundleName(); - HILOG_INFO("FeatureAbility::NAPI_GetBundleName bundleName = %{public}s.", - asyncCallbackInfo->native_data.str_value.c_str()); - asyncCallbackInfo->run_status = true; + asyncCallbackInfo->error_code = NAPI_ERR_NO_ERROR; + asyncCallbackInfo->native_data.data_type = NVT_NONE; + if (asyncCallbackInfo->ability == nullptr) { + asyncCallbackInfo->error_code = NAPI_ERR_ACE_ABILITY; + return; } + + asyncCallbackInfo->native_data.data_type = NVT_STRING; + asyncCallbackInfo->native_data.str_value = asyncCallbackInfo->ability->GetBundleName(); + HILOG_INFO("%{public}s called. bundleName=%{public}s", __func__, asyncCallbackInfo->native_data.str_value.c_str()); } /** @@ -830,32 +524,43 @@ void GetBundleNameExecuteCallback(napi_env env, void *data) * * @return Return JS data successfully, otherwise return nullptr. */ -napi_value NAPI_GetBundleNameWrap(napi_env env, napi_callback_info info, AsyncPermissionCallbackInfo *asyncCallbackInfo) +napi_value NAPI_GetBundleNameWrap(napi_env env, napi_callback_info info, AsyncJSCallbackInfo *asyncCallbackInfo) { - size_t argc = 2; - const size_t argCount = 0; - napi_value args[PERMISSION_ARGS_SIZE] = {nullptr}; + HILOG_INFO("%{public}s called", __func__); + size_t argc = ARGS_MAX_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; napi_value jsthis = 0; void *data = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &jsthis, &data)); + if (argc > ARGS_ONE) { + HILOG_INFO("%{public}s called, parameters is invalid.", __func__); + return nullptr; + } + + if (argc == ARGS_ONE) { + if (!CreateAsyncCallback(env, args[PARAM0], asyncCallbackInfo)) { + HILOG_INFO("%{public}s called, the first parameter is invalid.", __func__); + return nullptr; + } + } + AsyncParamEx asyncParamEx; - asyncParamEx.argc = argc; - if (argc > argCount) { - HILOG_INFO("Context::NAPI_GetBundleName asyncCallback."); - asyncParamEx.resource = "NAPI_GetBundleName_Callback"; - asyncParamEx.startIndex = 0; + if (asyncCallbackInfo->cbInfo.callback != nullptr) { + HILOG_INFO("%{public}s called. asyncCallback.", __func__); + asyncParamEx.resource = "NAPI_GetBundleNameCallback"; asyncParamEx.execute = GetBundleNameExecuteCallback; - asyncParamEx.complete = AsyncCompleteCallback; - return ExecuteAsyncCallback(env, args, asyncCallbackInfo, &asyncParamEx); + asyncParamEx.complete = CompleteAsyncCallbackWork; + + return ExecuteAsyncCallbackWork(env, asyncCallbackInfo, &asyncParamEx); } else { - HILOG_INFO("Context::NAPI_GetBundleName promise."); - asyncParamEx.resource = "NAPI_GetBundleName_Promise"; - asyncParamEx.startIndex = 0; + HILOG_INFO("%{public}s called. promise.", __func__); + asyncParamEx.resource = "NAPI_GetBundleNamePromise"; asyncParamEx.execute = GetBundleNameExecuteCallback; - asyncParamEx.complete = PromiseCompleteCallback; - return ExecutePromiseCallback(env, args, asyncCallbackInfo, &asyncParamEx); + asyncParamEx.complete = CompletePromiseCallbackWork; + + return ExecutePromiseCallbackWork(env, asyncCallbackInfo, &asyncParamEx); } } @@ -869,20 +574,397 @@ napi_value NAPI_GetBundleNameWrap(napi_env env, napi_callback_info info, AsyncPe */ napi_value NAPI_GetBundleName(napi_env env, napi_callback_info info) { - HILOG_INFO("FeatureAbility::NAPI_GetBundleName. called."); + HILOG_INFO("%{public}s called", __func__); - AsyncPermissionCallbackInfo *asyncCallbackInfo = CreateAsyncPermissionCallbackInfo(env); + AsyncJSCallbackInfo *asyncCallbackInfo = CreateAsyncJSCallbackInfo(env); if (asyncCallbackInfo == nullptr) { - return nullptr; + HILOG_INFO("%{public}s called. Invoke CreateAsyncJSCallbackInfo failed.", __func__); + return WrapVoidToJS(env); } napi_value rev = NAPI_GetBundleNameWrap(env, info, asyncCallbackInfo); if (rev == nullptr) { delete asyncCallbackInfo; asyncCallbackInfo = nullptr; - NAPI_CALL(env, napi_get_null(env, &rev)); + rev = WrapVoidToJS(env); + } + return rev; +} + +void CanRequestPermissionExecuteCallback(napi_env env, void *data) +{ + HILOG_INFO("%{public}s called.", __func__); + + AsyncJSCallbackInfo *asyncCallbackInfo = (AsyncJSCallbackInfo *)data; + if (asyncCallbackInfo == nullptr) { + HILOG_INFO("%{public}s called. asyncCallbackInfo is null", __func__); + return; + } + + asyncCallbackInfo->error_code = NAPI_ERR_NO_ERROR; + asyncCallbackInfo->native_data.data_type = NVT_NONE; + + if (asyncCallbackInfo->ability == nullptr) { + asyncCallbackInfo->error_code = NAPI_ERR_ACE_ABILITY; + return; + } + + std::string permission(asyncCallbackInfo->param.paramArgs.GetStringValue("permission")); + asyncCallbackInfo->native_data.data_type = NVT_BOOL; + asyncCallbackInfo->native_data.bool_value = asyncCallbackInfo->ability->CanRequestPermission(permission); +} + +napi_value NAPI_CanRequestPermissionWrap(napi_env env, napi_callback_info info, AsyncJSCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s called.", __func__); + size_t argc = ARGS_MAX_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value jsthis = 0; + void *data = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &jsthis, &data)); + + if (!UnwrapParamVerifySelfPermission(env, argc, args, asyncCallbackInfo)) { + HILOG_INFO("%{public}s called. Invoke UnwrapParamVerifySelfPermission fail", __func__); + return nullptr; + } + + AsyncParamEx asyncParamEx; + if (asyncCallbackInfo->cbInfo.callback != nullptr) { + HILOG_INFO("%{public}s called. asyncCallback.", __func__); + asyncParamEx.resource = "NAPI_CanRequestPermissionCallback"; + asyncParamEx.execute = CanRequestPermissionExecuteCallback; + asyncParamEx.complete = CompleteAsyncCallbackWork; + + return ExecuteAsyncCallbackWork(env, asyncCallbackInfo, &asyncParamEx); + } else { + HILOG_INFO("%{public}s called. promise.", __func__); + asyncParamEx.resource = "NAPI_CanRequestPermissionPromise"; + asyncParamEx.execute = CanRequestPermissionExecuteCallback; + asyncParamEx.complete = CompletePromiseCallbackWork; + + return ExecutePromiseCallbackWork(env, asyncCallbackInfo, &asyncParamEx); + } +} + +napi_value NAPI_CanRequestPermission(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + + AsyncJSCallbackInfo *asyncCallbackInfo = CreateAsyncJSCallbackInfo(env); + if (asyncCallbackInfo == nullptr) { + HILOG_INFO("%{public}s called. Invoke CreateAsyncJSCallbackInfo failed.", __func__); + return WrapVoidToJS(env); + } + + napi_value rev = NAPI_CanRequestPermissionWrap(env, info, asyncCallbackInfo); + if (rev == nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + rev = WrapVoidToJS(env); + } + return rev; +} + +bool UnwrapParamVerifyPermission(napi_env env, size_t argc, napi_value *argv, AsyncJSCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s called, argc=%{public}d", __func__, argc); + + const size_t argcMax = 4; + if (argc > argcMax || argc < argcMax - 1) { + HILOG_INFO("%{public}s called, Params is invalid.", __func__); + return false; + } + + if (argc == argcMax) { + if (!CreateAsyncCallback(env, argv[PARAM3], asyncCallbackInfo)) { + HILOG_INFO("%{public}s called, the second parameter is invalid.", __func__); + return false; + } + } + + std::string permission(""); + if (!UnwrapStringFromJS2(env, argv[PARAM0], permission)) { + HILOG_INFO("%{public}s called, the first parameter is invalid.", __func__); + return false; + } + + int pid = 0; + NAPI_CALL(env, napi_get_value_int32(env, argv[PARAM1], &pid)); + + int uid = 0; + NAPI_CALL(env, napi_get_value_int32(env, argv[PARAM2], &uid)); + + asyncCallbackInfo->param.paramArgs.PutStringValue("permission", permission); + asyncCallbackInfo->param.paramArgs.PutIntValue("pid", pid); + asyncCallbackInfo->param.paramArgs.PutIntValue("uid", uid); + + return true; +} + +void VerifyPermissionExecuteCallback(napi_env env, void *data) +{ + HILOG_INFO("%{public}s called.", __func__); + + AsyncJSCallbackInfo *asyncCallbackInfo = (AsyncJSCallbackInfo *)data; + if (asyncCallbackInfo == nullptr) { + HILOG_INFO("%{public}s called. asyncCallbackInfo is null", __func__); + return; + } + + asyncCallbackInfo->error_code = NAPI_ERR_NO_ERROR; + asyncCallbackInfo->native_data.data_type = NVT_NONE; + + if (asyncCallbackInfo->ability == nullptr) { + asyncCallbackInfo->error_code = NAPI_ERR_ACE_ABILITY; + return; + } + + std::string permission(asyncCallbackInfo->param.paramArgs.GetStringValue("permission").c_str()); + int pid = asyncCallbackInfo->param.paramArgs.GetIntValue("pid"); + int uid = asyncCallbackInfo->param.paramArgs.GetIntValue("uid"); + + asyncCallbackInfo->native_data.data_type = NVT_INT32; + asyncCallbackInfo->native_data.int32_value = asyncCallbackInfo->ability->VerifyPermission(permission, pid, uid); +} + +napi_value NAPI_VerifyPermissionWrap(napi_env env, napi_callback_info info, AsyncJSCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s called.", __func__); + size_t argc = ARGS_MAX_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value jsthis = 0; + void *data = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &jsthis, &data)); + + if (!UnwrapParamVerifyPermission(env, argc, args, asyncCallbackInfo)) { + HILOG_INFO("%{public}s called. Invoke UnwrapParamVerifyPermission fail", __func__); + return nullptr; + } + + AsyncParamEx asyncParamEx; + if (asyncCallbackInfo->cbInfo.callback != nullptr) { + HILOG_INFO("%{public}s called. asyncCallback.", __func__); + asyncParamEx.resource = "NAPI_VerifyPermissionCallback"; + asyncParamEx.execute = VerifyPermissionExecuteCallback; + asyncParamEx.complete = CompleteAsyncCallbackWork; + + return ExecuteAsyncCallbackWork(env, asyncCallbackInfo, &asyncParamEx); + } else { + HILOG_INFO("%{public}s called. promise.", __func__); + asyncParamEx.resource = "NAPI_VerifyPermissionPromise"; + asyncParamEx.execute = VerifyPermissionExecuteCallback; + asyncParamEx.complete = CompletePromiseCallbackWork; + + return ExecutePromiseCallbackWork(env, asyncCallbackInfo, &asyncParamEx); + } +} + +napi_value NAPI_VerifyPermission(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + AsyncJSCallbackInfo *asyncCallbackInfo = CreateAsyncJSCallbackInfo(env); + if (asyncCallbackInfo == nullptr) { + HILOG_INFO("%{public}s called. Invoke CreateAsyncJSCallbackInfo failed.", __func__); + return WrapVoidToJS(env); + } + + napi_value rev = NAPI_VerifyPermissionWrap(env, info, asyncCallbackInfo); + if (rev == nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + rev = WrapVoidToJS(env); + } + return rev; +} + +void VerifyCallingPermissionExecuteCallback(napi_env env, void *data) +{ + HILOG_INFO("%{public}s called.", __func__); + + AsyncJSCallbackInfo *asyncCallbackInfo = (AsyncJSCallbackInfo *)data; + if (asyncCallbackInfo == nullptr) { + HILOG_INFO("%{public}s called. asyncCallbackInfo is null", __func__); + return; + } + + asyncCallbackInfo->error_code = NAPI_ERR_NO_ERROR; + asyncCallbackInfo->native_data.data_type = NVT_NONE; + + if (asyncCallbackInfo->ability == nullptr) { + asyncCallbackInfo->error_code = NAPI_ERR_ACE_ABILITY; + return; + } + + asyncCallbackInfo->native_data.data_type = NVT_INT32; + std::string permission(asyncCallbackInfo->param.paramArgs.GetStringValue("permission").c_str()); + asyncCallbackInfo->native_data.int32_value = asyncCallbackInfo->ability->VerifyCallingPermission(permission); +} + +napi_value NAPI_VerifyCallingPermissionWrap( + napi_env env, napi_callback_info info, AsyncJSCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s called.", __func__); + size_t argc = ARGS_MAX_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value jsthis = 0; + void *data = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &jsthis, &data)); + + if (!UnwrapParamVerifySelfPermission(env, argc, args, asyncCallbackInfo)) { + HILOG_INFO("%{public}s called. Invoke UnwrapParamVerifySelfPermission fail", __func__); + return nullptr; + } + + AsyncParamEx asyncParamEx; + if (asyncCallbackInfo->cbInfo.callback != nullptr) { + HILOG_INFO("%{public}s called. asyncCallback.", __func__); + asyncParamEx.resource = "NAPI_VerifyCallingPermissionCallback"; + asyncParamEx.execute = VerifyCallingPermissionExecuteCallback; + asyncParamEx.complete = CompleteAsyncCallbackWork; + + return ExecuteAsyncCallbackWork(env, asyncCallbackInfo, &asyncParamEx); + } else { + HILOG_INFO("%{public}s called. promise.", __func__); + asyncParamEx.resource = "NAPI_VerifyCallingPermissionPromise"; + asyncParamEx.execute = VerifyCallingPermissionExecuteCallback; + asyncParamEx.complete = CompletePromiseCallbackWork; + + return ExecutePromiseCallbackWork(env, asyncCallbackInfo, &asyncParamEx); + } +} + +napi_value NAPI_VerifyCallingPermission(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + + AsyncJSCallbackInfo *asyncCallbackInfo = CreateAsyncJSCallbackInfo(env); + if (asyncCallbackInfo == nullptr) { + HILOG_INFO("%{public}s called. Invoke CreateAsyncJSCallbackInfo failed.", __func__); + return WrapVoidToJS(env); + } + + napi_value rev = NAPI_VerifyCallingPermissionWrap(env, info, asyncCallbackInfo); + if (rev == nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + rev = WrapVoidToJS(env); + } + return rev; +} + +void VerifyCallingOrSelfPermissionExecuteCallback(napi_env env, void *data) +{ + HILOG_INFO("%{public}s called.", __func__); + + AsyncJSCallbackInfo *asyncCallbackInfo = (AsyncJSCallbackInfo *)data; + if (asyncCallbackInfo == nullptr) { + HILOG_INFO("%{public}s called. asyncCallbackInfo is null", __func__); + return; + } + + asyncCallbackInfo->error_code = NAPI_ERR_NO_ERROR; + asyncCallbackInfo->native_data.data_type = NVT_NONE; + + if (asyncCallbackInfo->ability == nullptr) { + asyncCallbackInfo->error_code = NAPI_ERR_ACE_ABILITY; + return; + } + + asyncCallbackInfo->native_data.data_type = NVT_INT32; + std::string permission(asyncCallbackInfo->param.paramArgs.GetStringValue("permission").c_str()); + asyncCallbackInfo->native_data.int32_value = asyncCallbackInfo->ability->VerifyCallingOrSelfPermission(permission); +} + +napi_value NAPI_VerifyCallingOrSelfPermissionWrap( + napi_env env, napi_callback_info info, AsyncJSCallbackInfo *asyncCallbackInfo) +{ + HILOG_INFO("%{public}s called.", __func__); + size_t argc = ARGS_MAX_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value jsthis = 0; + void *data = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &jsthis, &data)); + + if (!UnwrapParamVerifySelfPermission(env, argc, args, asyncCallbackInfo)) { + HILOG_INFO("%{public}s called. Invoke UnwrapParamVerifySelfPermission fail", __func__); + return nullptr; + } + + AsyncParamEx asyncParamEx; + if (asyncCallbackInfo->cbInfo.callback != nullptr) { + HILOG_INFO("%{public}s called. asyncCallback.", __func__); + asyncParamEx.resource = "NAPI_VerifyCallingOrSelfPermissionCallback"; + asyncParamEx.execute = VerifyCallingOrSelfPermissionExecuteCallback; + asyncParamEx.complete = CompleteAsyncCallbackWork; + + return ExecuteAsyncCallbackWork(env, asyncCallbackInfo, &asyncParamEx); + } else { + HILOG_INFO("%{public}s called. promise.", __func__); + asyncParamEx.resource = "NAPI_VerifyCallingOrSelfPermissionPromise"; + asyncParamEx.execute = VerifyCallingOrSelfPermissionExecuteCallback; + asyncParamEx.complete = CompletePromiseCallbackWork; + + return ExecutePromiseCallbackWork(env, asyncCallbackInfo, &asyncParamEx); + } +} + +napi_value NAPI_VerifyCallingOrSelfPermission(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called.", __func__); + + AsyncJSCallbackInfo *asyncCallbackInfo = CreateAsyncJSCallbackInfo(env); + if (asyncCallbackInfo == nullptr) { + HILOG_INFO("%{public}s called. Invoke CreateAsyncJSCallbackInfo failed.", __func__); + return WrapVoidToJS(env); + } + + napi_value rev = NAPI_VerifyCallingOrSelfPermissionWrap(env, info, asyncCallbackInfo); + if (rev == nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + rev = WrapVoidToJS(env); } return rev; } + +/** + * @brief Context 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 ContextPermissionInit(napi_env env, napi_value exports) +{ + HILOG_INFO("Context::ContextPermissionInit called."); + + napi_property_descriptor properties[] = { + DECLARE_NAPI_FUNCTION("verifySelfPermission", NAPI_VerifySelfPermission), + DECLARE_NAPI_FUNCTION("requestPermissionsFromUser", NAPI_RequestPermissionsFromUser), + DECLARE_NAPI_FUNCTION("onRequestPermissionsFromUserResult", NAPI_OnRequestPermissionsFromUserResult), + DECLARE_NAPI_FUNCTION("getBundleName", NAPI_GetBundleName), + DECLARE_NAPI_FUNCTION("canRequestPermission", NAPI_CanRequestPermission), + DECLARE_NAPI_FUNCTION("verifyPermission", NAPI_VerifyPermission), + DECLARE_NAPI_FUNCTION("verifyCallingPermission", NAPI_VerifyCallingPermission), + DECLARE_NAPI_FUNCTION("verifyCallingOrSelfPermission", NAPI_VerifyCallingOrSelfPermission), + }; + + NAPI_CALL(env, + napi_define_class(env, + "context", + NAPI_AUTO_LENGTH, + ContextConstructor, + nullptr, + sizeof(properties) / sizeof(*properties), + properties, + &g_classContext)); + + return exports; +} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/featureAbility/napi_context.h b/interfaces/kits/napi/aafwk/featureAbility/napi_context.h old mode 100644 new mode 100755 index baa5871d2ef017e125a172c1ba3d507fcbf48c29..f146698eddd4514e6fc14fda222dbc7902d52dd7 --- a/interfaces/kits/napi/aafwk/featureAbility/napi_context.h +++ b/interfaces/kits/napi/aafwk/featureAbility/napi_context.h @@ -18,11 +18,8 @@ #include "napi/native_common.h" #include "napi/native_node_api.h" #include "ability.h" -#include "feature_ability_common.h" +#include "../inner/napi_common/napi_common.h" -#define PERMISSION_C_BUFFER_SIZE 1024 /* Converted to C-style string buffer size */ -#define PERMISSION_ARGS_SIZE 10 -#define PERMISSION_EVENT_SIZE 1 using Ability = OHOS::AppExecFwk::Ability; namespace OHOS { @@ -34,42 +31,6 @@ struct CallAbilityPermissionParam { int syncOption = false; }; -typedef enum { - NVT_NONE = 0, - NVT_INT32, - NVT_BOOL, - NVT_STRING, -} TNativeValueType; - -typedef struct __ThreadReturnData { - TNativeValueType data_type; - int32_t int32_value; - bool bool_value; - std::string str_value; -} ThreadReturnData; - -struct AsyncPermissionCallbackInfo { - napi_env env; - napi_async_work asyncWork; - napi_deferred deferred; - Ability *ability; - CallAbilityPermissionParam param; - napi_ref callback[2] = {0}; - ThreadReturnData native_data; - napi_value result; - bool run_status; - int error_code; - OHOS::AppExecFwk::CallbackInfo *aceCallback; -}; - -struct AsyncParamEx { - std::string resource; - size_t argc; - size_t startIndex; - napi_async_execute_callback execute; - napi_async_complete_callback complete; -}; - struct OnRequestPermissionsFromUserResultCallback { int requestCode = 0; std::vector permissions; @@ -77,115 +38,6 @@ struct OnRequestPermissionsFromUserResultCallback { CallbackInfo cb; }; -/** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * - * @return Return a pointer to AsyncPermissionCallbackInfo on success, nullptr on failure - */ -AsyncPermissionCallbackInfo *CreateAsyncPermissionCallbackInfo(napi_env env); - -/** - * @brief Create asynchronous data. - * - * @param env The environment that the Node-API call is invoked under. - * @param argc Number of parameters. - * @param startIndex The position of the first event parameter. - * @param args Parameter list. - * @param callback Point to asynchronous processing of data. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value CreateAsyncCallback( - napi_env env, size_t argc, size_t startIndex, napi_value *args, AsyncPermissionCallbackInfo *callback); - -/** - * @brief Parse JS numeric parameters. - * - * @param env The environment that the Node-API call is invoked under. - * @param value Return integer value. - * @param args Parameter list. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value UnwrapParamInt(int *value, napi_env env, napi_value args); - -/** - * @brief Parse JS string parameters. - * - * @param env The environment that the Node-API call is invoked under. - * @param value Return stirng value. - * @param args Parameter list. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value UnwrapParamString(std::vector &value, napi_env env, napi_value args); - -/** - * @brief Parse JS array of string parameters. - * - * @param env The environment that the Node-API call is invoked under. - * @param value Return array of stirng value. - * @param args Parameter list. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value UnwrapParamArrayString(std::vector &value, napi_env env, napi_value args); - -/** - * @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 AsyncCompleteCallback(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 PromiseCompleteCallback(napi_env env, napi_status status, void *data); - -/** - * @brief Asynchronous callback processing. - * - * @param env The environment that the Node-API call is invoked under. - * @param args list of JS of param. - * @param asyncCallbackInfo Process data asynchronously. - * @param param other param. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value ExecuteAsyncCallback( - napi_env env, napi_value *args, AsyncPermissionCallbackInfo *asyncCallbackInfo, const AsyncParamEx *param); - -/** - * @brief Asynchronous promise processing. - * - * @param env The environment that the Node-API call is invoked under. - * @param args list of JS of param. - * @param asyncCallbackInfo Process data asynchronously. - * @param param other param. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value ExecutePromiseCallback( - napi_env env, napi_value *args, AsyncPermissionCallbackInfo *asyncCallbackInfo, const AsyncParamEx *param); - -/** - * @brief Convert local data to JS data. - * - * @param env The environment that the Node-API call is invoked under. - * @param data The local data. - * @param value the JS data. - * - * @return The return value from NAPI C++ to JS for the module. - */ -void NAPI_GetNapiValue(napi_env env, const ThreadReturnData *data, napi_value *value); - /** * @brief Context NAPI module registration. * 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 c90cd86c16e3ea1cc387c4c188ac7df3c01fe2dd..088fc84e36399841ed0eb963c8957b70be571329 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp +++ b/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp @@ -14,7 +14,6 @@ */ #include "napi_data_ability_helper.h" #include "data_ability_helper.h" -#include "want_wrapper.h" #include "uri.h" #include #include @@ -155,8 +154,8 @@ napi_value InsertWrap(napi_env env, napi_callback_info info, DAHelperInsertCB *i { HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS3; - const size_t argcPromise = ARGS2; + 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; @@ -269,14 +268,14 @@ void InsertAsyncCompleteCB(napi_env env, napi_status status, void *data) DAHelperInsertCB *insertCB = (DAHelperInsertCB *)data; napi_value callback = nullptr; napi_value undefined = nullptr; - napi_value result[ARGS2] = {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, NO_ERROR); napi_create_int32(env, insertCB->result, &result[PARAM1]); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS2, &result[PARAM0], &callResult)); + 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)); @@ -318,14 +317,14 @@ napi_value UnwrapValuesBucket(std::string &value, napi_env env, napi_value args) } napi_value jsObject = nullptr; - jsObject = GetObjectByPropertyName(env, args, "valueBucket"); + jsObject = GetPropertyValueByPropertyName(env, args, "valueBucket", napi_object); if (jsObject == nullptr) { HILOG_ERROR("%{public}s, jsObject == nullptr.", __func__); return nullptr; } std::string strValue = ""; - if (GetStringByPropertyName(env, jsObject, "value", strValue)) { + if (UnwrapStringByPropertyName(env, jsObject, "value", strValue)) { HILOG_INFO("%{public}s,strValue=%{public}s", __func__, strValue.c_str()); value = strValue; } diff --git a/interfaces/kits/napi/aafwk/featureAbility/want_wrapper.cpp b/interfaces/kits/napi/aafwk/featureAbility/want_wrapper.cpp deleted file mode 100644 index e96618c06dc734a1bd790ee764a162da63b4f5df..0000000000000000000000000000000000000000 --- a/interfaces/kits/napi/aafwk/featureAbility/want_wrapper.cpp +++ /dev/null @@ -1,796 +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 -#include -#include -#include "want_wrapper.h" -#include "want_params.h" -#include "securec.h" -#include "hilog_wrapper.h" -namespace OHOS { -namespace AppExecFwk { - -/** - * @brief Indicates the specified attribute exists in the object passed by JS. - * - * @param env The environment that the Node-API call is invoked under. - * @param jsObject Indicates object passed by JS. - * @param propertyName Indicates the name of the property. - * - * @return Returns true if the attribute exists, else returns false. - */ -bool IsExistsByPropertyName(napi_env env, napi_value jsObject, const char *propertyName) -{ - bool result = false; - if (napi_has_named_property(env, jsObject, propertyName, &result) == napi_ok) { - return result; - } else { - return false; - } -} - -/** - * @brief Get the JSValue of the specified name from the JS object. - * - * @param env The environment that the Node-API call is invoked under. - * @param jsObject Indicates object passed by JS. - * @param propertyName Indicates the name of the property. - * @param expectType Indicates expected JS data type. - * - * @return Return value of JSObject if successful, else return nullptr. - */ -napi_value GetJSValueByPropertyName( - napi_env env, napi_value jsObject, const char *propertyName, napi_valuetype expectType) -{ - napi_valuetype valueType = napi_undefined; - napi_value value = nullptr; - if (IsExistsByPropertyName(env, jsObject, propertyName) == false) { - return nullptr; - } - - if (napi_get_named_property(env, jsObject, propertyName, &value) != napi_ok) { - return nullptr; - } - - if (napi_typeof(env, value, &valueType) != napi_ok) { - return nullptr; - } - - if (expectType != napi_undefined && valueType != expectType) { - return nullptr; - } - return value; -} - -/** - * @brief Get the native string from the JSObject of the given property name. - * - * @param env The environment that the Node-API call is invoked under. - * @param jsObject Indicates object passed by JS. - * @param propertyName Indicates the name of the property. - * @param nativeValue Indicates the returned native value. - * - * @return Return true if successful, else return false. - */ -bool GetStringByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, std::string &nativeValue) -{ - napi_value value = GetJSValueByPropertyName(env, jsObject, propertyName, napi_string); - if (value != nullptr) { - nativeValue = NapiValueToStringUtf8(env, value); - HILOG_INFO("%{public}s,called, nativeValue=%{public}s", __func__, nativeValue.c_str()); - return true; - } else { - return false; - } -} - -/** - * @brief Get the native number(int32) from the JSObject of the given property name. - * - * @param env The environment that the Node-API call is invoked under. - * @param jsObject Indicates object passed by JS. - * @param propertyName Indicates the name of the property. - * @param nativeValue Indicates the returned native value. - * - * @return Return true if successful, else return false. - */ -bool GetInt32ByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, int32_t &nativeValue) -{ - napi_value value = GetJSValueByPropertyName(env, jsObject, propertyName, napi_number); - if (value != nullptr) { - return (napi_get_value_int32(env, value, &nativeValue) == napi_ok); - } else { - return false; - } -} - -/** - * @brief Get the native number(int64) from the JSObject of the given property name. - * - * @param env The environment that the Node-API call is invoked under. - * @param jsObject Indicates object passed by JS. - * @param propertyName Indicates the name of the property. - * @param nativeValue Indicates the returned native value. - * - * @return Return true if successful, else return false. - */ -bool GetInt64ByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, int64_t &nativeValue) -{ - napi_value value = GetJSValueByPropertyName(env, jsObject, propertyName, napi_number); - if (value != nullptr) { - return (napi_get_value_int64(env, value, &nativeValue) == napi_ok); - } else { - return false; - } -} - -/** - * @brief Get the native number(double) from the JSObject of the given property name. - * - * @param env The environment that the Node-API call is invoked under. - * @param jsObject Indicates object passed by JS. - * @param propertyName Indicates the name of the property. - * @param nativeValue Indicates the returned native value. - * - * @return Return true if successful, else return false. - */ -bool GetDoubleByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, double &nativeValue) -{ - napi_value value = GetJSValueByPropertyName(env, jsObject, propertyName, napi_number); - if (value != nullptr) { - return (napi_get_value_double(env, value, &nativeValue) == napi_ok); - } else { - return false; - } -} - -/** - * @brief Get the native boolean from the JSObject of the given property name. - * - * @param env The environment that the Node-API call is invoked under. - * @param jsObject Indicates object passed by JS. - * @param propertyName Indicates the name of the property. - * @param nativeValue Indicates the returned native value. - * - * @return Return true if successful, else return false. - */ -bool GetBooleanByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, bool &nativeValue) -{ - napi_value value = GetJSValueByPropertyName(env, jsObject, propertyName, napi_boolean); - if (value != nullptr) { - return (napi_get_value_bool(env, value, &nativeValue) == napi_ok); - } else { - return false; - } -} - -/** - * @brief Get the JSObject from the JSObject of the given property name. - * - * @param env The environment that the Node-API call is invoked under. - * @param jsObject Indicates object passed by JS. - * @param propertyName Indicates the name of the property. - * - * @return Return value of JSObject if successful, else return nullptr. - */ -napi_value GetObjectByPropertyName(napi_env env, napi_value jsObject, const char *propertyName) -{ - return GetJSValueByPropertyName(env, jsObject, propertyName, napi_object); -} - -/** - * @brief Get the native array of string from the JSObject of the given property name. - * - * @param env The environment that the Node-API call is invoked under. - * @param jsObject Indicates object passed by JS. - * @param propertyName Indicates the name of the property. - * @param nativeValue Indicates the returned native value. - * - */ -void GetStringArrayByPropertyName( - napi_env env, napi_value jsObject, const char *propertyName, std::vector &nativeValue) -{ - nativeValue.clear(); - napi_value jsArrayObject = GetObjectByPropertyName(env, jsObject, propertyName); - if (jsArrayObject == nullptr) { - return; - } - - bool isArray = false; - if (napi_is_array(env, jsArrayObject, &isArray) != napi_ok) { - return; - } - if (isArray == false) { - return; - } - - bool hasElement = false; - size_t index = 0; - napi_value elementValue = nullptr; - napi_valuetype valueType = napi_undefined; - while (napi_has_element(env, jsArrayObject, index, &hasElement) == napi_ok) { - if (hasElement == false) { - break; - } - - if (napi_get_element(env, jsArrayObject, index, &elementValue) == napi_ok) { - if (napi_typeof(env, elementValue, &valueType) == napi_ok) { - if (valueType == napi_string) { - nativeValue.emplace_back(NapiValueToStringUtf8(env, elementValue)); - } - } - } - index++; - } -} - -/** - * @brief Parse and set WantOptions from the JSObject of the given property name. - * Get the native array of string from the JSObject of the given property name. - * - * @param env The environment that the Node-API call is invoked under. - * @param jsObject Indicates object passed by JS. - * @param propertyName Indicates the name of the property. - * @param nativeValue Indicates the returned native value. - * - */ -void GetWantOptions(napi_env env, napi_value jsObject, const char *propertyName, Want &want) -{ - napi_value jsOptionsObject = GetObjectByPropertyName(env, jsObject, propertyName); - if (jsOptionsObject == nullptr) { - return; - } - - bool nativeValue = false; - unsigned int flags = 0; - std::map flagMap; - InitWantOptionsData(flagMap); - for (auto iter = flagMap.begin(); iter != flagMap.end(); iter++) { - nativeValue = false; - if (GetBooleanByPropertyName(env, jsOptionsObject, iter->first.c_str(), nativeValue)) { - if (nativeValue) { - flags |= iter->second; - } - } - } - - want.SetFlags(flags); -} - -/** - * @brief Parse the want 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 UnwrapWant(Want ¶m, napi_env env, napi_value args) -{ - HILOG_INFO("%{public}s,called", __func__); - // unwrap the param - napi_valuetype valueType = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args, &valueType)); - if (valueType != napi_object) { - return nullptr; - } - - napi_value jsWant = nullptr; - // unwrap the param : want object - jsWant = GetObjectByPropertyName(env, args, "want"); - if (jsWant == nullptr) { - return nullptr; - } - - std::string strValue; - // get want action property - if (GetStringByPropertyName(env, jsWant, "action", strValue)) { - param.SetAction(strValue); - } - // get want entities property - std::vector nativeStringList; - GetStringArrayByPropertyName(env, jsWant, "entities", nativeStringList); - for (size_t i = 0; i < nativeStringList.size(); i++) { - param.AddEntity(nativeStringList[i]); - } - // get want type property - if (GetStringByPropertyName(env, jsWant, "type", strValue)) { - param.SetType(strValue); - } - // get want flags property(WantOptions in want.d.ts) - GetWantOptions(env, jsWant, "options", param); - // get want uri property - if (GetStringByPropertyName(env, jsWant, "uri", strValue)) { - param.SetUri(strValue); - } - // get elementName property - UnwrapElementName(param, env, jsWant); - - // get want param (optional) - UnwrapWantParam(param, env, jsWant); - - napi_value result; - NAPI_CALL(env, napi_create_int32(env, 1, &result)); - return result; -} - -napi_value WrapWant(const Want ¶m, napi_env env) -{ - HILOG_INFO("%{public}s,called", __func__); - napi_value jsWant = nullptr; - napi_value proValue = nullptr; - NAPI_CALL(env, napi_create_object(env, &jsWant)); - - WrapElementName(param, env, jsWant); - proValue = nullptr; - HILOG_INFO("%{public}s, uri=%{public}s", __func__, param.GetUriString().c_str()); - if (napi_create_string_utf8(env, param.GetUriString().c_str(), NAPI_AUTO_LENGTH, &proValue) == napi_ok) { - napi_set_named_property(env, jsWant, "uri", proValue); - } - - proValue = nullptr; - HILOG_INFO("%{public}s, type=%{public}s", __func__, param.GetType().c_str()); - if (napi_create_string_utf8(env, param.GetType().c_str(), NAPI_AUTO_LENGTH, &proValue) == napi_ok) { - napi_set_named_property(env, jsWant, "type", proValue); - } - - proValue = WrapWantOptions(param, env); - if (proValue != nullptr) { - napi_set_named_property(env, jsWant, "options", proValue); - } - - proValue = nullptr; - HILOG_INFO("%{public}s, action=%{public}s", __func__, param.GetAction().c_str()); - if (napi_create_string_utf8(env, param.GetAction().c_str(), NAPI_AUTO_LENGTH, &proValue) == napi_ok) { - napi_set_named_property(env, jsWant, "action", proValue); - } - - const AAFwk::WantParams nativeParams = param.GetParams(); - if (!nativeParams.IsEmpty()) { - proValue = WrapWantParam(param, env); - if (proValue != nullptr) { - napi_set_named_property(env, jsWant, "parameters", proValue); - } - } - - proValue = WrapEntries(param, env); - if (proValue != nullptr) { - napi_set_named_property(env, jsWant, "entities", proValue); - } - return jsWant; -} - -napi_value WrapEntries(const Want &want, napi_env env) -{ - napi_value jsEntries = nullptr; - napi_value proValue = nullptr; - NAPI_CALL(env, napi_create_array(env, &jsEntries)); - const std::vector nativeEntries = want.GetEntities(); - for (uint32_t i = 0; i < nativeEntries.size(); i++) { - proValue = nullptr; - if (napi_create_string_utf8(env, nativeEntries[i].c_str(), NAPI_AUTO_LENGTH, &proValue) == napi_ok) { - napi_set_element(env, jsEntries, i, proValue); - } - } - return jsEntries; -} - -/** - * @brief Parse the elementName parameters. - * - * @param param Indicates the elementName 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. - */ -void UnwrapElementName(Want ¶m, napi_env env, napi_value args) -{ - HILOG_INFO("%{public}s,called", __func__); - // get elementName property - std::string deviceId = ""; - std::string bundleName = ""; - std::string abilityName = ""; - - GetStringByPropertyName(env, args, "deviceId", deviceId); - GetStringByPropertyName(env, args, "bundleName", bundleName); - GetStringByPropertyName(env, args, "abilityName", abilityName); - param.SetElementName(deviceId, bundleName, abilityName); -} - -napi_value WrapElementName(const Want ¶m, napi_env env, napi_value jsWant) -{ - HILOG_INFO("%{public}s,called", __func__); - napi_value proValue = nullptr; - OHOS::AppExecFwk::ElementName nativeElement = param.GetElement(); - - proValue = nullptr; - NAPI_CALL(env, napi_create_string_utf8(env, nativeElement.GetDeviceID().c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, jsWant, "deviceId", proValue)); - - proValue = nullptr; - NAPI_CALL(env, napi_create_string_utf8(env, nativeElement.GetBundleName().c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, jsWant, "bundleName", proValue)); - - proValue = nullptr; - NAPI_CALL(env, napi_create_string_utf8(env, nativeElement.GetAbilityName().c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_named_property(env, jsWant, "abilityName", proValue)); - - napi_value result; - NAPI_CALL(env, napi_create_int32(env, 1, &result)); - return result; -} - -/** - * @brief Parse the wantParam parameters. - * - * @param param Indicates the wantParam 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 UnwrapWantParam(Want &want, napi_env env, napi_value wantParam) -{ - HILOG_INFO("%{public}s,called", __func__); - napi_valuetype valueType = napi_undefined; - napi_value proNameList = 0; - uint32_t proCount = 0; - - napi_value jsObject = GetJSValueByPropertyName(env, wantParam, "parameters", napi_object); - if (jsObject == nullptr) { - return nullptr; - } - - NAPI_CALL(env, napi_get_property_names(env, jsObject, &proNameList)); - NAPI_CALL(env, napi_get_array_length(env, proNameList, &proCount)); - HILOG_INFO("UnwrapWantParam property size=%{public}d", proCount); - - napi_value proName = 0; - napi_value proValue = 0; - for (uint32_t index = 0; index < proCount; index++) { - NAPI_CALL(env, napi_get_element(env, proNameList, index, &proName)); - std::string strProName = NapiValueToStringUtf8(env, proName); - HILOG_INFO("UnwrapWantParam proName=%{public}s", strProName.c_str()); - NAPI_CALL(env, napi_get_named_property(env, jsObject, strProName.c_str(), &proValue)); - NAPI_CALL(env, napi_typeof(env, proValue, &valueType)); - - switch (valueType) { - case napi_string: { - std::string str_pro_value = NapiValueToStringUtf8(env, proValue); - HILOG_INFO("UnwrapWantParam proValue=%{public}s", str_pro_value.c_str()); - want.SetParam(strProName, str_pro_value); - break; - } - case napi_boolean: { - bool c_pro_value = false; - NAPI_CALL(env, napi_get_value_bool(env, proValue, &c_pro_value)); - HILOG_INFO("UnwrapWantParam proValue=%{public}d", c_pro_value); - want.SetParam(strProName, c_pro_value); - break; - } - case napi_number: { - int32_t c_pro_value32 = 0; - double c_pro_value_double = 0.0; - - if (napi_get_value_int32(env, proValue, &c_pro_value32) == napi_ok) { - HILOG_INFO("UnwrapWantParam proValue=%{public}d", c_pro_value32); - want.SetParam(strProName, c_pro_value32); - break; - } - if (napi_get_value_double(env, proValue, &c_pro_value_double) == napi_ok) { - HILOG_INFO("UnwrapWantParam proValue=%{public}lf", c_pro_value_double); - want.SetParam(strProName, c_pro_value_double); - break; - } - HILOG_INFO("UnwrapWantParam unknown proValue of Number"); - break; - } - default: { - if (UnwrapWantParamArray(want, env, strProName, proValue) == nullptr) { - return nullptr; - } - } - } - } - napi_value result; - NAPI_CALL(env, napi_create_int32(env, 1, &result)); - return result; -} - -void WrapWantParamArray( - const Want &want, napi_env env, const std::string &key, sptr &ao, napi_value jsObject) -{ - napi_value jsArray = nullptr; - napi_value proValue = nullptr; - if (AAFwk::Array::IsStringArray(ao)) { - std::vector nativeValue = want.GetStringArrayParam(key); - if (napi_create_array(env, &jsArray) != napi_ok) { - return; - } - for (uint32_t i = 0; i < nativeValue.size(); i++) { - proValue = nullptr; - if (napi_create_string_utf8(env, nativeValue[i].c_str(), NAPI_AUTO_LENGTH, &proValue) == napi_ok) { - napi_set_element(env, jsArray, i, proValue); - } - } - napi_set_named_property(env, jsObject, key.c_str(), jsArray); - } else if (AAFwk::Array::IsBooleanArray(ao)) { - std::vector nativeValue = want.GetBoolArrayParam(key); - if (napi_create_array(env, &jsArray) != napi_ok) { - return; - } - for (uint32_t i = 0; i < nativeValue.size(); i++) { - proValue = nullptr; - if (napi_get_boolean(env, nativeValue[i], &proValue) == napi_ok) { - napi_set_element(env, jsArray, i, proValue); - } - } - napi_set_named_property(env, jsObject, key.c_str(), jsArray); - } else if (AAFwk::Array::IsIntegerArray(ao)) { - std::vector nativeValue = want.GetIntArrayParam(key); - if (napi_create_array(env, &jsArray) != napi_ok) { - return; - } - for (uint32_t i = 0; i < nativeValue.size(); i++) { - proValue = nullptr; - if (napi_create_int32(env, nativeValue[i], &proValue) == napi_ok) { - napi_set_element(env, jsArray, i, proValue); - } - } - napi_set_named_property(env, jsObject, key.c_str(), jsArray); - } else if (AAFwk::Array::IsLongArray(ao)) { - std::vector nativeValue = want.GetLongArrayParam(key); - if (napi_create_array(env, &jsArray) != napi_ok) { - return; - } - for (uint32_t i = 0; i < nativeValue.size(); i++) { - proValue = nullptr; - if (napi_create_int64(env, nativeValue[i], &proValue) == napi_ok) { - napi_set_element(env, jsArray, i, proValue); - } - } - napi_set_named_property(env, jsObject, key.c_str(), jsArray); - } else if (AAFwk::Array::IsDoubleArray(ao)) { - std::vector nativeValue = want.GetDoubleArrayParam(key); - if (napi_create_array(env, &jsArray) != napi_ok) { - return; - } - for (uint32_t i = 0; i < nativeValue.size(); i++) { - proValue = nullptr; - if (napi_create_double(env, nativeValue[i], &proValue) == napi_ok) { - napi_set_element(env, jsArray, i, proValue); - } - } - napi_set_named_property(env, jsObject, key.c_str(), jsArray); - } -} - -napi_value WrapWantParam(const Want &want, napi_env env) -{ - HILOG_INFO("%{public}s,called", __func__); - napi_value jsParam = nullptr; - napi_value proValue = nullptr; - NAPI_CALL(env, napi_create_object(env, &jsParam)); - const AAFwk::WantParams nativeParams = want.GetParams(); - const std::map> paramList = nativeParams.GetParams(); - for (auto iter = paramList.begin(); iter != paramList.end(); iter++) { - proValue = nullptr; - if (AAFwk::IString::Query(iter->second) != nullptr) { - std::string nativeValue = want.GetStringParam(iter->first); - HILOG_INFO("%{public}s, %{public}s=%{public}s", __func__, iter->first.c_str(), nativeValue.c_str()); - if (napi_create_string_utf8(env, nativeValue.c_str(), NAPI_AUTO_LENGTH, &proValue) == napi_ok) { - napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); - } - } else if (AAFwk::IBoolean::Query(iter->second) != nullptr) { - bool natvieValue = want.GetBoolParam(iter->first, false); - if (napi_get_boolean(env, natvieValue, &proValue) == napi_ok) { - napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); - } - } else if (AAFwk::IShort::Query(iter->second) != nullptr) { - short natvieValue = want.GetShortParam(iter->first, 0); - if (napi_create_int32(env, natvieValue, &proValue) == napi_ok) { - napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); - } - } else if (AAFwk::IInteger::Query(iter->second) != nullptr) { - int natvieValue = want.GetIntParam(iter->first, 0); - if (napi_create_int32(env, natvieValue, &proValue) == napi_ok) { - napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); - } - } else if (AAFwk::ILong::Query(iter->second) != nullptr) { - long natvieValue = want.GetLongParam(iter->first, 0); - if (napi_create_int64(env, natvieValue, &proValue) == napi_ok) { - napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); - } - } else if (AAFwk::IFloat::Query(iter->second) != nullptr) { - float natvieValue = want.GetFloatParam(iter->first, 0.0); - if (napi_create_double(env, natvieValue, &proValue) == napi_ok) { - napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); - } - } else if (AAFwk::IDouble::Query(iter->second) != nullptr) { - double natvieValue = want.GetDoubleParam(iter->first, 0.0); - if (napi_create_double(env, natvieValue, &proValue) == napi_ok) { - napi_set_named_property(env, jsParam, iter->first.c_str(), proValue); - } - } else { - AAFwk::IArray *ao = AAFwk::IArray::Query(iter->second); - if (ao != nullptr) { - sptr array(ao); - WrapWantParamArray(want, env, iter->first, array, jsParam); - } - } - } - return jsParam; -} - -/** - * @brief Parse the wantParamArray parameters. - * - * @param param Indicates the wantParamArray 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 UnwrapWantParamArray(Want &want, napi_env env, std::string strProName, napi_value proValue) -{ - HILOG_INFO("%{public}s,called", __func__); - bool isArray = false; - uint32_t arrayLength = 0; - napi_value valueAry = 0; - napi_valuetype valueAryType = napi_undefined; - - NAPI_CALL(env, napi_is_array(env, proValue, &isArray)); - NAPI_CALL(env, napi_get_array_length(env, proValue, &arrayLength)); - HILOG_INFO("UnwrapWantParam proValue is array, length=%{public}d", arrayLength); - - std::vector stringList; - std::vector intList; - std::vector longList; - std::vector boolList; - std::vector doubleList; - bool isDouble = false; - for (uint32_t j = 0; j < arrayLength; j++) { - NAPI_CALL(env, napi_get_element(env, proValue, j, &valueAry)); - NAPI_CALL(env, napi_typeof(env, valueAry, &valueAryType)); - switch (valueAryType) { - case napi_string: { - std::string str_ary_value = NapiValueToStringUtf8(env, valueAry); - HILOG_INFO("UnwrapWantParam string array proValue=%{public}s", str_ary_value.c_str()); - stringList.push_back(str_ary_value); - break; - } - case napi_boolean: { - bool c_ary_value = false; - NAPI_CALL(env, napi_get_value_bool(env, valueAry, &c_ary_value)); - HILOG_INFO("UnwrapWantParam bool array proValue=%{public}d", c_ary_value); - boolList.push_back(c_ary_value); - break; - } - case napi_number: { - int32_t c_ary_value32 = 0; - int64_t c_ary_value64 = 0; - double c_ary_value_double = 0.0; - if (isDouble) { - if (napi_get_value_double(env, valueAry, &c_ary_value_double) == napi_ok) { - HILOG_INFO("UnwrapWantParam double array proValue=%{public}lf", c_ary_value_double); - doubleList.push_back(c_ary_value_double); - } - break; - } else { - if (napi_get_value_int32(env, valueAry, &c_ary_value32) == napi_ok) { - HILOG_INFO("UnwrapWantParam int array proValue=%{public}d", c_ary_value32); - intList.push_back(c_ary_value32); - break; - } - } - - if (napi_get_value_int64(env, valueAry, &c_ary_value64) == napi_ok) { - HILOG_INFO("UnwrapWantParam int64 array proValue=%{public}lld", c_ary_value64); - longList.push_back(c_ary_value64); - break; - } - if (napi_get_value_double(env, valueAry, &c_ary_value_double) == napi_ok) { - HILOG_INFO("UnwrapWantParam double array proValue=%{public}lf", c_ary_value_double); - isDouble = true; - if (intList.size() > 0) { - for (int k = 0; k < (int)intList.size(); k++) { - doubleList.push_back(intList[k]); - } - intList.clear(); - } - doubleList.push_back(c_ary_value_double); - break; - } - HILOG_INFO("UnwrapWantParam array unkown Number"); - break; - } - default: - HILOG_INFO("UnwrapWantParam array unkown"); - break; - } - } - if (stringList.size() > 0) { - want.SetParam(strProName, stringList); - } - if (intList.size() > 0) { - want.SetParam(strProName, intList); - } - if (longList.size() > 0) { - want.SetParam(strProName, longList); - } - if (boolList.size() > 0) { - want.SetParam(strProName, boolList); - } - if (doubleList.size() > 0) { - want.SetParam(strProName, doubleList); - } - napi_value result; - NAPI_CALL(env, napi_create_int32(env, 1, &result)); - return result; -} - -/** - * @brief Init param of wantOptions. - * - * @param flagMap Indicates flag of list in Want . - */ -void InitWantOptionsData(std::map &flagMap) -{ - flagMap.emplace("authReadUriPermission", Want::FLAG_AUTH_READ_URI_PERMISSION); - flagMap.emplace("authWriteUriPermission", Want::FLAG_AUTH_WRITE_URI_PERMISSION); - flagMap.emplace("abilityForwardResult", Want::FLAG_ABILITY_FORWARD_RESULT); - flagMap.emplace("abilityContinuation", Want::FLAG_ABILITY_CONTINUATION); - flagMap.emplace("notOhosComponent", Want::FLAG_NOT_OHOS_COMPONENT); - flagMap.emplace("abilityFormEnabled", Want::FLAG_ABILITY_FORM_ENABLED); - flagMap.emplace("authPersistableUriPermission", Want::FLAG_AUTH_PERSISTABLE_URI_PERMISSION); - flagMap.emplace("authPrefixUriPermission", Want::FLAG_AUTH_PREFIX_URI_PERMISSION); - flagMap.emplace("abilitySliceMultiDevice", Want::FLAG_ABILITYSLICE_MULTI_DEVICE); - flagMap.emplace("startForegroundAbility", Want::FLAG_START_FOREGROUND_ABILITY); - flagMap.emplace("installOnDemand", Want::FLAG_INSTALL_ON_DEMAND); - flagMap.emplace("abilitySliceForwardResult", Want::FLAG_ABILITYSLICE_FORWARD_RESULT); - flagMap.emplace("installWithBackgroundMode", Want::FLAG_INSTALL_WITH_BACKGROUND_MODE); -} - -/** - * @brief Wrap the wantOptions parameters. - * - * @param param Indicates the wantOptions parameters saved the parse result. - * @param env The environment that the Node-API call is invoked under. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value WrapWantOptions(const Want &want, napi_env env) -{ - HILOG_INFO("%{public}s,call", __func__); - napi_value wantOptions = 0; - std::map flagMap; - InitWantOptionsData(flagMap); - unsigned int flags = want.GetFlags(); - bool blValue = false; - napi_value proValue = 0; - NAPI_CALL(env, napi_create_object(env, &wantOptions)); - for (auto iter = flagMap.begin(); iter != flagMap.end(); iter++) { - blValue = ((flags & iter->second) == iter->second); - NAPI_CALL(env, napi_get_boolean(env, blValue, &proValue)); - HILOG_INFO("%{public}s, %{public}s=%{public}s", __func__, iter->first.c_str(), blValue ? "true" : "false"); - NAPI_CALL(env, napi_set_named_property(env, wantOptions, iter->first.c_str(), proValue)); - } - - return wantOptions; -} -} // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn b/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..018cbb2fbddff95b877baf59705dcb3ab48f36d7 --- /dev/null +++ b/interfaces/kits/napi/aafwk/inner/napi_common/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("//build/config/ohos/rules.gni") +import("//build/ohos.gni") +ohos_shared_library("napi_common") { + include_dirs = [ + "//foundation/ace/napi/interfaces/kits", + "//third_party/node/src", + "//third_party/libuv/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + ] + + sources = [ + "napi_common_util.cpp", + "napi_common_want.cpp", + ] + + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/ace/napi:ace_napi", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//third_party/libuv:uv_static", + "//utils/native/base:utils", + ] + + external_deps = [ + "aafwk_standard:ability_manager", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "appexecfwk_standard:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + subsystem_name = "aafwk" + part_name = "aafwk_standard" +} diff --git a/interfaces/kits/napi/aafwk/featureAbility/napi_error.h b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common.h old mode 100644 new mode 100755 similarity index 71% rename from interfaces/kits/napi/aafwk/featureAbility/napi_error.h rename to interfaces/kits/napi/aafwk/inner/napi_common/napi_common.h index f2199a40c7d8841ab4f391672c1067741626ce8d..d3f624be95d9986789b9e18db257dc05f387bba7 --- a/interfaces/kits/napi/aafwk/featureAbility/napi_error.h +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common.h @@ -13,9 +13,11 @@ * limitations under the License. */ -#ifndef NAPI_CONTEXT_ERROR_H -#define NAPI_CONTEXT_ERROR_H +#ifndef OHOS_APPEXECFWK_NAPI_COMMON_H +#define OHOS_APPEXECFWK_NAPI_COMMON_H -#define NAPI_ERR_NO_PERMISSION -100 - -#endif +#include "napi_common_error.h" +#include "napi_common_data.h" +#include "napi_common_util.h" +#include "napi_common_want.h" +#endif // OHOS_APPEXECFWK_NAPI_COMMON_H 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 new file mode 100755 index 0000000000000000000000000000000000000000..d6acdb2e489b89da09557f94f7bbc474df4beaf7 --- /dev/null +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_data.h @@ -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. + */ + +#ifndef OHOS_APPEXECFWK_NAPI_COMMON_DATA_H +#define OHOS_APPEXECFWK_NAPI_COMMON_DATA_H + +#include +#include +#include +#include "napi/native_common.h" +#include "napi/native_node_api.h" +#include "pac_map.h" +#include "ability.h" + +using Ability = OHOS::AppExecFwk::Ability; +namespace OHOS { +namespace AppExecFwk { + +#define NATIVE_C_BUFFER_SIZE 1024 /* Converted to C-style string buffer size */ +#define ARGS_MAX_COUNT 10 +#define ARGS_ASYNC_COUNT 1 + +#define ARGS_ONE 1 +#define ARGS_TWO 2 +#define ARGS_THREE 3 +#define ARGS_FOUR 4 +#define ARGS_FIVE 5 +#define ARGS_SIX 6 +#define ARGS_SEVEN 7 +#define ARGS_EIGHT 8 +#define ARGS_NINE 9 +#define ARGS_TEN 10 + +#define PARAM0 0 +#define PARAM1 1 +#define PARAM2 2 +#define PARAM3 3 +#define PARAM4 4 +#define PARAM5 5 +#define PARAM6 6 +#define PARAM7 7 +#define PARAM8 8 +#define PARAM9 9 +#define PARAM10 10 + +struct CallbackInfo { + napi_env env; + napi_ref callback = 0; +}; + +struct CallAbilityParamData { + PacMap paramArgs; +}; + +typedef enum { + NVT_NONE = 0, + NVT_INT32, + NVT_BOOL, + NVT_STRING, + NVT_DOUBLE, + NVT_PACMAP, +} TNativeValueType; + +typedef struct __ThreadReturnData { + TNativeValueType data_type; + int32_t int32_value; + bool bool_value; + std::string str_value; + double double_value; + PacMap pac_value; +} ThreadReturnData; + +typedef struct __AsyncJSCallbackInfo { + CallbackInfo cbInfo; + napi_async_work asyncWork; + napi_deferred deferred; + Ability *ability; + CallAbilityParamData param; + ThreadReturnData native_data; + napi_value result; + int error_code; + CallbackInfo *aceCallback; +} AsyncJSCallbackInfo; + +typedef struct __AsyncParamEx { + std::string resource; + size_t argc; + napi_async_execute_callback execute; + napi_async_complete_callback complete; +} AsyncParamEx; + +typedef struct __ComplexArrayData { + std::vector intList; + std::vector longList; + std::vector boolList; + std::vector doubleList; + std::vector stringList; +} ComplexArrayData; + +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_APPEXECFWK_NAPI_COMMON_DATA_H diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_error.h b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_error.h new file mode 100755 index 0000000000000000000000000000000000000000..f0efb69f97fcf8a99e55a3dd78c1a29173a6d75c --- /dev/null +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_error.h @@ -0,0 +1,31 @@ +/* + * 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_APPEXECFWK_NAPI_COMMON_ERROR_H +#define OHOS_APPEXECFWK_NAPI_COMMON_ERROR_H + +namespace OHOS { +namespace AppExecFwk { + +#define NAPI_ERR_NO_ERROR 0 +#define NAPI_ERR_NO_PERMISSION -100 +#define NAPI_ERR_INNER_DATA -101 // Internal data error, data allocation fail +#define NAPI_ERR_ACE_ABILITY -102 // Failed to acquire ability object +#define NAPI_ERR_LONG_CALLBACK -103 // Failed to acquire long callack object +#define NAPI_ERR_PARAM_INVALID -104 // Parameter is invalid + +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_APPEXECFWK_NAPI_COMMON_ERROR_H diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.cpp b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.cpp new file mode 100755 index 0000000000000000000000000000000000000000..52be95fc89f5fdbc1dd746653d8eb18183f4d17b --- /dev/null +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.cpp @@ -0,0 +1,1006 @@ +/* + * 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 "napi_common_util.h" +#include "napi_common_data.h" +#include "hilog_wrapper.h" +#include "securec.h" + +namespace OHOS { +namespace AppExecFwk { + +bool IsTypeForNapiValue(napi_env env, napi_value param, napi_valuetype expectType) +{ + napi_valuetype valueType = napi_undefined; + + if (napi_typeof(env, param, &valueType) != napi_ok) { + return false; + } + + return valueType == expectType; +} + +bool IsArrayForNapiValue(napi_env env, napi_value param, uint32_t &arraySize) +{ + bool isArray = false; + arraySize = 0; + + if (napi_is_array(env, param, &isArray) != napi_ok || isArray == false) { + return false; + } + + if (napi_get_array_length(env, param, &arraySize) != napi_ok) { + return false; + } + return true; +} + +napi_value WrapVoidToJS(napi_env env) +{ + napi_value result = nullptr; + NAPI_CALL(env, napi_get_null(env, &result)); + return result; +} + +napi_value CreateJSObject(napi_env env) +{ + napi_value result = nullptr; + NAPI_CALL(env, napi_create_object(env, &result)); + return result; +} + +napi_value WrapInt32ToJS(napi_env env, int32_t value) +{ + napi_value result = nullptr; + NAPI_CALL(env, napi_create_int32(env, value, &result)); + return result; +} + +int UnwrapInt32FromJS(napi_env env, napi_value param, int defaultValue) +{ + int value = defaultValue; + if (napi_get_value_int32(env, param, &value) == napi_ok) { + return value; + } else { + return defaultValue; + } +} + +bool UnwrapInt32FromJS2(napi_env env, napi_value param, int &value) +{ + bool result = false; + if (napi_get_value_int32(env, param, &value) == napi_ok) { + result = true; + } + return result; +} + +napi_value WrapLongToJS(napi_env env, long value) +{ + napi_value result = nullptr; + NAPI_CALL(env, napi_create_int32(env, value, &result)); + return result; +} + +long UnwrapLongFromJS(napi_env env, napi_value param, long defaultValue) +{ + int value = 0; + if (napi_get_value_int32(env, param, &value) == napi_ok) { + return value; + } else { + return defaultValue; + } +} + +bool UnwrapLongFromJS2(napi_env env, napi_value param, long &value) +{ + bool result = false; + int natValue = 0; + if (napi_get_value_int32(env, param, &natValue) == napi_ok) { + value = natValue; + result = true; + } + return result; +} + +napi_value WrapInt64ToJS(napi_env env, int64_t value) +{ + napi_value result = nullptr; + NAPI_CALL(env, napi_create_int64(env, value, &result)); + return result; +} + +int64_t UnwrapInt64FromJS(napi_env env, napi_value param, int64_t defaultValue) +{ + int64_t value = defaultValue; + if (napi_get_value_int64(env, param, &value) == napi_ok) { + return value; + } else { + return defaultValue; + } +} + +bool UnwrapInt64FromJS2(napi_env env, napi_value param, int64_t &value) +{ + bool result = false; + if (napi_get_value_int64(env, param, &value) == napi_ok) { + result = true; + } + return result; +} + +napi_value WrapBoolToJS(napi_env env, bool value) +{ + napi_value result = nullptr; + NAPI_CALL(env, napi_get_boolean(env, value, &result)); + return result; +} + +bool UnwrapBoolFromJS(napi_env env, napi_value param, bool defaultValue) +{ + bool value = defaultValue; + if (napi_get_value_bool(env, param, &value) == napi_ok) { + return value; + } else { + return defaultValue; + } +} + +bool UnwrapBoolFromJS2(napi_env env, napi_value param, bool &value) +{ + bool result = false; + if (napi_get_value_bool(env, param, &value) == napi_ok) { + result = true; + } + return result; +} + +napi_value WrapDoubleToJS(napi_env env, double value) +{ + napi_value result = nullptr; + NAPI_CALL(env, napi_create_double(env, value, &result)); + return result; +} + +double UnwrapDoubleFromJS(napi_env env, napi_value param, double defaultValue) +{ + double value = defaultValue; + if (napi_get_value_double(env, param, &value) == napi_ok) { + return value; + } else { + return defaultValue; + } +} + +bool UnwrapDoubleFromJS2(napi_env env, napi_value param, double &value) +{ + bool result = false; + if (napi_get_value_double(env, param, &value) == napi_ok) { + result = true; + } + return result; +} + +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; +} + +std::string UnwrapStringFromJS(napi_env env, napi_value param, const std::string &defaultValue) +{ + size_t size = 0; + if (napi_get_value_string_utf8(env, param, nullptr, 0, &size) != napi_ok) { + return defaultValue; + } + + std::string value(""); + if (size == 0) { + return defaultValue; + } + + char *buf = new (std::nothrow) char[size + 1]; + if (buf == nullptr) { + return value; + } + memset_s(buf, sizeof(buf), 0, sizeof(buf)); + + bool rev = napi_get_value_string_utf8(env, param, buf, size + 1, &size) == napi_ok; + if (rev) { + value = buf; + } else { + value = defaultValue; + } + + delete[] buf; + buf = nullptr; + return value; +} + +bool UnwrapStringFromJS2(napi_env env, napi_value param, std::string &value) +{ + value = ""; + size_t size = 0; + if (napi_get_value_string_utf8(env, param, nullptr, 0, &size) != napi_ok) { + return false; + } + + if (size == 0) { + return true; + } + + char *buf = new (std::nothrow) char[size + 1]; + if (buf == nullptr) { + return false; + } + memset_s(buf, sizeof(buf), 0, sizeof(buf)); + + bool rev = napi_get_value_string_utf8(env, param, buf, size + 1, &size) == napi_ok; + if (rev) { + value = buf; + } + delete[] buf; + buf = nullptr; + return rev; +} + +napi_value WrapArrayInt32ToJS(napi_env env, const std::vector &value) +{ + napi_value jsArray = nullptr; + napi_value jsValue = nullptr; + uint32_t index = 0; + + NAPI_CALL(env, napi_create_array(env, &jsArray)); + for (uint32_t i = 0; i < value.size(); i++) { + jsValue = nullptr; + if (napi_create_int32(env, value[i], &jsValue) == napi_ok) { + if (napi_set_element(env, jsArray, index, jsValue) == napi_ok) { + index++; + } + } + } + return jsArray; +} + +bool UnwrapArrayInt32FromJS(napi_env env, napi_value param, std::vector &value) +{ + uint32_t arraySize = 0; + napi_value jsValue = nullptr; + int natValue = 0; + + if (!IsArrayForNapiValue(env, param, arraySize)) { + return false; + } + + value.clear(); + for (uint32_t i = 0; i < arraySize; i++) { + jsValue = nullptr; + natValue = 0; + if (napi_get_element(env, param, i, &jsValue) != napi_ok) { + return false; + } + + if (!UnwrapInt32FromJS2(env, jsValue, natValue)) { + return false; + } + + value.push_back(natValue); + } + return true; +} + +napi_value WrapArrayLongToJS(napi_env env, const std::vector &value) +{ + napi_value jsArray = nullptr; + napi_value jsValue = nullptr; + uint32_t index = 0; + + NAPI_CALL(env, napi_create_array(env, &jsArray)); + for (uint32_t i = 0; i < value.size(); i++) { + jsValue = nullptr; + if (napi_create_int32(env, (int)(value[i]), &jsValue) == napi_ok) { + if (napi_set_element(env, jsArray, index, jsValue) == napi_ok) { + index++; + } + } + } + return jsArray; +} + +bool UnwrapArrayLongFromJS(napi_env env, napi_value param, std::vector &value) +{ + uint32_t arraySize = 0; + napi_value jsValue = nullptr; + long natValue = 0; + + if (!IsArrayForNapiValue(env, param, arraySize)) { + return false; + } + + value.clear(); + for (uint32_t i = 0; i < arraySize; i++) { + jsValue = nullptr; + natValue = 0; + if (napi_get_element(env, param, i, &jsValue) != napi_ok) { + return false; + } + + if (!UnwrapLongFromJS2(env, jsValue, natValue)) { + return false; + } + + value.push_back(natValue); + } + return true; +} + +napi_value WrapArrayDoubleToJS(napi_env env, const std::vector &value) +{ + napi_value jsArray = nullptr; + napi_value jsValue = nullptr; + uint32_t index = 0; + + NAPI_CALL(env, napi_create_array(env, &jsArray)); + for (uint32_t i = 0; i < value.size(); i++) { + jsValue = nullptr; + if (napi_create_double(env, value[i], &jsValue) == napi_ok) { + if (napi_set_element(env, jsArray, index, jsValue) == napi_ok) { + index++; + } + } + } + return jsArray; +} + +bool UnwrapArrayDoubleFromJS(napi_env env, napi_value param, std::vector &value) +{ + uint32_t arraySize = 0; + napi_value jsValue = nullptr; + double natValue = 0; + + if (!IsArrayForNapiValue(env, param, arraySize)) { + return false; + } + + value.clear(); + for (uint32_t i = 0; i < arraySize; i++) { + jsValue = nullptr; + natValue = 0; + if (napi_get_element(env, param, i, &jsValue) != napi_ok) { + return false; + } + + if (!UnwrapDoubleFromJS2(env, jsValue, natValue)) { + return false; + } + + value.push_back(natValue); + } + return true; +} + +napi_value WrapArrayBoolToJS(napi_env env, const std::vector &value) +{ + napi_value jsArray = nullptr; + napi_value jsValue = nullptr; + uint32_t index = 0; + + NAPI_CALL(env, napi_create_array(env, &jsArray)); + for (uint32_t i = 0; i < value.size(); i++) { + jsValue = nullptr; + if (napi_get_boolean(env, value[i], &jsValue) == napi_ok) { + if (napi_set_element(env, jsArray, index, jsValue) == napi_ok) { + index++; + } + } + } + return jsArray; +} + +bool UnwrapArrayBoolFromJS(napi_env env, napi_value param, std::vector &value) +{ + uint32_t arraySize = 0; + napi_value jsValue = nullptr; + bool natValue = 0; + + if (!IsArrayForNapiValue(env, param, arraySize)) { + return false; + } + + value.clear(); + for (uint32_t i = 0; i < arraySize; i++) { + jsValue = nullptr; + natValue = 0; + if (napi_get_element(env, param, i, &jsValue) != napi_ok) { + return false; + } + + if (!UnwrapBoolFromJS2(env, jsValue, natValue)) { + return false; + } + + value.push_back(natValue); + } + return true; +} + +napi_value WrapArrayStringToJS(napi_env env, const std::vector &value) +{ + napi_value jsArray = nullptr; + napi_value jsValue = nullptr; + uint32_t index = 0; + + NAPI_CALL(env, napi_create_array(env, &jsArray)); + for (uint32_t i = 0; i < value.size(); i++) { + jsValue = nullptr; + if (napi_create_string_utf8(env, value[i].c_str(), NAPI_AUTO_LENGTH, &jsValue) == napi_ok) { + if (napi_set_element(env, jsArray, index, jsValue) == napi_ok) { + index++; + } + } + } + return jsArray; +} + +bool UnwrapArrayStringFromJS(napi_env env, napi_value param, std::vector &value) +{ + uint32_t arraySize = 0; + napi_value jsValue = nullptr; + std::string natValue(""); + + if (!IsArrayForNapiValue(env, param, arraySize)) { + return false; + } + + value.clear(); + for (uint32_t i = 0; i < arraySize; i++) { + jsValue = nullptr; + natValue = ""; + if (napi_get_element(env, param, i, &jsValue) != napi_ok) { + return false; + } + + if (!UnwrapStringFromJS2(env, jsValue, natValue)) { + return false; + } + + value.push_back(natValue); + } + return true; +} + +bool UnwrapArrayComplexFromJS(napi_env env, napi_value param, ComplexArrayData &value) +{ + uint32_t arraySize = 0; + if (!IsArrayForNapiValue(env, param, arraySize)) { + return false; + } + + napi_valuetype valueType = napi_undefined; + napi_value jsValue = nullptr; + bool isDouble = false; + + value.intList.clear(); + value.longList.clear(); + value.boolList.clear(); + value.doubleList.clear(); + value.stringList.clear(); + + for (uint32_t i = 0; i < arraySize; i++) { + jsValue = nullptr; + valueType = napi_undefined; + NAPI_CALL_BASE(env, napi_get_element(env, param, i, &jsValue), false); + NAPI_CALL_BASE(env, napi_typeof(env, jsValue, &valueType), false); + switch (valueType) { + case napi_string: { + std::string elementValue(""); + if (UnwrapStringFromJS2(env, jsValue, elementValue)) { + value.stringList.push_back(elementValue); + } else { + return false; + } + break; + } + case napi_boolean: { + bool elementValue = false; + NAPI_CALL_BASE(env, napi_get_value_bool(env, jsValue, &elementValue), false); + value.boolList.push_back(elementValue); + break; + } + case napi_number: { + int32_t elementInt32 = 0; + double elementDouble = 0.0; + if (isDouble) { + if (napi_get_value_double(env, jsValue, &elementDouble) == napi_ok) { + value.doubleList.push_back(elementDouble); + } + break; + } else { + bool isReadValue32 = napi_get_value_int32(env, jsValue, &elementInt32) == napi_ok; + bool isReadDouble = napi_get_value_double(env, jsValue, &elementDouble) == napi_ok; + if (isReadValue32 && isReadDouble) { + if (abs(elementDouble - elementInt32 * 1.0) > 0.0) { + isDouble = true; + if (value.intList.size() > 0) { + for (size_t j = 0; j < value.intList.size(); j++) { + value.doubleList.push_back(value.intList[j]); + } + value.intList.clear(); + } + value.doubleList.push_back(elementDouble); + } else { + value.intList.push_back(elementInt32); + } + } else if (isReadValue32) { + value.intList.push_back(elementInt32); + } else if (isReadDouble) { + isDouble = true; + if (value.intList.size() > 0) { + for (size_t j = 0; j < value.intList.size(); j++) { + value.doubleList.push_back(value.intList[j]); + } + value.intList.clear(); + } + value.doubleList.push_back(elementDouble); + } + } + break; + } + default: + break; + } + } + return true; +} + +/** + * @brief Indicates the specified attribute exists in the object passed by JS. + * + * @param env The environment that the Node-API call is invoked under. + * @param jsObject Indicates object passed by JS. + * @param propertyName Indicates the name of the property. + * + * @return Returns true if the attribute exists, else returns false. + */ +bool IsExistsByPropertyName(napi_env env, napi_value jsObject, const char *propertyName) +{ + bool result = false; + if (napi_has_named_property(env, jsObject, propertyName, &result) == napi_ok) { + return result; + } else { + return false; + } +} + +/** + * @brief Get the JSValue of the specified name from the JS object. + * + * @param env The environment that the Node-API call is invoked under. + * @param jsObject Indicates object passed by JS. + * @param propertyName Indicates the name of the property. + * @param expectType Indicates expected JS data type. + * + * @return Return the property value of the specified property name int jsObject on success, otherwise return nullptr. + */ +napi_value GetPropertyValueByPropertyName( + napi_env env, napi_value jsObject, const char *propertyName, napi_valuetype expectType) +{ + napi_value value = nullptr; + if (IsExistsByPropertyName(env, jsObject, propertyName) == false) { + return nullptr; + } + + if (napi_get_named_property(env, jsObject, propertyName, &value) != napi_ok) { + return nullptr; + } + + if (!IsTypeForNapiValue(env, value, expectType)) { + return nullptr; + } + + return value; +} + +bool SetPropertyValueByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, napi_value value) +{ + if (value != nullptr && propertyName != nullptr) { + NAPI_CALL_BASE(env, napi_set_named_property(env, jsObject, propertyName, value), false); + return true; + } + return false; +} + +/** + * @brief Get the native number(int32) from the JSObject of the given property name. + * + * @param env The environment that the Node-API call is invoked under. + * @param jsObject Indicates object passed by JS. + * @param propertyName Indicates the name of the property. + * @param value Indicates the returned native value. + * + * @return Return true if successful, else return false. + */ +bool UnwrapInt32ByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, int32_t &value) +{ + napi_value jsValue = GetPropertyValueByPropertyName(env, jsObject, propertyName, napi_number); + if (jsValue != nullptr) { + return UnwrapInt32FromJS2(env, jsValue, value); + } else { + return false; + } +} + +/** + * @brief Get the native number(double) from the JSObject of the given property name. + * + * @param env The environment that the Node-API call is invoked under. + * @param jsObject Indicates object passed by JS. + * @param propertyName Indicates the name of the property. + * @param value Indicates the returned native value. + * + * @return Return true if successful, else return false. + */ +bool UnwrapDoubleByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, double &value) +{ + napi_value jsValue = GetPropertyValueByPropertyName(env, jsObject, propertyName, napi_number); + if (jsValue != nullptr) { + return UnwrapDoubleFromJS2(env, jsValue, value); + } else { + return false; + } +} + +/** + * @brief Get the native boolean from the JSObject of the given property name. + * + * @param env The environment that the Node-API call is invoked under. + * @param jsObject Indicates object passed by JS. + * @param propertyName Indicates the name of the property. + * @param value Indicates the returned native value. + * + * @return Return true if successful, else return false. + */ +bool UnwrapBooleanByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, bool &value) +{ + napi_value jsValue = GetPropertyValueByPropertyName(env, jsObject, propertyName, napi_boolean); + if (jsValue != nullptr) { + return UnwrapBoolFromJS2(env, jsValue, value); + } else { + return false; + } +} + +bool UnwrapBooleanArrayByPropertyName( + napi_env env, napi_value jsObject, const char *propertyName, std::vector &value) +{ + napi_value jsArray = GetPropertyValueByPropertyName(env, jsObject, propertyName, napi_object); + if (jsArray == nullptr) { + return false; + } + + return UnwrapArrayBoolFromJS(env, jsArray, value); +} + +/** + * @brief Get the native string from the JSObject of the given property name. + * + * @param env The environment that the Node-API call is invoked under. + * @param jsObject Indicates object passed by JS. + * @param propertyName Indicates the name of the property. + * @param value Indicates the returned native value. + * + * @return Return true if successful, else return false. + */ +bool UnwrapStringByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, std::string &value) +{ + napi_value jsValue = GetPropertyValueByPropertyName(env, jsObject, propertyName, napi_string); + if (jsValue != nullptr) { + return UnwrapStringFromJS2(env, jsValue, value); + } else { + return false; + } +} + +bool UnwrapStringArrayByPropertyName( + napi_env env, napi_value jsObject, const char *propertyName, std::vector &value) +{ + napi_value jsArray = GetPropertyValueByPropertyName(env, jsObject, propertyName, napi_object); + if (jsArray == nullptr) { + return false; + } + + return UnwrapArrayStringFromJS(env, jsArray, value); +} + +bool UnwrapComplexArrayByPropertyName( + napi_env env, napi_value jsObject, const char *propertyName, ComplexArrayData &value) +{ + napi_value jsArray = GetPropertyValueByPropertyName(env, jsObject, propertyName, napi_object); + if (jsArray == nullptr) { + return false; + } + + return UnwrapArrayComplexFromJS(env, jsArray, value); +} + +void ClearThreadReturnData(ThreadReturnData *data) +{ + if (data != nullptr) { + data->data_type = NVT_NONE; + data->int32_value = 0; + data->bool_value = false; + data->str_value = ""; + data->double_value = 0.0; + } +} + +napi_value GetCallbackErrorValue(napi_env env, int errCode) +{ + napi_value jsObject = nullptr; + napi_value jsValue = nullptr; + NAPI_CALL(env, napi_create_int32(env, errCode, &jsValue)); + NAPI_CALL(env, napi_create_object(env, &jsObject)); + NAPI_CALL(env, napi_set_named_property(env, jsObject, "code", jsValue)); + return jsObject; +} + +/** + * @brief Create asynchronous data. + * + * @param env The environment that the Node-API call is invoked under. + * + * @return Return a pointer to AsyncPermissionCallbackInfo on success, nullptr on failure + */ +AsyncJSCallbackInfo *CreateAsyncJSCallbackInfo(napi_env env) +{ + HILOG_INFO("%{public}s called.", __func__); + + napi_value global = 0; + NAPI_CALL(env, napi_get_global(env, &global)); + + napi_value abilityObj = 0; + NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); + + Ability *ability = nullptr; + NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); + + AsyncJSCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncJSCallbackInfo{ + .cbInfo.env = env, + .cbInfo.callback = nullptr, + .asyncWork = nullptr, + .deferred = nullptr, + .ability = ability, + .aceCallback = nullptr, + }; + if (asyncCallbackInfo != nullptr) { + ClearThreadReturnData(&asyncCallbackInfo->native_data); + } + return asyncCallbackInfo; +} + +/** + * @brief Convert local data to JS data. + * + * @param env The environment that the Node-API call is invoked under. + * @param data The local data. + * @param value the JS data. + * + * @return The return value from NAPI C++ to JS for the module. + */ +bool WrapThreadReturnData(napi_env env, const ThreadReturnData *data, napi_value *value) +{ + if (data == nullptr || value == nullptr) { + return false; + } + + switch (data->data_type) { + case NVT_INT32: + NAPI_CALL_BASE(env, napi_create_int32(env, data->int32_value, value), false); + break; + case NVT_BOOL: + NAPI_CALL_BASE(env, napi_get_boolean(env, data->bool_value, value), false); + break; + case NVT_STRING: + NAPI_CALL_BASE(env, napi_create_string_utf8(env, data->str_value.c_str(), NAPI_AUTO_LENGTH, value), false); + break; + default: + NAPI_CALL_BASE(env, napi_get_null(env, value), false); + break; + } + return true; +} + +/** + * @brief Create asynchronous data. + * + * @param env The environment that the Node-API call is invoked under. + * @param param Parameter list. + * @param callback Point to asynchronous processing of data. + * + * @return Return true successfully, otherwise return false. + */ +bool CreateAsyncCallback(napi_env env, napi_value param, AsyncJSCallbackInfo *callback) +{ + HILOG_INFO("%{public}s called.", __func__); + + if (param == nullptr || callback == nullptr) { + HILOG_INFO("%{public}s called, param or callback is null.", __func__); + return false; + } + + callback->cbInfo.callback = CreateCallbackRefFromJS(env, param); + if (callback->cbInfo.callback == nullptr) { + HILOG_INFO("%{public}s, create ref failed.", __func__); + return false; + } + + return true; +} + +napi_ref CreateCallbackRefFromJS(napi_env env, napi_value param) +{ + if (env == nullptr || param == nullptr) { + HILOG_INFO("%{public}s called, env or param is null", __func__); + return nullptr; + } + + napi_valuetype valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, param, &valueType)); + + if (valueType != napi_function) { + HILOG_INFO("%{public}s called, Param is invalid.", __func__); + return nullptr; + } + + napi_ref callbackRef = nullptr; + NAPI_CALL(env, napi_create_reference(env, param, 1, &callbackRef)); + return callbackRef; +} + +/** + * @brief Asynchronous callback processing. + * + * @param env The environment that the Node-API call is invoked under. + * @param asyncCallbackInfo Process data asynchronously. + * @param param other param. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value ExecuteAsyncCallbackWork(napi_env env, AsyncJSCallbackInfo *asyncCallbackInfo, const AsyncParamEx *param) +{ + HILOG_INFO("%{public}s called.", __func__); + if (asyncCallbackInfo == nullptr || param == nullptr) { + HILOG_INFO("%{public}s called, asyncCallbackInfo or param is null", __func__); + return nullptr; + } + + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, param->resource.c_str(), NAPI_AUTO_LENGTH, &resourceName)); + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + param->execute, + param->complete, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork)); + + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + return WrapVoidToJS(env); +} + +/** + * @brief Asynchronous promise processing. + * + * @param env The environment that the Node-API call is invoked under. + * @param asyncCallbackInfo Process data asynchronously. + * @param param other param. + * + * @return Return JS data successfully, otherwise return nullptr. + */ +napi_value ExecutePromiseCallbackWork(napi_env env, AsyncJSCallbackInfo *asyncCallbackInfo, const AsyncParamEx *param) +{ + HILOG_INFO("%{public}s called.", __func__); + if (asyncCallbackInfo == nullptr || param == nullptr) { + HILOG_INFO("%{public}s called, asyncCallbackInfo or param is null", __func__); + return nullptr; + } + + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, param->resource.c_str(), NAPI_AUTO_LENGTH, &resourceName)); + + napi_deferred deferred = 0; + 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, + param->execute, + param->complete, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork)); + + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + return promise; +} + +/** + * @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 CompleteAsyncCallbackWork(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("%{public}s called.", __func__); + + AsyncJSCallbackInfo *asyncCallbackInfo = (AsyncJSCallbackInfo *)data; + if (asyncCallbackInfo == nullptr) { + HILOG_INFO("%{public}s called, asyncCallbackInfo is null", __func__); + return; + } + + napi_value callback = 0; + napi_value undefined = 0; + napi_get_undefined(env, &undefined); + napi_value callResult = 0; + napi_value revParam[ARGS_TWO] = {nullptr}; + + revParam[PARAM0] = GetCallbackErrorValue(env, asyncCallbackInfo->error_code); + WrapThreadReturnData(env, &asyncCallbackInfo->native_data, &revParam[PARAM1]); + + if (asyncCallbackInfo->cbInfo.callback != nullptr) { + napi_get_reference_value(env, asyncCallbackInfo->cbInfo.callback, &callback); + napi_call_function(env, undefined, callback, ARGS_TWO, revParam, &callResult); + napi_delete_reference(env, asyncCallbackInfo->cbInfo.callback); + } + + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; +} + +/** + * @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 CompletePromiseCallbackWork(napi_env env, napi_status status, void *data) +{ + HILOG_INFO("%{public}s called.", __func__); + + AsyncJSCallbackInfo *asyncCallbackInfo = (AsyncJSCallbackInfo *)data; + if (asyncCallbackInfo == nullptr) { + HILOG_INFO("%{public}s called, asyncCallbackInfo is null", __func__); + return; + } + + napi_value result = 0; + WrapThreadReturnData(env, &asyncCallbackInfo->native_data, &result); + napi_resolve_deferred(env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/kits/napi/aafwk/featureAbility/want_wrapper.h b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.h old mode 100644 new mode 100755 similarity index 38% rename from interfaces/kits/napi/aafwk/featureAbility/want_wrapper.h rename to interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.h index 28b44e32790f5df2db5303dfd9e182f66db25738..18ec2ae1a648a965d235358d2372573319cc92d6 --- a/interfaces/kits/napi/aafwk/featureAbility/want_wrapper.h +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.h @@ -12,14 +12,65 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef OHOS_APPEXECFWK_WANT_WRAPPER_H -#define OHOS_APPEXECFWK_WANT_WRAPPER_H -#include "feature_ability_common.h" -using Want = OHOS::AAFwk::Want; +#ifndef OHOS_APPEXECFWK_NAPI_COMMON_UTIL_H +#define OHOS_APPEXECFWK_NAPI_COMMON_UTIL_H + +#include "napi/native_common.h" +#include "napi/native_node_api.h" +#include "napi_common_data.h" + namespace OHOS { namespace AppExecFwk { +bool IsTypeForNapiValue(napi_env env, napi_value param, napi_valuetype expectType); +bool IsArrayForNapiValue(napi_env env, napi_value param, uint32_t &arraySize); + +napi_value WrapVoidToJS(napi_env env); + +napi_value CreateJSObject(napi_env env); + +napi_value WrapInt32ToJS(napi_env env, int32_t value); +int UnwrapInt32FromJS(napi_env env, napi_value param, int defaultValue = 0); +bool UnwrapInt32FromJS2(napi_env env, napi_value param, int &value); + +napi_value WrapLongToJS(napi_env env, long value); +long UnwrapLongFromJS(napi_env env, napi_value param, long defaultValue = 0); +bool UnwrapLongFromJS2(napi_env env, napi_value param, long &value); + +napi_value WrapInt64ToJS(napi_env env, int64_t value); +int64_t UnwrapInt64FromJS(napi_env env, napi_value param, int64_t defaultValue = 0); +bool UnwrapInt64FromJS2(napi_env env, napi_value param, int64_t &value); + +napi_value WrapBoolToJS(napi_env env, bool value); +bool UnWrapBoolFromJS(napi_env env, napi_value param, bool defaultValue = false); +bool UnwrapBoolFromJS2(napi_env env, napi_value param, bool &value); + +napi_value WrapDoubleToJS(napi_env env, double value); +double UnWrapDoubleFromJS(napi_env env, napi_value param, double defaultValue = 0.0); +bool UnWrapDoubleFromJS2(napi_env env, napi_value param, double &value); + +napi_value WrapStringToJS(napi_env env, const std::string &value); +std::string UnwrapStringFromJS(napi_env env, napi_value param, const std::string &defaultValue = ""); +bool UnwrapStringFromJS2(napi_env env, napi_value param, std::string &value); + +napi_value WrapArrayInt32ToJS(napi_env env, const std::vector &value); +bool UnwrapArrayInt32FromJS(napi_env env, napi_value param, std::vector &value); + +napi_value WrapArrayLongToJS(napi_env env, const std::vector &value); +bool UnwrapArrayLongFromJS(napi_env env, napi_value param, std::vector &value); + +napi_value WrapArrayDoubleToJS(napi_env env, const std::vector &value); +bool UnwrapArrayDoubleFromJS(napi_env env, napi_value param, std::vector &value); + +napi_value WrapArrayBoolToJS(napi_env env, const std::vector &value); +bool UnwrapArrayBoolFromJS(napi_env env, napi_value param, std::vector &value); + +napi_value WrapArrayStringToJS(napi_env env, const std::vector &value); +bool UnwrapArrayStringFromJS(napi_env env, napi_value param, std::vector &value); + +bool UnwrapArrayComplexFromJS(napi_env env, napi_value param, ComplexArrayData &value); + /** * @brief Indicates the specified attribute exists in the object passed by JS. * @@ -39,22 +90,12 @@ bool IsExistsByPropertyName(napi_env env, napi_value jsObject, const char *prope * @param propertyName Indicates the name of the property. * @param expectType Indicates expected JS data type. * - * @return Return value of JSObject if successful, else return nullptr. + * @return Return the property value of the specified property name int jsObject on success, otherwise return nullptr. */ -napi_value GetJSValueByPropertyName( +napi_value GetPropertyValueByPropertyName( napi_env env, napi_value jsObject, const char *propertyName, napi_valuetype expectType); -/** - * @brief Get the native string from the JSObject of the given property name. - * - * @param env The environment that the Node-API call is invoked under. - * @param jsObject Indicates object passed by JS. - * @param propertyName Indicates the name of the property. - * @param nativeValue Indicates the returned native value. - * - * @return Return true if successful, else return false. - */ -bool GetStringByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, std::string &nativeValue); +bool SetPropertyValueByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, napi_value value); /** * @brief Get the native number(int32) from the JSObject of the given property name. @@ -62,23 +103,11 @@ bool GetStringByPropertyName(napi_env env, napi_value jsObject, const char *prop * @param env The environment that the Node-API call is invoked under. * @param jsObject Indicates object passed by JS. * @param propertyName Indicates the name of the property. - * @param nativeValue Indicates the returned native value. + * @param value Indicates the returned native value. * * @return Return true if successful, else return false. */ -bool GetInt32ByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, int32_t &nativeValue); - -/** - * @brief Get the native number(int64) from the JSObject of the given property name. - * - * @param env The environment that the Node-API call is invoked under. - * @param jsObject Indicates object passed by JS. - * @param propertyName Indicates the name of the property. - * @param nativeValue Indicates the returned native value. - * - * @return Return true if successful, else return false. - */ -bool GetInt64ByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, int64_t &nativeValue); +bool UnwrapInt32ByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, int32_t &value); /** * @brief Get the native number(double) from the JSObject of the given property name. @@ -86,11 +115,11 @@ bool GetInt64ByPropertyName(napi_env env, napi_value jsObject, const char *prope * @param env The environment that the Node-API call is invoked under. * @param jsObject Indicates object passed by JS. * @param propertyName Indicates the name of the property. - * @param nativeValue Indicates the returned native value. + * @param value Indicates the returned native value. * * @return Return true if successful, else return false. */ -bool GetDoubleByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, double &nativeValue); +bool UnwrapDoubleByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, double &value); /** * @brief Get the native boolean from the JSObject of the given property name. @@ -98,110 +127,105 @@ bool GetDoubleByPropertyName(napi_env env, napi_value jsObject, const char *prop * @param env The environment that the Node-API call is invoked under. * @param jsObject Indicates object passed by JS. * @param propertyName Indicates the name of the property. - * @param nativeValue Indicates the returned native value. + * @param value Indicates the returned native value. * * @return Return true if successful, else return false. */ -bool GetBooleanByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, bool &nativeValue); +bool UnwrapBooleanByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, bool &value); +bool UnwrapBooleanArrayByPropertyName( + napi_env env, napi_value jsObject, const char *propertyName, std::vector &value); /** - * @brief Get the JSObject from the JSObject of the given property name. + * @brief Get the native string from the JSObject of the given property name. * * @param env The environment that the Node-API call is invoked under. * @param jsObject Indicates object passed by JS. * @param propertyName Indicates the name of the property. + * @param value Indicates the returned native value. * - * @return Return value of JSObject if successful, else return nullptr. + * @return Return true if successful, else return false. */ -napi_value GetObjectByPropertyName(napi_env env, napi_value jsObject, const char *propertyName); +bool UnwrapStringByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, std::string &value); +bool UnwrapStringArrayByPropertyName( + napi_env env, napi_value jsObject, const char *propertyName, std::vector &value); -/** - * @brief Get the native array of string from the JSObject of the given property name. - * - * @param env The environment that the Node-API call is invoked under. - * @param jsObject Indicates object passed by JS. - * @param propertyName Indicates the name of the property. - * @param nativeValue Indicates the returned native value. - * - */ -void GetStringArrayByPropertyName( - napi_env env, napi_value jsObject, const char *propertyName, std::vector &nativeValue); +bool UnwrapComplexArrayByPropertyName( + napi_env env, napi_value jsObject, const char *propertyName, ComplexArrayData &value); + +void ClearThreadReturnData(ThreadReturnData *data); + +napi_value GetCallbackErrorValue(napi_env env, int errCode); /** - * @brief Parse and set WantOptions from the JSObject of the given property name. - * Get the native array of string from the JSObject of the given property name. + * @brief Create asynchronous data. * * @param env The environment that the Node-API call is invoked under. - * @param jsObject Indicates object passed by JS. - * @param propertyName Indicates the name of the property. - * @param nativeValue Indicates the returned native value. * + * @return Return a pointer to AsyncJSCallbackInfo on success, nullptr on failure */ -void GetWantOptions(napi_env env, napi_value jsObject, const char *propertyName, Want &want); +AsyncJSCallbackInfo *CreateAsyncJSCallbackInfo(napi_env env); /** - * @brief Parse the want parameters. + * @brief Convert local data to JS data. * - * @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. + * @param data The local data. + * @param value the JS data. * * @return The return value from NAPI C++ to JS for the module. */ -napi_value UnwrapWant(Want ¶m, napi_env env, napi_value args); -napi_value WrapWant(const Want ¶m, napi_env env); +bool WrapThreadReturnData(napi_env env, const ThreadReturnData *data, napi_value *value); + /** - * @brief Parse the elementName parameters. + * @brief Create asynchronous data. * - * @param param Indicates the elementName 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. + * @param param Parameter list. + * @param callback Point to asynchronous processing of data. * - * @return The return value from NAPI C++ to JS for the module. + * @return Return true successfully, otherwise return false. */ -void UnwrapElementName(Want ¶m, napi_env env, napi_value args); -napi_value WrapElementName(const Want ¶m, napi_env env, napi_value jsWant); +bool CreateAsyncCallback(napi_env env, napi_value param, AsyncJSCallbackInfo *callback); + +napi_ref CreateCallbackRefFromJS(napi_env env, napi_value param); /** - * @brief Parse the wantParam parameters. + * @brief Asynchronous callback processing. * - * @param param Indicates the wantParam 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. + * @param asyncCallbackInfo Process data asynchronously. + * @param param other param. * - * @return The return value from NAPI C++ to JS for the module. + * @return Return JS data successfully, otherwise return nullptr. */ -napi_value UnwrapWantParam(Want &want, napi_env env, napi_value wantParam); -napi_value WrapWantParam(const Want &want, napi_env env); -napi_value WrapEntries(const Want &want, napi_env env); +napi_value ExecuteAsyncCallbackWork(napi_env env, AsyncJSCallbackInfo *asyncCallbackInfo, const AsyncParamEx *param); /** - * @brief Parse the wantParamArray parameters. + * @brief Asynchronous promise processing. * - * @param param Indicates the wantParamArray parameters saved the parse result. * @param env The environment that the Node-API call is invoked under. + * @param asyncCallbackInfo Process data asynchronously. + * @param param other param. * - * @return The return value from NAPI C++ to JS for the module. + * @return Return JS data successfully, otherwise return nullptr. */ -napi_value UnwrapWantParamArray(Want &want, napi_env env, std::string strProName, napi_value wantParam); +napi_value ExecutePromiseCallbackWork(napi_env env, AsyncJSCallbackInfo *asyncCallbackInfo, const AsyncParamEx *param); /** - * @brief Init param of wantOptions. + * @brief The callback at the end of the asynchronous callback. * - * @param flagMap Indicates flag of list in Want . + * @param env The environment that the Node-API call is invoked under. + * @param data Point to asynchronous processing of data. */ -void InitWantOptionsData(std::map &flagMap); +void CompleteAsyncCallbackWork(napi_env env, napi_status status, void *data); /** - * @brief Wrap the wantOptions parameters. + * @brief The callback at the end of the Promise callback. * - * @param param Indicates the wantOptions parameters saved the parse result. * @param env The environment that the Node-API call is invoked under. - * - * @return The return value from NAPI C++ to JS for the module. + * @param data Point to asynchronous processing of data. */ -napi_value WrapWantOptions(const Want &want, napi_env env); - +void CompletePromiseCallbackWork(napi_env env, napi_status status, void *data); } // namespace AppExecFwk } // namespace OHOS -#endif /* OHOS_APPEXECFWK_WANT_WRAPPER_H */ +#endif // OHOS_APPEXECFWK_NAPI_COMMON_UTIL_H 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 new file mode 100755 index 0000000000000000000000000000000000000000..15ff59ba40425034a27997abf0748fb1737a53fe --- /dev/null +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.cpp @@ -0,0 +1,818 @@ +/* + * 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_common_want.h" +#include "napi_common_util.h" +#include "hilog_wrapper.h" +#include "ohos/aafwk/content/want_params_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { + +/** + * @brief Init param of wantOptions. + * + * @param flagMap Indicates flag of list in Want . + */ +void InnerInitWantOptionsData(std::map &flagMap) +{ + flagMap.emplace("authReadUriPermission", Want::FLAG_AUTH_READ_URI_PERMISSION); + flagMap.emplace("authWriteUriPermission", Want::FLAG_AUTH_WRITE_URI_PERMISSION); + flagMap.emplace("abilityForwardResult", Want::FLAG_ABILITY_FORWARD_RESULT); + flagMap.emplace("abilityContinuation", Want::FLAG_ABILITY_CONTINUATION); + flagMap.emplace("notOhosComponent", Want::FLAG_NOT_OHOS_COMPONENT); + flagMap.emplace("abilityFormEnabled", Want::FLAG_ABILITY_FORM_ENABLED); + flagMap.emplace("authPersistableUriPermission", Want::FLAG_AUTH_PERSISTABLE_URI_PERMISSION); + flagMap.emplace("authPrefixUriPermission", Want::FLAG_AUTH_PREFIX_URI_PERMISSION); + flagMap.emplace("abilitySliceMultiDevice", Want::FLAG_ABILITYSLICE_MULTI_DEVICE); + flagMap.emplace("startForegroundAbility", Want::FLAG_START_FOREGROUND_ABILITY); + flagMap.emplace("installOnDemand", Want::FLAG_INSTALL_ON_DEMAND); + flagMap.emplace("abilitySliceForwardResult", Want::FLAG_ABILITYSLICE_FORWARD_RESULT); + flagMap.emplace("installWithBackgroundMode", Want::FLAG_INSTALL_WITH_BACKGROUND_MODE); +} + +napi_value WrapElementName(napi_env env, const ElementName &elementName) +{ + HILOG_INFO("%{public}s called.", __func__); + + napi_value jsObject = nullptr; + NAPI_CALL(env, napi_create_object(env, &jsObject)); + + napi_value jsValue = nullptr; + HILOG_INFO("%{public}s called. deviceID=%{public}s", __func__, elementName.GetDeviceID().c_str()); + NAPI_CALL(env, napi_create_string_utf8(env, elementName.GetDeviceID().c_str(), NAPI_AUTO_LENGTH, &jsValue)); + NAPI_CALL(env, napi_set_named_property(env, jsObject, "deviceId", jsValue)); + + jsValue = nullptr; + HILOG_INFO("%{public}s called. GetBundleName=%{public}s", __func__, elementName.GetBundleName().c_str()); + NAPI_CALL(env, napi_create_string_utf8(env, elementName.GetBundleName().c_str(), NAPI_AUTO_LENGTH, &jsValue)); + NAPI_CALL(env, napi_set_named_property(env, jsObject, "bundleName", jsValue)); + + jsValue = nullptr; + HILOG_INFO("%{public}s called. GetAbilityName=%{public}s", __func__, elementName.GetAbilityName().c_str()); + NAPI_CALL(env, napi_create_string_utf8(env, elementName.GetAbilityName().c_str(), NAPI_AUTO_LENGTH, &jsValue)); + NAPI_CALL(env, napi_set_named_property(env, jsObject, "abilityName", jsValue)); + + return jsObject; +} + +bool UnwrapElementName(napi_env env, napi_value param, ElementName &elementName) +{ + HILOG_INFO("%{public}s called.", __func__); + + std::string natValue(""); + if (UnwrapStringByPropertyName(env, param, "deviceId", natValue)) { + elementName.SetDeviceID(natValue); + } + + natValue = ""; + if (UnwrapStringByPropertyName(env, param, "bundleName", natValue)) { + elementName.SetBundleName(natValue); + } + + natValue = ""; + if (UnwrapStringByPropertyName(env, param, "abilityName", natValue)) { + elementName.SetAbilityName(natValue); + } + return true; +} + +bool InnerWrapWantParamsString( + napi_env env, napi_value jsObject, const std::string &key, const AAFwk::WantParams &wantParams) +{ + auto value = wantParams.GetParam(key); + AAFwk::IString *ao = AAFwk::IString::Query(value); + if (ao != nullptr) { + std::string natValue = AAFwk::String::Unbox(ao); + HILOG_INFO("%{public}s called. key=%{public}s, natValue=%{public}s", __func__, key.c_str(), natValue.c_str()); + napi_value jsValue = WrapStringToJS(env, natValue); + if (jsValue != nullptr) { + NAPI_CALL_BASE(env, napi_set_named_property(env, jsObject, key.c_str(), jsValue), false); + return true; + } + } + return false; +} + +bool InnerWrapWantParamsBool( + napi_env env, napi_value jsObject, const std::string &key, const AAFwk::WantParams &wantParams) +{ + auto value = wantParams.GetParam(key); + AAFwk::IBoolean *bo = AAFwk::IBoolean::Query(value); + if (bo != nullptr) { + bool natValue = AAFwk::Boolean::Unbox(bo); + napi_value jsValue = WrapBoolToJS(env, natValue); + if (jsValue != nullptr) { + NAPI_CALL_BASE(env, napi_set_named_property(env, jsObject, key.c_str(), jsValue), false); + return true; + } + } + return false; +} + +bool InnerWrapWantParamsShort( + napi_env env, napi_value jsObject, const std::string &key, const AAFwk::WantParams &wantParams) +{ + auto value = wantParams.GetParam(key); + AAFwk::IShort *ao = AAFwk::IShort::Query(value); + if (ao != nullptr) { + short natValue = AAFwk::Short::Unbox(ao); + napi_value jsValue = WrapInt32ToJS(env, natValue); + if (jsValue != nullptr) { + NAPI_CALL_BASE(env, napi_set_named_property(env, jsObject, key.c_str(), jsValue), false); + return true; + } + } + return false; +} + +bool InnerWrapWantParamsInt32( + napi_env env, napi_value jsObject, const std::string &key, const AAFwk::WantParams &wantParams) +{ + auto value = wantParams.GetParam(key); + AAFwk::IInteger *ao = AAFwk::IInteger::Query(value); + if (ao != nullptr) { + int natValue = AAFwk::Integer::Unbox(ao); + HILOG_INFO("%{public}s called. key=%{public}s, natValue=%{public}d", __func__, key.c_str(), natValue); + napi_value jsValue = WrapInt32ToJS(env, natValue); + if (jsValue != nullptr) { + NAPI_CALL_BASE(env, napi_set_named_property(env, jsObject, key.c_str(), jsValue), false); + return true; + } + } + return false; +} + +bool InnerWrapWantParamsLong( + napi_env env, napi_value jsObject, const std::string &key, const AAFwk::WantParams &wantParams) +{ + auto value = wantParams.GetParam(key); + AAFwk::ILong *ao = AAFwk::ILong::Query(value); + if (ao != nullptr) { + long natValue = AAFwk::Long::Unbox(ao); + napi_value jsValue = WrapLongToJS(env, natValue); + if (jsValue != nullptr) { + NAPI_CALL_BASE(env, napi_set_named_property(env, jsObject, key.c_str(), jsValue), false); + return true; + } + } + return false; +} + +bool InnerWrapWantParamsFloat( + napi_env env, napi_value jsObject, const std::string &key, const AAFwk::WantParams &wantParams) +{ + auto value = wantParams.GetParam(key); + AAFwk::IFloat *ao = AAFwk::IFloat::Query(value); + if (ao != nullptr) { + float natValue = AAFwk::Float::Unbox(ao); + napi_value jsValue = WrapDoubleToJS(env, natValue); + if (jsValue != nullptr) { + NAPI_CALL_BASE(env, napi_set_named_property(env, jsObject, key.c_str(), jsValue), false); + return true; + } + } + return false; +} + +bool InnerWrapWantParamsDouble( + napi_env env, napi_value jsObject, const std::string &key, const AAFwk::WantParams &wantParams) +{ + auto value = wantParams.GetParam(key); + AAFwk::IDouble *ao = AAFwk::IDouble::Query(value); + if (ao != nullptr) { + double natValue = AAFwk::Double::Unbox(ao); + napi_value jsValue = WrapDoubleToJS(env, natValue); + if (jsValue != nullptr) { + NAPI_CALL_BASE(env, napi_set_named_property(env, jsObject, key.c_str(), jsValue), false); + return true; + } + } + return false; +} + +bool InnerWrapWantParamsWantParams( + napi_env env, napi_value jsObject, const std::string &key, const AAFwk::WantParams &wantParams) +{ + HILOG_INFO("%{public}s called. key=%{public}s", __func__, key.c_str()); + auto value = wantParams.GetParam(key); + AAFwk::IWantParams *o = AAFwk::IWantParams::Query(value); + if (o != nullptr) { + AAFwk::WantParams wp = AAFwk::WantParamWrapper::Unbox(o); + napi_value jsValue = WrapWantParams(env, wp); + if (jsValue != nullptr) { + NAPI_CALL_BASE(env, napi_set_named_property(env, jsObject, key.c_str(), jsValue), false); + return true; + } + } + return false; +} + +bool InnerWrapWantParamsArrayString(napi_env env, napi_value jsObject, const std::string &key, sptr &ao) +{ + long size = 0; + if (ao->GetLength(size) != ERR_OK) { + return false; + } + + std::vector natArray; + for (long i = 0; i < size; i++) { + sptr iface = nullptr; + if (ao->Get(i, iface) == ERR_OK) { + AAFwk::IString *iValue = AAFwk::IString::Query(iface); + if (iValue != nullptr) { + natArray.push_back(AAFwk::String::Unbox(iValue)); + } + } + } + + napi_value jsValue = WrapArrayStringToJS(env, natArray); + if (jsValue != nullptr) { + NAPI_CALL_BASE(env, napi_set_named_property(env, jsObject, key.c_str(), jsValue), false); + return true; + } + return false; +} + +bool InnerWrapWantParamsArrayBool(napi_env env, napi_value jsObject, const std::string &key, sptr &ao) +{ + long size = 0; + if (ao->GetLength(size) != ERR_OK) { + return false; + } + + std::vector natArray; + for (long i = 0; i < size; i++) { + sptr iface = nullptr; + if (ao->Get(i, iface) == ERR_OK) { + AAFwk::IBoolean *iValue = AAFwk::IBoolean::Query(iface); + if (iValue != nullptr) { + natArray.push_back(AAFwk::Boolean::Unbox(iValue)); + } + } + } + + napi_value jsValue = WrapArrayBoolToJS(env, natArray); + if (jsValue != nullptr) { + NAPI_CALL_BASE(env, napi_set_named_property(env, jsObject, key.c_str(), jsValue), false); + return true; + } + return false; +} + +bool InnerWrapWantParamsArrayShort(napi_env env, napi_value jsObject, const std::string &key, sptr &ao) +{ + long size = 0; + if (ao->GetLength(size) != ERR_OK) { + return false; + } + + std::vector natArray; + for (long i = 0; i < size; i++) { + sptr iface = nullptr; + if (ao->Get(i, iface) == ERR_OK) { + AAFwk::IShort *iValue = AAFwk::IShort::Query(iface); + if (iValue != nullptr) { + natArray.push_back(AAFwk::Short::Unbox(iValue)); + } + } + } + + napi_value jsValue = WrapArrayInt32ToJS(env, natArray); + if (jsValue != nullptr) { + NAPI_CALL_BASE(env, napi_set_named_property(env, jsObject, key.c_str(), jsValue), false); + return true; + } + return false; +} + +bool InnerWrapWantParamsArrayInt32(napi_env env, napi_value jsObject, const std::string &key, sptr &ao) +{ + long size = 0; + if (ao->GetLength(size) != ERR_OK) { + return false; + } + + std::vector natArray; + for (long i = 0; i < size; i++) { + sptr iface = nullptr; + if (ao->Get(i, iface) == ERR_OK) { + AAFwk::IInteger *iValue = AAFwk::IInteger::Query(iface); + if (iValue != nullptr) { + natArray.push_back(AAFwk::Integer::Unbox(iValue)); + } + } + } + + napi_value jsValue = WrapArrayInt32ToJS(env, natArray); + if (jsValue != nullptr) { + NAPI_CALL_BASE(env, napi_set_named_property(env, jsObject, key.c_str(), jsValue), false); + return true; + } + return false; +} + +bool InnerWrapWantParamsArrayLong(napi_env env, napi_value jsObject, const std::string &key, sptr &ao) +{ + long size = 0; + if (ao->GetLength(size) != ERR_OK) { + return false; + } + + std::vector natArray; + for (long i = 0; i < size; i++) { + sptr iface = nullptr; + if (ao->Get(i, iface) == ERR_OK) { + AAFwk::ILong *iValue = AAFwk::ILong::Query(iface); + if (iValue != nullptr) { + natArray.push_back(AAFwk::Long::Unbox(iValue)); + } + } + } + + napi_value jsValue = WrapArrayLongToJS(env, natArray); + if (jsValue != nullptr) { + NAPI_CALL_BASE(env, napi_set_named_property(env, jsObject, key.c_str(), jsValue), false); + return true; + } + return false; +} + +bool InnerWrapWantParamsArrayFloat(napi_env env, napi_value jsObject, const std::string &key, sptr &ao) +{ + long size = 0; + if (ao->GetLength(size) != ERR_OK) { + return false; + } + + std::vector natArray; + for (long i = 0; i < size; i++) { + sptr iface = nullptr; + if (ao->Get(i, iface) == ERR_OK) { + AAFwk::IFloat *iValue = AAFwk::IFloat::Query(iface); + if (iValue != nullptr) { + natArray.push_back(AAFwk::Float::Unbox(iValue)); + } + } + } + + napi_value jsValue = WrapArrayDoubleToJS(env, natArray); + if (jsValue != nullptr) { + NAPI_CALL_BASE(env, napi_set_named_property(env, jsObject, key.c_str(), jsValue), false); + return true; + } + return false; +} + +bool InnerWrapWantParamsArrayDouble(napi_env env, napi_value jsObject, const std::string &key, sptr &ao) +{ + long size = 0; + if (ao->GetLength(size) != ERR_OK) { + return false; + } + + std::vector natArray; + for (long i = 0; i < size; i++) { + sptr iface = nullptr; + if (ao->Get(i, iface) == ERR_OK) { + AAFwk::IDouble *iValue = AAFwk::IDouble::Query(iface); + if (iValue != nullptr) { + natArray.push_back(AAFwk::Double::Unbox(iValue)); + } + } + } + + napi_value jsValue = WrapArrayDoubleToJS(env, natArray); + if (jsValue != nullptr) { + NAPI_CALL_BASE(env, napi_set_named_property(env, jsObject, key.c_str(), jsValue), false); + return true; + } + return false; +} + +bool InnerWrapWantParamsArray(napi_env env, napi_value jsObject, const std::string &key, sptr &ao) +{ + if (AAFwk::Array::IsStringArray(ao)) { + return InnerWrapWantParamsArrayString(env, jsObject, key, ao); + } else if (AAFwk::Array::IsBooleanArray(ao)) { + return InnerWrapWantParamsArrayBool(env, jsObject, key, ao); + } else if (AAFwk::Array::IsShortArray(ao)) { + return InnerWrapWantParamsArrayShort(env, jsObject, key, ao); + } else if (AAFwk::Array::IsIntegerArray(ao)) { + return InnerWrapWantParamsArrayInt32(env, jsObject, key, ao); + } else if (AAFwk::Array::IsLongArray(ao)) { + return InnerWrapWantParamsArrayLong(env, jsObject, key, ao); + } else if (AAFwk::Array::IsFloatArray(ao)) { + return InnerWrapWantParamsArrayFloat(env, jsObject, key, ao); + } else if (AAFwk::Array::IsDoubleArray(ao)) { + return InnerWrapWantParamsArrayDouble(env, jsObject, key, ao); + } else { + return false; + } +} + +napi_value WrapWantParams(napi_env env, const AAFwk::WantParams &wantParams) +{ + HILOG_INFO("%{public}s called.", __func__); + napi_value jsObject = nullptr; + NAPI_CALL(env, napi_create_object(env, &jsObject)); + + napi_value jsValue = nullptr; + const std::map> paramList = wantParams.GetParams(); + for (auto iter = paramList.begin(); iter != paramList.end(); iter++) { + jsValue = nullptr; + if (AAFwk::IString::Query(iter->second) != nullptr) { + InnerWrapWantParamsString(env, jsObject, iter->first, wantParams); + } else if (AAFwk::IBoolean::Query(iter->second) != nullptr) { + InnerWrapWantParamsBool(env, jsObject, iter->first, wantParams); + } else if (AAFwk::IShort::Query(iter->second) != nullptr) { + InnerWrapWantParamsShort(env, jsObject, iter->first, wantParams); + } else if (AAFwk::IInteger::Query(iter->second) != nullptr) { + InnerWrapWantParamsInt32(env, jsObject, iter->first, wantParams); + } else if (AAFwk::ILong::Query(iter->second) != nullptr) { + InnerWrapWantParamsLong(env, jsObject, iter->first, wantParams); + } else if (AAFwk::IFloat::Query(iter->second) != nullptr) { + InnerWrapWantParamsFloat(env, jsObject, iter->first, wantParams); + } else if (AAFwk::IDouble::Query(iter->second) != nullptr) { + InnerWrapWantParamsDouble(env, jsObject, iter->first, wantParams); + } else if (AAFwk::IArray::Query(iter->second) != nullptr) { + AAFwk::IArray *ao = AAFwk::IArray::Query(iter->second); + if (ao != nullptr) { + sptr array(ao); + InnerWrapWantParamsArray(env, jsObject, iter->first, array); + } + } else if (AAFwk::IWantParams::Query(iter->second) != nullptr) { + InnerWrapWantParamsWantParams(env, jsObject, iter->first, wantParams); + } + } + return jsObject; +} + +bool InnerSetWantParamsArrayString( + const std::string &key, const std::vector &value, AAFwk::WantParams &wantParams) +{ + long size = value.size(); + sptr ao = new (std::nothrow) AAFwk::Array(size, AAFwk::g_IID_IString); + if (ao != nullptr) { + for (long i = 0; i < size; i++) { + ao->Set(i, AAFwk::String::Box(value[i])); + } + wantParams.SetParam(key, ao); + return true; + } else { + return false; + } +} + +bool InnerSetWantParamsArrayInt(const std::string &key, const std::vector &value, AAFwk::WantParams &wantParams) +{ + long size = value.size(); + sptr ao = new (std::nothrow) AAFwk::Array(size, AAFwk::g_IID_IInteger); + if (ao != nullptr) { + for (long i = 0; i < size; i++) { + ao->Set(i, AAFwk::Integer::Box(value[i])); + } + wantParams.SetParam(key, ao); + return true; + } else { + return false; + } +} + +bool InnerSetWantParamsArrayLong(const std::string &key, const std::vector &value, AAFwk::WantParams &wantParams) +{ + long size = value.size(); + sptr ao = new (std::nothrow) AAFwk::Array(size, AAFwk::g_IID_ILong); + if (ao != nullptr) { + for (long i = 0; i < size; i++) { + ao->Set(i, AAFwk::Long::Box(value[i])); + } + wantParams.SetParam(key, ao); + return true; + } else { + return false; + } +} + +bool InnerSetWantParamsArrayBool(const std::string &key, const std::vector &value, AAFwk::WantParams &wantParams) +{ + long size = value.size(); + sptr ao = new (std::nothrow) AAFwk::Array(size, AAFwk::g_IID_IBoolean); + if (ao != nullptr) { + for (long i = 0; i < size; i++) { + ao->Set(i, AAFwk::Boolean::Box(value[i])); + } + wantParams.SetParam(key, ao); + return true; + } else { + return false; + } +} + +bool InnerSetWantParamsArrayDouble( + const std::string &key, const std::vector &value, AAFwk::WantParams &wantParams) +{ + long size = value.size(); + sptr ao = new (std::nothrow) AAFwk::Array(size, AAFwk::g_IID_IDouble); + if (ao != nullptr) { + for (long i = 0; i < size; i++) { + ao->Set(i, AAFwk::Double::Box(value[i])); + } + wantParams.SetParam(key, ao); + return true; + } else { + return false; + } +} + +bool InnerUnwrapWantParamsArray(napi_env env, const std::string &key, napi_value param, AAFwk::WantParams &wantParams) +{ + HILOG_INFO("%{public}s called.", __func__); + + ComplexArrayData natArrayValue; + if (!UnwrapArrayComplexFromJS(env, param, natArrayValue)) { + return false; + } + + if (natArrayValue.stringList.size() > 0) { + return InnerSetWantParamsArrayString(key, natArrayValue.stringList, wantParams); + } + if (natArrayValue.intList.size() > 0) { + return InnerSetWantParamsArrayInt(key, natArrayValue.intList, wantParams); + } + if (natArrayValue.longList.size() > 0) { + return InnerSetWantParamsArrayLong(key, natArrayValue.longList, wantParams); + } + if (natArrayValue.boolList.size() > 0) { + return InnerSetWantParamsArrayBool(key, natArrayValue.boolList, wantParams); + } + if (natArrayValue.doubleList.size() > 0) { + return InnerSetWantParamsArrayDouble(key, natArrayValue.doubleList, wantParams); + } + + return false; +} + +bool InnerUnwrapWantParams(napi_env env, const std::string &key, napi_value param, AAFwk::WantParams &wantParams) +{ + HILOG_INFO("%{public}s called.", __func__); + AAFwk::WantParams wp; + + if (UnwrapWantParams(env, param, wp)) { + sptr pWantParams = AAFwk::WantParamWrapper::Box(wp); + if (pWantParams != nullptr) { + wantParams.SetParam(key, pWantParams); + return true; + } + } + return false; +} + +bool UnwrapWantParams(napi_env env, napi_value param, AAFwk::WantParams &wantParams) +{ + HILOG_INFO("%{public}s called.", __func__); + + 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); + + switch (jsValueType) { + case napi_string: { + std::string natValue = UnwrapStringFromJS(env, jsProValue); + HILOG_INFO("%{public}s called. Property value=%{public}s.", __func__, natValue.c_str()); + wantParams.SetParam(strProName, AAFwk::String::Box(natValue)); + break; + } + case napi_boolean: { + bool natValue = false; + NAPI_CALL_BASE(env, napi_get_value_bool(env, jsProValue, &natValue), false); + HILOG_INFO("%{public}s called. Property value=%{public}s.", __func__, natValue ? "true" : "false"); + wantParams.SetParam(strProName, AAFwk::Boolean::Box(natValue)); + break; + } + case napi_number: { + int32_t natValue32 = 0; + double natValueDouble = 0.0; + bool isReadValue32 = false; + bool isReadDouble = false; + if (napi_get_value_int32(env, jsProValue, &natValue32) == napi_ok) { + HILOG_INFO("%{public}s called. Property value=%{public}d.", __func__, natValue32); + isReadValue32 = true; + } + + if (napi_get_value_double(env, jsProValue, &natValueDouble) == napi_ok) { + HILOG_INFO("%{public}s called. Property value=%{public}lf.", __func__, natValueDouble); + isReadDouble = true; + } + + if (isReadValue32 && isReadDouble) { + if (abs(natValueDouble - natValue32 * 1.0) > 0.0) { + wantParams.SetParam(strProName, AAFwk::Double::Box(natValueDouble)); + } else { + wantParams.SetParam(strProName, AAFwk::Integer::Box(natValue32)); + } + } else if (isReadValue32) { + wantParams.SetParam(strProName, AAFwk::Integer::Box(natValue32)); + } else if (isReadDouble) { + wantParams.SetParam(strProName, AAFwk::Double::Box(natValueDouble)); + } + break; + } + case napi_object: { + bool isArray = false; + if (napi_is_array(env, jsProValue, &isArray) == napi_ok) { + if (isArray) { + HILOG_INFO("%{public}s called. %{public}s is array.", __func__, strProName.c_str()); + InnerUnwrapWantParamsArray(env, strProName, jsProValue, wantParams); + } else { + HILOG_INFO("%{public}s called. %{public}s is wantparams.", __func__, strProName.c_str()); + InnerUnwrapWantParams(env, strProName, jsProValue, wantParams); + } + } + break; + } + default: + break; + } + } + + return true; +} + +napi_value InnerWrapWantOptions(napi_env env, const Want &want) +{ + HILOG_INFO("%{public}s called.", __func__); + napi_value jsObject = nullptr; + std::map flagMap; + InnerInitWantOptionsData(flagMap); + unsigned int flags = want.GetFlags(); + bool natValue = false; + napi_value jsValue = nullptr; + + NAPI_CALL(env, napi_create_object(env, &jsObject)); + for (auto iter = flagMap.begin(); iter != flagMap.end(); iter++) { + jsValue = nullptr; + natValue = ((flags & iter->second) == iter->second); + if (napi_get_boolean(env, natValue, &jsValue) == napi_ok) { + SetPropertyValueByPropertyName(env, jsObject, iter->first.c_str(), jsValue); + } + } + + return jsObject; +} + +bool InnerUnwrapWantOptions(napi_env env, napi_value param, const char *propertyName, Want &want) +{ + napi_value jsValue = GetPropertyValueByPropertyName(env, param, propertyName, napi_object); + if (jsValue == nullptr) { + return false; + } + + bool natValue = false; + unsigned int flags = 0; + std::map flagMap; + InnerInitWantOptionsData(flagMap); + for (auto iter = flagMap.begin(); iter != flagMap.end(); iter++) { + natValue = false; + if (UnwrapBooleanByPropertyName(env, jsValue, iter->first.c_str(), natValue)) { + if (natValue) { + flags |= iter->second; + } + } + } + + want.SetFlags(flags); + return true; +} + +napi_value WrapWant(napi_env env, const Want &want) +{ + HILOG_INFO("%{public}s called.", __func__); + napi_value jsObject = nullptr; + napi_value jsValue = nullptr; + + NAPI_CALL(env, napi_create_object(env, &jsObject)); + + napi_value jsElementName = WrapElementName(env, want.GetElement()); + if (jsElementName == nullptr) { + HILOG_INFO("%{public}s called. Invoke WrapElementName failed.", __func__); + return nullptr; + } + + jsValue = GetPropertyValueByPropertyName(env, jsElementName, "deviceId", napi_string); + SetPropertyValueByPropertyName(env, jsObject, "deviceId", jsValue); + + jsValue = nullptr; + jsValue = GetPropertyValueByPropertyName(env, jsElementName, "bundleName", napi_string); + SetPropertyValueByPropertyName(env, jsObject, "bundleName", jsValue); + + jsValue = nullptr; + jsValue = GetPropertyValueByPropertyName(env, jsElementName, "abilityName", napi_string); + SetPropertyValueByPropertyName(env, jsObject, "abilityName", jsValue); + + jsValue = nullptr; + jsValue = WrapStringToJS(env, want.GetUriString()); + SetPropertyValueByPropertyName(env, jsObject, "uri", jsValue); + + jsValue = nullptr; + jsValue = WrapStringToJS(env, want.GetType()); + SetPropertyValueByPropertyName(env, jsObject, "type", jsValue); + + jsValue = nullptr; + jsValue = InnerWrapWantOptions(env, want); + SetPropertyValueByPropertyName(env, jsObject, "options", jsValue); + + jsValue = nullptr; + jsValue = WrapStringToJS(env, want.GetAction()); + SetPropertyValueByPropertyName(env, jsObject, "action", jsValue); + + jsValue = nullptr; + jsValue = WrapWantParams(env, want.GetParams()); + SetPropertyValueByPropertyName(env, jsObject, "parameters", jsValue); + + jsValue = nullptr; + jsValue = WrapArrayStringToJS(env, want.GetEntities()); + SetPropertyValueByPropertyName(env, jsObject, "entities", jsValue); + + return jsObject; +} + +bool UnwrapWant(napi_env env, napi_value param, Want &want) +{ + HILOG_INFO("%{public}s called.", __func__); + + if (!IsTypeForNapiValue(env, param, napi_object)) { + HILOG_INFO("%{public}s called. Params is invalid.", __func__); + return false; + } + + napi_value jsValue = GetPropertyValueByPropertyName(env, param, "parameters", napi_object); + if (jsValue != nullptr) { + AAFwk::WantParams wantParams; + if (UnwrapWantParams(env, jsValue, wantParams)) { + want.SetParams(wantParams); + } + } + + std::string natValueString(""); + if (UnwrapStringByPropertyName(env, param, "action", natValueString)) { + want.SetAction(natValueString); + } + + std::vector natValueStringList; + if (UnwrapStringArrayByPropertyName(env, param, "entities", natValueStringList)) { + for (size_t i = 0; i < natValueStringList.size(); i++) { + want.AddEntity(natValueStringList[i]); + } + } + + natValueString = ""; + if (UnwrapStringByPropertyName(env, param, "uri", natValueString)) { + want.SetUri(natValueString); + } + + InnerUnwrapWantOptions(env, param, "options", want); + + ElementName natElementName; + UnwrapElementName(env, param, natElementName); + want.SetElementName(natElementName.GetDeviceID(), natElementName.GetBundleName(), natElementName.GetAbilityName()); + + natValueString = ""; + if (UnwrapStringByPropertyName(env, param, "type", natValueString)) { + want.SetType(natValueString); + } + + return true; +} +} // namespace AppExecFwk +} // namespace OHOS 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 new file mode 100755 index 0000000000000000000000000000000000000000..5d449d6edd30f5ec0f53b6e8406b5b681ff45efc --- /dev/null +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_want.h @@ -0,0 +1,40 @@ +/* + * 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_APPEXECFWK_NAPI_COMMON_WANT_H +#define OHOS_APPEXECFWK_NAPI_COMMON_WANT_H + +#include +#include +#include +#include "want.h" +#include "napi_common_data.h" +#include "want_params.h" + +namespace OHOS { +namespace AppExecFwk { + +napi_value WrapElementName(napi_env env, const ElementName &elementName); +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); + +napi_value WrapWant(napi_env env, const Want &want); +bool UnwrapWant(napi_env env, napi_value param, Want &want); + +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_APPEXECFWK_NAPI_COMMON_WANT_H diff --git a/services/abilitymgr/BUILD.gn b/services/abilitymgr/BUILD.gn index b0fbcad771cfe498a2fa059b46529be0c6f5a00e..5c39f87a528dc25ef723b52b53b3efe75264d9c4 100644 --- a/services/abilitymgr/BUILD.gn +++ b/services/abilitymgr/BUILD.gn @@ -14,7 +14,7 @@ import("//build/ohos.gni") import("//foundation/aafwk/standard/aafwk.gni") import("//foundation/aafwk/standard/services/abilitymgr/abilitymgr.gni") -EVENT_DIR = "//base/notification/ces_standard/cesfwk" +EVENT_DIR = "//base/notification/ces_standard/" group("abilityms_target") { deps = [ ":abilityms" ] @@ -29,8 +29,8 @@ group("unittest") { config("abilityms_config") { include_dirs = [ "include/", - "${EVENT_DIR}/innerkits/include", - "${EVENT_DIR}/kits/native/include", + "${EVENT_DIR}/frameworks/core/include", + "${EVENT_DIR}/interfaces/innerkits/native/include", "${innerkits_path}/ability_manager/include", "${innerkits_path}/base/include", "${innerkits_path}/want/include", @@ -59,7 +59,6 @@ ohos_shared_library("abilityms") { deps = [ "${innerkits_path}/want:want", - "//base/notification/ces_standard/cesfwk/kits/native:cesfwk_kits", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", "//foundation/aafwk/standard/interfaces/innerkits/base:base", @@ -73,6 +72,8 @@ ohos_shared_library("abilityms") { ] external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/abilitymgr/include/ability_manager_proxy.h b/services/abilitymgr/include/ability_manager_proxy.h index ff1f1470d5da34543aec4317e54a72f364727ea0..c67fa7582de73b9ceacaa6aaf7da7f64d57a4830 100644 --- a/services/abilitymgr/include/ability_manager_proxy.h +++ b/services/abilitymgr/include/ability_manager_proxy.h @@ -322,6 +322,23 @@ public: */ virtual int UnlockMission(int missionId) override; + /** + * Sets description information about the mission containing this ability. + * + * @param missionDescriptionInfo Indicates the object containing information about the + * mission. This parameter cannot be null. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int SetMissionDescriptionInfo( + const sptr &token, const MissionDescriptionInfo &missionDescriptionInfo) override; + + /** + * get current system mission lock mode state. + * + * @return Returns 0: LOCK_MISSION_STATE_NONE, 1: LOCK_MISSION_STATE_LOCKED + */ + virtual int GetMissionLockModeState() override; + virtual sptr GetWantSender( const WantSenderInfo &wantSenderInfo, const sptr &callerToken) override; diff --git a/services/abilitymgr/include/ability_manager_service.h b/services/abilitymgr/include/ability_manager_service.h index 4c84942e13808d0eaab00226bf271693bc455bc3..19463478d239f3d04947accf08af525753dd62e8 100644 --- a/services/abilitymgr/include/ability_manager_service.h +++ b/services/abilitymgr/include/ability_manager_service.h @@ -366,6 +366,23 @@ public: */ virtual int UnlockMission(int missionId) override; + /** + * Sets description information about the mission containing this ability. + * + * @param missionDescriptionInfo Indicates the object containing information about the + * mission. This parameter cannot be null. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int SetMissionDescriptionInfo( + const sptr &token, const MissionDescriptionInfo &missionDescriptionInfo) override; + + /** + * get current system mission lock mode state. + * + * @return Returns 0: LOCK_MISSION_STATE_NONE, 1: LOCK_MISSION_STATE_LOCKED + */ + virtual int GetMissionLockModeState() override; + /** * remove all service record. * diff --git a/services/abilitymgr/include/ability_manager_stub.h b/services/abilitymgr/include/ability_manager_stub.h index 85c6260e0e36f855505ba270e161d93e566125db..52a154b760e359564a59664eb15a2b4bbc389466 100644 --- a/services/abilitymgr/include/ability_manager_stub.h +++ b/services/abilitymgr/include/ability_manager_stub.h @@ -69,6 +69,8 @@ private: int PowerOnInner(MessageParcel &data, MessageParcel &reply); int LockMissionInner(MessageParcel &data, MessageParcel &reply); int UnlockMissionInner(MessageParcel &data, MessageParcel &reply); + int SetMissionDescriptionInfoInner(MessageParcel &data, MessageParcel &reply); + int GetMissionLockModeStateInner(MessageParcel &data, MessageParcel &reply); int GetWantSenderInner(MessageParcel &data, MessageParcel &reply); int SendWantSenderInner(MessageParcel &data, MessageParcel &reply); diff --git a/services/abilitymgr/include/ability_record.h b/services/abilitymgr/include/ability_record.h index 670e68c9042096265541bab54b08691f5eb2a462..71c3d7a05a6f3052f5810033b4a1b3ec4c0965ea 100644 --- a/services/abilitymgr/include/ability_record.h +++ b/services/abilitymgr/include/ability_record.h @@ -409,6 +409,9 @@ public: */ void CommandAbility(); + void SaveAbilityState(); + void RestoreAbilityState(); + /** * set the want for start ability. * @@ -445,12 +448,6 @@ public: */ void SendResult(); - /** - * Displays a system-defined message to the user, prompting the user how to exit the lock mission mode. - * - */ - void DisplayUnlockMissionMessage(); - /** * send result object to caller ability. * diff --git a/services/abilitymgr/include/ability_scheduler_proxy.h b/services/abilitymgr/include/ability_scheduler_proxy.h index e40f58d949fba094a50fb2395582b577c6b05c8a..67156c51e63583c04fa97f482e2101caf49e0b24 100644 --- a/services/abilitymgr/include/ability_scheduler_proxy.h +++ b/services/abilitymgr/include/ability_scheduler_proxy.h @@ -190,12 +190,6 @@ public: */ int BatchInsert(const Uri &uri, const std::vector &values) override; - /** - * @brief Displays a system-defined message to the user, prompting the user how to exit the lock mission mode. - * - */ - void DisplayUnlockMissionMessage() override; - private: bool WriteInterfaceToken(MessageParcel &data); diff --git a/services/abilitymgr/include/ability_scheduler_stub.h b/services/abilitymgr/include/ability_scheduler_stub.h index dbb85b6314a985784e883c57cedbd0243667cce7..50193495c0859084f90cf2abb39708c899fa62b6 100644 --- a/services/abilitymgr/include/ability_scheduler_stub.h +++ b/services/abilitymgr/include/ability_scheduler_stub.h @@ -54,7 +54,6 @@ private: int GetTypeInner(MessageParcel &data, MessageParcel &reply); int ReloadInner(MessageParcel &data, MessageParcel &reply); int BatchInsertInner(MessageParcel &data, MessageParcel &reply); - int DisplayUnlockMissionMessageInner(MessageParcel &data, MessageParcel &reply); using RequestFuncType = int (AbilitySchedulerStub::*)(MessageParcel &data, MessageParcel &reply); std::map requestFuncMap_; }; diff --git a/services/abilitymgr/include/ability_stack_manager.h b/services/abilitymgr/include/ability_stack_manager.h index bcf5f3ec0701064e3d960a130ae424d01746fb88..2f9a451ac01a7b97910ab064c4fc4091fd310899 100644 --- a/services/abilitymgr/include/ability_stack_manager.h +++ b/services/abilitymgr/include/ability_stack_manager.h @@ -324,6 +324,9 @@ public: int PowerOn(); int StartLockMission(int uid, int missionId, bool isSystemApp, int isLock); + int SetMissionDescriptionInfo( + const std::shared_ptr &abilityRecord, const MissionDescriptionInfo &missionDescriptionInfo); + int GetMissionLockModeState(); private: /** @@ -528,7 +531,7 @@ private: bool CanStartInLockMissionState( const AbilityRequest &abilityRequest, const std::shared_ptr ¤tTopAbility) const; bool CanStopInLockMissionState(const std::shared_ptr &terminateAbility) const; - void SendDisplayUnlockMissionMessage(); + void SendUnlockMissionMessage(); private: const std::string MISSION_NAME_MARK_HEAD = "#"; diff --git a/services/abilitymgr/include/lock_mission_container.h b/services/abilitymgr/include/lock_mission_container.h index 426cb9815c0a71889d5720ef082ba058d76efb5a..1b553f0b7b7e370565121951ffee18a6856aedf4 100644 --- a/services/abilitymgr/include/lock_mission_container.h +++ b/services/abilitymgr/include/lock_mission_container.h @@ -31,18 +31,21 @@ public: LockMissionContainer() = default; virtual ~LockMissionContainer() = default; + enum LockMissionState { LOCK_MISSION_STATE_NONE = 0, LOCK_MISSION_STATE_LOCKED, LOCK_MISSION_STATE_PINNED }; + bool IsLockedMissionState() const; - bool SetLockedMission(const std::shared_ptr &mission, int lockUid); + bool SetLockedMission(const std::shared_ptr &mission, int lockUid, bool isSystemApp); bool ReleaseLockedMission(const std::shared_ptr &mission, int callerUid, bool isForce); bool IsSameLockedMission(std::string bundleName) const; std::shared_ptr GetLockMission(); + int GetLockedMissionState() const; private: void Clear(); private: int lockerUid_ = -1; - bool isLocked_ = false; + LockMissionState lockState_ = LOCK_MISSION_STATE_NONE; std::weak_ptr lockMission_; }; } // namespace AAFwk diff --git a/services/abilitymgr/include/mission_record.h b/services/abilitymgr/include/mission_record.h index 9385d924f7b1872f8a1f250e09ba76bf7d2883e9..0b0470c532366545d4dc0d571a3e25c3fc2782e5 100644 --- a/services/abilitymgr/include/mission_record.h +++ b/services/abilitymgr/include/mission_record.h @@ -20,6 +20,7 @@ #include "ability_record.h" #include "mission_stack.h" +#include "mission_description_info.h" namespace OHOS { namespace AAFwk { @@ -194,6 +195,15 @@ public: return bundleName_; }; + void SetMissionDescriptionInfo(std::shared_ptr &missionDescriptionInfo) + { + missionDescriptionInfo_ = missionDescriptionInfo; + }; + std::shared_ptr GetMissionDescriptionInfo() const + { + return missionDescriptionInfo_; + }; + private: static int nextMissionId_; int missionId_; @@ -202,6 +212,8 @@ private: bool isLauncherCreate_ = false; std::weak_ptr preMissionRecord_; std::weak_ptr parentMissionStack_; + + std::shared_ptr missionDescriptionInfo_ = nullptr; }; // namespace AAFwk } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/pending_want_manager.h b/services/abilitymgr/include/pending_want_manager.h index 9041ab65b4aa608401514c9deef1254353412f8e..97e9fa9bb49716a3e6fc063f8d9326ac45b64ecf 100644 --- a/services/abilitymgr/include/pending_want_manager.h +++ b/services/abilitymgr/include/pending_want_manager.h @@ -25,7 +25,7 @@ #include "ability_manager_service.h" #include "ability_manager_errors.h" #include "ability_record.h" -#include "common_event_manager.h" +#include "common_event.h" #include "nocopyable.h" #include "pending_want_key.h" #include "pending_want_record.h" @@ -151,7 +151,7 @@ public: int32_t PendingWantStartAbility(const Want &want, const sptr &callerToken, int32_t requestCode); int32_t PendingWantStartAbilitys( const std::vector wnatsInfo, const sptr &callerToken, int32_t requestCode); - int32_t PendingWantPublishCommonEvent(const Want &want, const SenderInfo &senderInfo); + int32_t PendingWantPublishCommonEvent(const Want &want, const SenderInfo &senderInfo, int32_t callerUid); private: sptr GetWantSenderLocked(const int32_t callingUid, const int32_t uid, const int32_t userId, diff --git a/services/abilitymgr/include/pending_want_record.h b/services/abilitymgr/include/pending_want_record.h index d88091e99cc39e0c1e5e90c375440696b4225d05..de137ec2d4b81870133a1ed111cdb9dfb7416c8b 100644 --- a/services/abilitymgr/include/pending_want_record.h +++ b/services/abilitymgr/include/pending_want_record.h @@ -48,6 +48,7 @@ public: public: std::shared_ptr GetKey(); int32_t GetUid() const; + void SetCallerUid(const int32_t callerUid); void SetCanceled(); bool GetCanceled(); std::list> GetCancelCallbacks(); @@ -55,6 +56,7 @@ public: private: std::weak_ptr pendingWantManager_; int32_t uid_; + int32_t callerUid_; sptr callerToken_; bool canceled_ = false; std::shared_ptr key_; diff --git a/services/abilitymgr/src/ability_manager_client.cpp b/services/abilitymgr/src/ability_manager_client.cpp index 5d02f81ce12568044e2f9227cc126b57dffde960..54ea62983904b42017a8e8dee8909ab497dc1689 100644 --- a/services/abilitymgr/src/ability_manager_client.cpp +++ b/services/abilitymgr/src/ability_manager_client.cpp @@ -404,6 +404,27 @@ ErrCode AbilityManagerClient::UnlockMission(int missionId) return abms->UnlockMission(missionId); } +ErrCode AbilityManagerClient::SetMissionDescriptionInfo( + const sptr &token, const MissionDescriptionInfo &missionDescriptionInfo) +{ + if (remoteObject_ == nullptr) { + HILOG_ERROR("%{private}s:ability service not connect", __func__); + return ABILITY_SERVICE_NOT_CONNECTED; + } + sptr abms = iface_cast(remoteObject_); + return abms->SetMissionDescriptionInfo(token, missionDescriptionInfo); +} + +int AbilityManagerClient::GetMissionLockModeState() +{ + if (remoteObject_ == nullptr) { + HILOG_ERROR("%{private}s:ability service not connect", __func__); + return ABILITY_SERVICE_NOT_CONNECTED; + } + sptr abms = iface_cast(remoteObject_); + return abms->GetMissionLockModeState(); +} + sptr AbilityManagerClient::GetWantSender( const WantSenderInfo &wantSenderInfo, const sptr &callerToken) { diff --git a/services/abilitymgr/src/ability_manager_proxy.cpp b/services/abilitymgr/src/ability_manager_proxy.cpp index 642be7604591981a98bb552cdd17027001abe9cc..dca43305a1c59bc6728b77cdec01816c398b380f 100644 --- a/services/abilitymgr/src/ability_manager_proxy.cpp +++ b/services/abilitymgr/src/ability_manager_proxy.cpp @@ -818,6 +818,51 @@ int AbilityManagerProxy::UnlockMission(int missionId) return reply.ReadInt32(); } +int AbilityManagerProxy::SetMissionDescriptionInfo( + const sptr &token, const MissionDescriptionInfo &missionDescriptionInfo) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + if (!data.WriteParcelable(token)) { + HILOG_ERROR("%{public}s for result fail", __func__); + return false; + } + if (!data.WriteParcelable(&missionDescriptionInfo)) { + HILOG_ERROR("%{public}s for result fail", __func__); + return false; + } + error = Remote()->SendRequest(IAbilityManager::SET_MISSION_INFO, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("unlock mission by id , error: %d", error); + return error; + } + return reply.ReadInt32(); +} + +int AbilityManagerProxy::GetMissionLockModeState() +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return INNER_ERR; + } + error = Remote()->SendRequest(IAbilityManager::GET_MISSION_LOCK_MODE_STATE, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("get mission luck mode state , error: %d", error); + return error; + } + return reply.ReadInt32(); +} + sptr AbilityManagerProxy::GetWantSender( const WantSenderInfo &wantSenderInfo, const sptr &callerToken) { diff --git a/services/abilitymgr/src/ability_manager_service.cpp b/services/abilitymgr/src/ability_manager_service.cpp index 0b7db746a5dd508316605ecf697cf67f3af1593e..09b92eebb60d6b4a9041da23e9774f96d528fe06 100644 --- a/services/abilitymgr/src/ability_manager_service.cpp +++ b/services/abilitymgr/src/ability_manager_service.cpp @@ -296,6 +296,26 @@ int AbilityManagerService::GetMissionSnapshot(const int32_t missionId, MissionSn return 0; } +int AbilityManagerService::SetMissionDescriptionInfo( + const sptr &token, const MissionDescriptionInfo &missionDescriptionInfo) +{ + HILOG_INFO("%{public}s called", __func__); + CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE); + CHECK_POINTER_AND_RETURN(currentStackManager_, INNER_ERR); + + auto abilityRecord = Token::GetAbilityRecordByToken(token); + CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); + + return currentStackManager_->SetMissionDescriptionInfo(abilityRecord, missionDescriptionInfo); +} + +int AbilityManagerService::GetMissionLockModeState() +{ + HILOG_INFO("%{public}s called", __func__); + CHECK_POINTER_AND_RETURN(currentStackManager_, ERR_INVALID_VALUE); + return currentStackManager_->GetMissionLockModeState(); +} + int AbilityManagerService::MoveMissionToTop(int32_t missionId) { HILOG_INFO("%{public}s mission id: %d", __func__, missionId); diff --git a/services/abilitymgr/src/ability_manager_stub.cpp b/services/abilitymgr/src/ability_manager_stub.cpp index f424ce61c6646d232c86dbfa5819090e23bcabb7..9281226edb7a86085a23046ca849caf9fb70e2c8 100644 --- a/services/abilitymgr/src/ability_manager_stub.cpp +++ b/services/abilitymgr/src/ability_manager_stub.cpp @@ -72,6 +72,8 @@ AbilityManagerStub::AbilityManagerStub() requestFuncMap_[REGISTER_CANCEL_LISTENER] = &AbilityManagerStub::RegisterCancelListenerInner; requestFuncMap_[UNREGISTER_CANCEL_LISTENER] = &AbilityManagerStub::UnregisterCancelListenerInner; requestFuncMap_[GET_PENDING_REQUEST_WANT] = &AbilityManagerStub::GetPendingRequestWantInner; + requestFuncMap_[SET_MISSION_INFO] = &AbilityManagerStub::SetMissionDescriptionInfoInner; + requestFuncMap_[GET_MISSION_LOCK_MODE_STATE] = &AbilityManagerStub::GetMissionLockModeStateInner; } AbilityManagerStub::~AbilityManagerStub() @@ -466,6 +468,28 @@ int AbilityManagerStub::UnlockMissionInner(MessageParcel &data, MessageParcel &r return NO_ERROR; } +int AbilityManagerStub::SetMissionDescriptionInfoInner(MessageParcel &data, MessageParcel &reply) +{ + auto token = data.ReadParcelable(); + auto missionInfo = data.ReadParcelable(); + int result = SetMissionDescriptionInfo(token, *missionInfo); + if (!reply.WriteInt32(result)) { + HILOG_ERROR("AbilityManagerStub: set mission info failed."); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +int AbilityManagerStub::GetMissionLockModeStateInner(MessageParcel &data, MessageParcel &reply) +{ + int result = GetMissionLockModeState(); + if (!reply.WriteInt32(result)) { + HILOG_ERROR("AbilityManagerStub: get mission lock mode state failed."); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + int AbilityManagerStub::GetWantSenderInner(MessageParcel &data, MessageParcel &reply) { HILOG_INFO("%{public}s:begin.", __func__); diff --git a/services/abilitymgr/src/ability_record.cpp b/services/abilitymgr/src/ability_record.cpp index e76b739fca84b03a63f42953200eea7d8079778b..1240817fadd1d91b386acc4d416b7ccd38a021dc 100644 --- a/services/abilitymgr/src/ability_record.cpp +++ b/services/abilitymgr/src/ability_record.cpp @@ -440,6 +440,16 @@ void AbilityRecord::CommandAbility() lifecycleDeal_->CommandAbility(want_, false, startId_); } +void AbilityRecord::SaveAbilityState() +{ + HILOG_INFO("%{public}s", __func__); +} + +void AbilityRecord::RestoreAbilityState() +{ + HILOG_INFO("%{public}s", __func__); +} + void AbilityRecord::SetWant(const Want &want) { want_ = want; @@ -475,13 +485,6 @@ void AbilityRecord::SendResult() result_.reset(); } -void AbilityRecord::DisplayUnlockMissionMessage() -{ - HILOG_INFO("%{public}s", __func__); - CHECK_POINTER(scheduler_); - scheduler_->DisplayUnlockMissionMessage(); -} - void AbilityRecord::SendResultToCallers() { for (auto caller : GetCallerRecordList()) { diff --git a/services/abilitymgr/src/ability_scheduler_proxy.cpp b/services/abilitymgr/src/ability_scheduler_proxy.cpp index 4ffe97d254adf00a96b63325804c07a67de26b9f..a744a282d40bd475a60da7855e67d833f65e57c4 100644 --- a/services/abilitymgr/src/ability_scheduler_proxy.cpp +++ b/services/abilitymgr/src/ability_scheduler_proxy.cpp @@ -612,19 +612,5 @@ int AbilitySchedulerProxy::BatchInsert(const Uri &uri, const std::vectorSendRequest(IAbilityScheduler::DISPLAY_UNLOCK_MISSION_MESSAGE, data, reply, option); - if (err != NO_ERROR) { - HILOG_ERROR("DisplayUnlockMissionMessage​ fail to SendRequest. err: %d", err); - } -} } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/ability_scheduler_stub.cpp b/services/abilitymgr/src/ability_scheduler_stub.cpp index c5975bfff0aaa483adfaf002108f48f8c3a31ec4..ff5d236cb442bbc0c0c8d9ae35bcdb13b305c652 100644 --- a/services/abilitymgr/src/ability_scheduler_stub.cpp +++ b/services/abilitymgr/src/ability_scheduler_stub.cpp @@ -41,7 +41,6 @@ AbilitySchedulerStub::AbilitySchedulerStub() requestFuncMap_[SCHEDULE_GETTYPE] = &AbilitySchedulerStub::GetTypeInner; requestFuncMap_[SCHEDULE_RELOAD] = &AbilitySchedulerStub::ReloadInner; requestFuncMap_[SCHEDULE_BATCHINSERT] = &AbilitySchedulerStub::BatchInsertInner; - requestFuncMap_[DISPLAY_UNLOCK_MISSION_MESSAGE] = &AbilitySchedulerStub::DisplayUnlockMissionMessageInner; } AbilitySchedulerStub::~AbilitySchedulerStub() @@ -386,12 +385,6 @@ int AbilitySchedulerStub::BatchInsertInner(MessageParcel &data, MessageParcel &r return NO_ERROR; } -int AbilitySchedulerStub::DisplayUnlockMissionMessageInner(MessageParcel &data, MessageParcel &reply) -{ - DisplayUnlockMissionMessage(); - return NO_ERROR; -} - void AbilitySchedulerRecipient::OnRemoteDied(const wptr &remote) { HILOG_ERROR("recv AbilitySchedulerRecipient death notice"); diff --git a/services/abilitymgr/src/ability_stack_manager.cpp b/services/abilitymgr/src/ability_stack_manager.cpp index 4f1262a98a3362c197a1b19e87e1e66b1b8c8027..a6ad13e9efd17963ff7183e58bb70072ff86a9ba 100644 --- a/services/abilitymgr/src/ability_stack_manager.cpp +++ b/services/abilitymgr/src/ability_stack_manager.cpp @@ -47,9 +47,8 @@ int AbilityStackManager::StartAbility(const AbilityRequest &abilityRequest) auto currentTopAbilityRecord = GetCurrentTopAbility(); if (!CanStartInLockMissionState(abilityRequest, currentTopAbilityRecord)) { - HILOG_ERROR("current is lock mission state, refusing to operate other mission."); - SendDisplayUnlockMissionMessage(); - return CREATE_MISSION_RECORD_FAILED; + SendUnlockMissionMessage(); + return LOCK_MISSION_STATE_DENY_REQUEST; } if (abilityRequest.abilityInfo.applicationInfo.isLauncherApp && @@ -192,9 +191,8 @@ int AbilityStackManager::TerminateAbility(const sptr &token, int } if (!CanStopInLockMissionState(abilityRecord)) { - HILOG_ERROR("current is lock mission state, refusing to operate other mission."); - SendDisplayUnlockMissionMessage(); - return ERR_INVALID_VALUE; + SendUnlockMissionMessage(); + return LOCK_MISSION_STATE_DENY_REQUEST; } abilityRecord->SetTerminatingState(); @@ -220,9 +218,8 @@ int AbilityStackManager::TerminateAbility(const std::shared_ptr & } if (!CanStopInLockMissionState(targetAbility)) { - HILOG_ERROR("current is lock mission state, refusing to operate other mission."); - SendDisplayUnlockMissionMessage(); - return ERR_INVALID_VALUE; + SendUnlockMissionMessage(); + return LOCK_MISSION_STATE_DENY_REQUEST; } return TerminateAbilityLocked(targetAbility, -1, nullptr); @@ -1357,9 +1354,37 @@ void AbilityStackManager::CreateRecentMissionInfo( recentMissionInfo.missionDescription = missionDescription; } + if (auto desc = missionRecord->GetMissionDescriptionInfo()) { + recentMissionInfo.missionDescription = *desc; + } + recentMissionInfo.size = missionRecord->GetAbilityRecordCount(); } +int AbilityStackManager::SetMissionDescriptionInfo( + const std::shared_ptr &abilityRecord, const MissionDescriptionInfo &missionDescriptionInfo) +{ + HILOG_DEBUG("%{public}s called", __FUNCTION__); + CHECK_POINTER_AND_RETURN(abilityRecord, SET_MISSION_INFO_FAILED); + + auto mission = abilityRecord->GetMissionRecord(); + CHECK_POINTER_AND_RETURN(mission, SET_MISSION_INFO_FAILED); + auto ptr = std::make_shared(missionDescriptionInfo); + mission->SetMissionDescriptionInfo(ptr); + + return ERR_OK; +} + +int AbilityStackManager::GetMissionLockModeState() +{ + HILOG_DEBUG("%{public}s called", __FUNCTION__); + if (!lockMissionContainer_) { + return LockMissionContainer::LockMissionState::LOCK_MISSION_STATE_NONE; + } + + return lockMissionContainer_->GetLockedMissionState(); +} + int AbilityStackManager::MoveMissionToTop(int32_t missionId) { HILOG_INFO("%{public}s,%{public}d", __PRETTY_FUNCTION__, __LINE__); @@ -1603,6 +1628,13 @@ void AbilityStackManager::OnAbilityDiedByDefault(std::shared_ptr HILOG_ERROR("mission is nullptr or not exist"); return; } + + auto topAbility = mission->GetTopAbilityRecord(); + if (!topAbility) { + return; + } + auto isBackLauncher = topAbility->IsAbilityState(AbilityState::ACTIVE); + std::vector abilityInfos; mission->GetAllAbilityInfo(abilityInfos); for (auto &it : abilityInfos) { @@ -1612,13 +1644,18 @@ void AbilityStackManager::OnAbilityDiedByDefault(std::shared_ptr continue; } if (ability == abilityRecord) { - DelayedStartLauncher(); + if (isBackLauncher) { + DelayedStartLauncher(); + } if (abilityRecord->IsUninstallAbility()) { HILOG_INFO("ability uninstall,%{public}d", __LINE__); mission->RemoveAbilityRecord(abilityRecord); if (mission->GetAbilityRecordCount() == 0) { defaultMissionStack_->RemoveMissionRecord(mission->GetMissionRecordId()); } + if (defaultMissionStack_->GetMissionRecordCount() == 0) { + MoveMissionStackToTop(launcherMissionStack_); + } break; } if (mission->GetBottomAbilityRecord() == ability) { @@ -1990,10 +2027,12 @@ int AbilityStackManager::StartLockMission(int uid, int missionId, bool isSystemA // lock mission if (isLock) { - if (!lockMissionContainer_->SetLockedMission(missionRecord, lockUid)) { + if (!lockMissionContainer_->SetLockedMission(missionRecord, lockUid, isSystemApp)) { HILOG_ERROR("lock mission error."); return LOCK_MISSION_DENY_FAILED; } + // notify wms mission locked state. + // move lock mission to top return MoveMissionToTopLocked(missionRecord->GetMissionRecordId()); } @@ -2088,14 +2127,9 @@ bool AbilityStackManager::CanStopInLockMissionState(const std::shared_ptrIsSameLockedMission(mission->GetName()) && terminateAbility != bottom); } -void AbilityStackManager::SendDisplayUnlockMissionMessage() +void AbilityStackManager::SendUnlockMissionMessage() { - CHECK_POINTER(lockMissionContainer_); - auto lockMission = lockMissionContainer_->GetLockMission(); - CHECK_POINTER(lockMission); - auto topLockAbility = lockMission->GetTopAbilityRecord(); - CHECK_POINTER(topLockAbility); - topLockAbility->DisplayUnlockMissionMessage(); + HILOG_ERROR("current is lock mission state, refusing to operate other mission."); } } // namespace AAFwk diff --git a/services/abilitymgr/src/lock_mission_container.cpp b/services/abilitymgr/src/lock_mission_container.cpp index f91b7d2bf9c03ca7f7c49248df8ac588a6cc6851..881a97bcc4429e43d2cf3131526af8a50211fdee 100644 --- a/services/abilitymgr/src/lock_mission_container.cpp +++ b/services/abilitymgr/src/lock_mission_container.cpp @@ -22,10 +22,16 @@ namespace AAFwk { bool LockMissionContainer::IsLockedMissionState() const { - return isLocked_; + return lockState_ != LockMissionState::LOCK_MISSION_STATE_NONE; } -bool LockMissionContainer::SetLockedMission(const std::shared_ptr &mission, int lockerUid) +int LockMissionContainer::GetLockedMissionState() const +{ + return lockState_; +} + +bool LockMissionContainer::SetLockedMission( + const std::shared_ptr &mission, int lockerUid, bool isSystemApp) { auto lockMission = lockMission_.lock(); if (lockMission) { @@ -44,7 +50,8 @@ bool LockMissionContainer::SetLockedMission(const std::shared_ptr lockerUid); lockMission_ = mission; lockerUid_ = lockerUid; - isLocked_ = true; + lockState_ = + isSystemApp ? LockMissionState::LOCK_MISSION_STATE_PINNED : LockMissionState::LOCK_MISSION_STATE_LOCKED; return true; } @@ -99,7 +106,7 @@ void LockMissionContainer::Clear() { lockMission_.reset(); lockerUid_ = -1; - isLocked_ = false; + lockState_ = LockMissionState::LOCK_MISSION_STATE_NONE; } std::shared_ptr LockMissionContainer::GetLockMission() diff --git a/services/abilitymgr/src/pending_want_manager.cpp b/services/abilitymgr/src/pending_want_manager.cpp index 94d8ff1eb34b375cdc30595655983b0efeb29017..8923936c4a14381ac3eb25d16500fbfe507e29ed 100644 --- a/services/abilitymgr/src/pending_want_manager.cpp +++ b/services/abilitymgr/src/pending_want_manager.cpp @@ -88,6 +88,7 @@ sptr PendingWantManager::GetWantSenderLocked(const int32_t callingU wantSenderInfo.allWants.back().want = ref->GetKey()->GetRequestWant(); wantSenderInfo.allWants.back().resolvedTypes = ref->GetKey()->GetRequestResolvedType(); ref->GetKey()->SetAllWantsInfos(wantSenderInfo.allWants); + ref->SetCallerUid(callingUid); } return ref; } @@ -103,6 +104,7 @@ sptr PendingWantManager::GetWantSenderLocked(const int32_t callingU sptr rec = new (std::nothrow) PendingWantRecord(shared_from_this(), uid, callerToken, pendingKey); if (rec != nullptr) { + rec->SetCallerUid(callingUid); pendingKey->SetCode(PendingRecordIdCreate()); wantRecords_.insert(std::make_pair(pendingKey, rec)); return rec; @@ -222,14 +224,16 @@ int32_t PendingWantManager::PendingWantStartAbilitys( for (const auto &item : wantsInfo) { const auto &want = item.want; result = DelayedSingleton::GetInstance()->StartAbility(want, callerToken, requestCode); - if (result != ERR_OK || result != START_ABILITY_WAITING) { + if (result != ERR_OK && result != START_ABILITY_WAITING) { + HILOG_ERROR("%{public}s:result != ERR_OK && result != START_ABILITY_WAITING.", __func__); return result; } } return result; } -int32_t PendingWantManager::PendingWantPublishCommonEvent(const Want &want, const SenderInfo &senderInfo) +int32_t PendingWantManager::PendingWantPublishCommonEvent( + const Want &want, const SenderInfo &senderInfo, int32_t callerUid) { HILOG_INFO("%{public}s:begin.", __func__); @@ -252,8 +256,8 @@ int32_t PendingWantManager::PendingWantPublishCommonEvent(const Want &want, cons WantParams wantParams = {}; pendingWantCommonEvent->SetWantParams(wantParams); } - - bool result = CommonEventManager::PublishCommonEvent(eventData, eventPublishData, pendingWantCommonEvent); + bool result = DelayedSingleton::GetInstance()->PublishCommonEvent( + eventData, eventPublishData, pendingWantCommonEvent, callerUid); return ((result == true) ? ERR_OK : (-1)); } diff --git a/services/abilitymgr/src/pending_want_record.cpp b/services/abilitymgr/src/pending_want_record.cpp index fa68154ec9a3d9e431292be5330f2bcdc92b1316..f60d5887dda0b712c321d6bf78cc42dc2ce0c3e7 100644 --- a/services/abilitymgr/src/pending_want_record.cpp +++ b/services/abilitymgr/src/pending_want_record.cpp @@ -85,7 +85,6 @@ int32_t PendingWantRecord::SenderInner(SenderInfo &senderInfo) bool immutable = (key_->GetFlags() & (int32_t)Flags::CONSTANT_FLAG) != 0; senderInfo.resolvedType = key_->GetRequestResolvedType(); if (!immutable) { - want = senderInfo.want; want.AddFlags(key_->GetFlags()); } @@ -106,7 +105,8 @@ int32_t PendingWantRecord::SenderInner(SenderInfo &senderInfo) res = pendingWantManager->PendingWantStartAbility(want, callerToken_, -1); break; case (int32_t)OperationType::SEND_COMMON_EVENT: - res = pendingWantManager->PendingWantPublishCommonEvent(want, senderInfo); + res = pendingWantManager->PendingWantPublishCommonEvent(want, senderInfo, callerUid_); + (res == ERR_OK) ? (sendFinish = false) : (sendFinish = (senderInfo.finishedReceiver != nullptr)); break; default: break; @@ -139,6 +139,11 @@ bool PendingWantRecord::GetCanceled() return canceled_; } +void PendingWantRecord::SetCallerUid(const int32_t callerUid) +{ + callerUid_ = callerUid; +} + std::list> PendingWantRecord::GetCancelCallbacks() { return mCancelCallbacks_; diff --git a/services/abilitymgr/test/BUILD.gn b/services/abilitymgr/test/BUILD.gn index aeed8e34d00759cb3de589b0f4ba66763afeb47c..a5142290da2cdb035539f83de0d0fef2eb8082ba 100644 --- a/services/abilitymgr/test/BUILD.gn +++ b/services/abilitymgr/test/BUILD.gn @@ -15,13 +15,13 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") import("//foundation/aafwk/standard/services/abilitymgr/abilitymgr.gni") -EVENT_DIR = "//base/notification/ces_standard/cesfwk" +EVENT_DIR = "//base/notification/ces_standard/" ohos_source_set("abilityms_test_source") { sources = abilityms_files include_dirs = [ - "${EVENT_DIR}/innerkits/include", - "${EVENT_DIR}/kits/native/include", + "${EVENT_DIR}/frameworks/core/include", + "${EVENT_DIR}/interfaces/innerkits/native/include", "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", @@ -36,8 +36,6 @@ ohos_source_set("abilityms_test_source") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ - "${EVENT_DIR}/innerkits:cesfwk_innerkits", - "${EVENT_DIR}/kits/native:cesfwk_kits", "${innerkits_path}/want:want", "${services_path}/abilitymgr/test/mock/libs/sa_mgr:sa_mgr_mock", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", @@ -46,6 +44,8 @@ ohos_source_set("abilityms_test_source") { ] external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] 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 a995d280b18dacabf3ec62fae94d6373c7085af8..4fec9c0536da66b7777218ce9ea698ee6eb44c56 100644 --- a/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h +++ b/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h @@ -71,8 +71,6 @@ public: int BatchInsert(const Uri &uri, const std::vector &values) override; - void DisplayUnlockMissionMessage() override; - private: AbilityResult result_; }; diff --git a/services/abilitymgr/test/mock/libs/aakit/src/ability_scheduler.cpp b/services/abilitymgr/test/mock/libs/aakit/src/ability_scheduler.cpp index 55e4377e5ef9ab32cb67928d65b48502b6cc9d43..9be782990c316f4019021ba9601941edb9a61ac9 100644 --- a/services/abilitymgr/test/mock/libs/aakit/src/ability_scheduler.cpp +++ b/services/abilitymgr/test/mock/libs/aakit/src/ability_scheduler.cpp @@ -112,7 +112,5 @@ int AbilityScheduler::BatchInsert(const Uri &uri, const std::vector &appInfos)); MOCK_METHOD2(GetBundleInfos, bool(const BundleFlag flag, std::vector &bundleInfos)); - MOCK_METHOD2(GetUidByBundleName, int(const std::string &bundleName, const int userId)); + // MOCK_METHOD2(GetUidByBundleName, int(const std::string &bundleName, const int userId)); MOCK_METHOD2(GetBundleNameForUid, bool(const int uid, std::string &bundleName)); MOCK_METHOD2(GetBundleGids, bool(const std::string &bundleName, std::vector &gids)); MOCK_METHOD1(GetAppType, std::string(const std::string &bundleName)); @@ -229,7 +229,7 @@ public: MOCK_METHOD0(GetBundleInstaller, sptr()); bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override; - + int GetUidByBundleName(const std::string &bundleName, const int userId) override; BundleMgrService() { abilityInfoMap_.emplace(COM_IX_HIWORLD, HiWordInfo); 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 e47fa2dfc7975a3707c308d402e361e91caffb5f..de3fb0972c8843f7503f8adf8cb6d6b25eb8259d 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 @@ -160,5 +160,10 @@ bool BundleMgrService::CheckWantEntity(const AAFwk::Want &want, AbilityInfo &abi return false; } +int BundleMgrService::GetUidByBundleName(const std::string &bundleName, const int userId) +{ + return 1000; +} + } // namespace AppExecFwk } // namespace OHOS 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 f4d5c21d05e8fe3d575dd69c42209a5625d9e21d..8f32c4824f333d9703ccbb73dc531f61a78c480f 100755 --- 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 @@ -215,11 +215,22 @@ public: int LockMission(int missionId) override { return 0; - }; + } int UnlockMission(int missionId) override { return 0; - }; + } + + int SetMissionDescriptionInfo( + const sptr &token, const MissionDescriptionInfo &missionDescriptionInfo) override + { + return 0; + } + + int GetMissionLockModeState() + { + return 0; + } MOCK_METHOD2(TerminateAbilityByCaller, int(const sptr &callerToken, int requestCode)); MOCK_METHOD3(StartAbility, int(const Want &want, const sptr &callerToken, int requestCode)); 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 b9c233eecb60fd326fa690fe58b9b3bf2c0c2f99..45b2faae77bdd35f02548d4b4dfa4d54e357b74c 100755 --- 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 @@ -214,11 +214,21 @@ public: int LockMission(int missionId) override { return 0; - }; + } int UnlockMission(int missionId) override { return 0; - }; + } + int SetMissionDescriptionInfo( + const sptr &token, const MissionDescriptionInfo &missionDescriptionInfo) override + { + return 0; + } + + int GetMissionLockModeState() + { + return 0; + } }; } // namespace AAFwk 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 2e4a4cf504ae720bceb2ed3d7c4c8923a5507718..cf48cd111a13f2ab90943eb3d5a5f14342b24b0c 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 @@ -66,6 +66,9 @@ public: MOCK_METHOD0(PowerOn, int()); MOCK_METHOD1(LockMission, int(int)); MOCK_METHOD1(UnlockMission, int(int)); + MOCK_METHOD2(SetMissionDescriptionInfo, int(const sptr &token, const MissionDescriptionInfo &info)); + MOCK_METHOD0(GetMissionLockModeState, int()); + MOCK_METHOD2( GetWantSender, sptr(const WantSenderInfo &wantSenderInfo, const sptr &callerToken)); MOCK_METHOD2(SendWantSender, int(const sptr &target, const SenderInfo &senderInfo)); 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 458e7b5075bb988ed7801615127f7757fcf31f8c..d3e93a97f840a2687ea9d01baa8e94f785950bdb 100644 --- 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 @@ -93,9 +93,6 @@ public: { return -1; } - - virtual void DisplayUnlockMissionMessage() override - {} }; } // namespace AAFwk 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 ea6d6ef41b64839d966d3695d40a786001324f13..1e53cfbc1924971da933ce91c559068a7c2bc97a 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 @@ -62,12 +62,24 @@ void AbilityStackManagerTest::SetUpTestCase(void) void AbilityStackManagerTest::TearDownTestCase(void) {} void AbilityStackManagerTest::TearDown() -{} +{ + stackManager_.reset(); + auto ams = DelayedSingleton::GetInstance(); + OHOS::DelayedSingleton::DestroyInstance(); +} void AbilityStackManagerTest::SetUp() { - stackManager_ = std::make_shared(0); init(); + auto bundleObject = new BundleMgrService(); + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( + OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject); + + auto ams = DelayedSingleton::GetInstance(); + // stackManager_ = ams->GetStackManager(); + stackManager_ = std::make_shared(0); + auto bms = ams->GetBundleManager(); + EXPECT_NE(bms, nullptr); } void AbilityStackManagerTest::init() @@ -152,6 +164,7 @@ AbilityRequest AbilityStackManagerTest::GenerateAbilityRequest(const std::string return abilityRequest; } + /* * Feature: AbilityStackManager * Function: stack operate @@ -1633,7 +1646,6 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_048, TestSize. secondTopAbility->SetAbilityState(OHOS::AAFwk::INACTIVE); auto thridMissionId = thirdTopAbility->GetMissionRecord()->GetMissionRecordId(); - EXPECT_EQ(secondMissionId, thridMissionId); EXPECT_NE(firstMissionId, secondMissionId); @@ -1652,13 +1664,13 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_048, TestSize. auto recordVector = stackManager_->powerStorage_->GetPowerOffRecord(); int size = recordVector.size(); - EXPECT_EQ(size, 1); // Because we only focus on the top of the stack + EXPECT_EQ(size, 1); // Because we only focus on the top of the stack - for(const auto &it : recordVector){ - if(it.missionId == thridMissionId){ + for (const auto &it : recordVector) { + if (it.missionId == thridMissionId) { EXPECT_EQ(firstTopAbility->GetRecordId(), it.ability.lock()->GetRecordId()); } - if(it.missionId == secondMissionId){ + if (it.missionId == secondMissionId) { EXPECT_EQ(secondTopAbility->GetRecordId(), it.ability.lock()->GetRecordId()); } } @@ -1666,7 +1678,6 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_048, TestSize. result = stackManager_->PowerOn(); EXPECT_EQ(ERR_OK, result); EXPECT_EQ(OHOS::AAFwk::INACTIVE, secondTopAbility->GetAbilityState()); - } /* @@ -1729,23 +1740,405 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_049, TestSize. int size = recordVector.size(); EXPECT_EQ(size, 2); - for(const auto &it : recordVector){ - if(it.missionId == firstMissionId){ + for (const auto &it : recordVector) { + if (it.missionId == firstMissionId) { EXPECT_TRUE(firstTopAbility->GetRecordId() == it.ability.lock()->GetRecordId()); } - if(it.missionId == thridMissionId){ + if (it.missionId == thridMissionId) { EXPECT_TRUE(thirdTopAbility->GetRecordId() == it.ability.lock()->GetRecordId()); } } result = stackManager_->PowerOn(); EXPECT_EQ(ERR_OK, result); - //mocke app clent + // mocke app clent // EXPECT_EQ(OHOS::AAFwk::ACTIVATING, firstTopAbility->GetAbilityState()); // EXPECT_EQ(OHOS::AAFwk::ACTIVATING, thirdTopAbility->GetAbilityState()); EXPECT_EQ(OHOS::AAFwk::INACTIVATING, fourthTopAbility->GetAbilityState()); - } +/* + * Feature: AbilityStackManager + * Function: StartLockMission + * SubFunction: NA + * FunctionPoints: StartLockMission + * EnvConditions: NA + * CaseDescription: lock a mission + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_050, TestSize.Level1) +{ + stackManager_->Init(); + auto result = stackManager_->StartLockMission(1000, 3, true, true); + EXPECT_EQ(LOCK_MISSION_DENY_FAILED, result); + + auto result1 = stackManager_->StartLockMission(1000, -2, true, true); + EXPECT_EQ(LOCK_MISSION_DENY_FAILED, result1); +} + +/* + * Feature: AbilityStackManager + * Function: StartLockMission + * SubFunction: NA + * FunctionPoints: StartLockMission + * EnvConditions: NA + * CaseDescription: lock a mission + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_051, TestSize.Level1) +{ + stackManager_->Init(); + auto result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + + auto topMisionRecord = stackManager_->GetTopMissionRecord(); + auto MisionRecordId = topMisionRecord->GetMissionRecordId(); + + auto topAbilityRecord = topMisionRecord->GetTopAbilityRecord(); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto result1 = stackManager_->StartLockMission(1000, MisionRecordId, false, true); + EXPECT_EQ(ERR_OK, result1); + + // can't repeat the lock + auto resul2 = stackManager_->StartLockMission(1000, MisionRecordId, false, true); + EXPECT_EQ(LOCK_MISSION_DENY_FAILED, resul2); + + auto lockState = stackManager_->GetMissionLockModeState(); + EXPECT_EQ(lockState, LockMissionContainer::LockMissionState::LOCK_MISSION_STATE_LOCKED); +} + +/* + * Feature: AbilityStackManager + * Function: StartLockMission + * SubFunction: NA + * FunctionPoints: StartLockMission + * EnvConditions: NA + * CaseDescription: lock a mission + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_052, TestSize.Level1) +{ + stackManager_->Init(); + auto result = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(0, result); + + auto topAbility = stackManager_->GetCurrentTopAbility(); + topAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + auto luncherMissionRecord = stackManager_->GetTopMissionRecord(); + auto luncherMisionRecordId = luncherMissionRecord->GetMissionRecordId(); + + result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + + auto musicMisionRecord = stackManager_->GetTopMissionRecord(); + // auto musicMisionRecordId = musicMisionRecord->GetMissionRecordId(); + + auto topAbilityRecord = stackManager_->GetCurrentTopAbility(); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto result1 = stackManager_->StartLockMission(1000, luncherMisionRecordId, true, true); + EXPECT_EQ(ERR_OK, result1); + + auto missionRecord = stackManager_->GetTopMissionRecord(); + EXPECT_EQ(missionRecord->GetMissionRecordId(), luncherMisionRecordId); + + auto lockState = stackManager_->GetMissionLockModeState(); + EXPECT_EQ(lockState, LockMissionContainer::LockMissionState::LOCK_MISSION_STATE_PINNED); +} + +/* + * Feature: AbilityStackManager + * Function: StartLockMission + * SubFunction: NA + * FunctionPoints: StartLockMission + * EnvConditions: NA + * CaseDescription: lock a mission + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_053, TestSize.Level1) +{ + stackManager_->Init(); + auto result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + + auto musicMisionRecord = stackManager_->GetTopMissionRecord(); + auto musicMisionRecordId = musicMisionRecord->GetMissionRecordId(); + + auto topAbilityRecord = stackManager_->GetCurrentTopAbility(); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // 2 + auto musicAbilityRequest2th = GenerateAbilityRequest("device", "MusicAbility2th", "music", "com.ix.hiMusic"); + result = stackManager_->StartAbility(musicAbilityRequest2th); + EXPECT_EQ(0, result); + auto musicMisionRecord2th = stackManager_->GetTopMissionRecord(); + auto musicMisionRecordId2th = musicMisionRecord->GetMissionRecordId(); + EXPECT_EQ(musicMisionRecordId, musicMisionRecordId2th); + + topAbilityRecord = stackManager_->GetCurrentTopAbility(); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto result1 = stackManager_->StartLockMission(1000, musicMisionRecordId, false, true); + EXPECT_EQ(ERR_OK, result1); + + auto topRecord = stackManager_->GetCurrentTopAbility(); + auto abilityInfo = topRecord->GetAbilityInfo(); + EXPECT_EQ(abilityInfo.name, "MusicAbility2th"); + + auto lockState = stackManager_->GetMissionLockModeState(); + EXPECT_EQ(lockState, LockMissionContainer::LockMissionState::LOCK_MISSION_STATE_LOCKED); +} + +/* + * Feature: AbilityStackManager + * Function: StartLockMission + * SubFunction: NA + * FunctionPoints: StartLockMission + * EnvConditions: NA + * CaseDescription: lock a mission + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_054, TestSize.Level1) +{ + stackManager_->Init(); + auto result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + + auto topMisionRecord = stackManager_->GetTopMissionRecord(); + auto MisionRecordId = topMisionRecord->GetMissionRecordId(); + EXPECT_NE(0, MisionRecordId); + auto topAbilityRecord = topMisionRecord->GetTopAbilityRecord(); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto result1 = stackManager_->StartLockMission(1000, MisionRecordId, false, false); + EXPECT_EQ(LOCK_MISSION_DENY_FAILED, result1); +} + +/* + * Feature: AbilityStackManager + * Function: StartLockMission + * SubFunction: NA + * FunctionPoints: StartLockMission + * EnvConditions: NA + * CaseDescription: lock a mission and unlock + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_055, TestSize.Level1) +{ + stackManager_->Init(); + auto result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + + auto topMisionRecord = stackManager_->GetTopMissionRecord(); + auto MisionRecordId = topMisionRecord->GetMissionRecordId(); + EXPECT_NE(0, MisionRecordId); + auto topAbilityRecord = topMisionRecord->GetTopAbilityRecord(); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto result1 = stackManager_->StartLockMission(1000, MisionRecordId, false, true); + EXPECT_EQ(ERR_OK, result1); + + auto lockState = stackManager_->GetMissionLockModeState(); + EXPECT_EQ(lockState, LockMissionContainer::LockMissionState::LOCK_MISSION_STATE_LOCKED); + + // unlock + auto result2 = stackManager_->StartLockMission(1000, MisionRecordId, false, false); + EXPECT_EQ(ERR_OK, result2); +} + +/* + * Feature: AbilityStackManager + * Function: StartLockMission + * SubFunction: NA + * FunctionPoints: StartLockMission + * EnvConditions: NA + * CaseDescription: lock a luncher mission and unlock + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_056, TestSize.Level1) +{ + stackManager_->Init(); + auto result = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(0, result); + + auto topMisionRecord = stackManager_->GetTopMissionRecord(); + auto MisionRecordId = topMisionRecord->GetMissionRecordId(); + EXPECT_NE(0, MisionRecordId); + auto topAbilityRecord = topMisionRecord->GetTopAbilityRecord(); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto result1 = stackManager_->StartLockMission(1000, MisionRecordId, true, true); + EXPECT_EQ(ERR_OK, result1); + + auto lockState = stackManager_->GetMissionLockModeState(); + EXPECT_EQ(lockState, LockMissionContainer::LockMissionState::LOCK_MISSION_STATE_PINNED); + + // unlock + auto result2 = stackManager_->StartLockMission(1000, MisionRecordId, true, false); + EXPECT_EQ(ERR_OK, result2); +} + +/* + * Feature: AbilityStackManager + * Function: StartLockMission + * SubFunction: NA + * FunctionPoints: StartLockMission + * EnvConditions: NA + * CaseDescription: lock a luncher mission and unlock + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_057, TestSize.Level1) +{ + stackManager_->Init(); + auto result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + + auto topMisionRecord = stackManager_->GetTopMissionRecord(); + auto MisionRecordId = topMisionRecord->GetMissionRecordId(); + EXPECT_NE(0, MisionRecordId); + auto topAbilityRecord = topMisionRecord->GetTopAbilityRecord(); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto result1 = stackManager_->StartLockMission(1000, MisionRecordId, false, true); + EXPECT_EQ(ERR_OK, result1); + + auto lockState = stackManager_->GetMissionLockModeState(); + EXPECT_EQ(lockState, LockMissionContainer::LockMissionState::LOCK_MISSION_STATE_LOCKED); + + // unlock + auto result2 = stackManager_->StartLockMission(1000, MisionRecordId, false, false); + EXPECT_EQ(ERR_OK, result2); +} + +/* + * Feature: AbilityStackManager + * Function: SetMissionDescriptionInfo + * SubFunction: NA + * FunctionPoints: SetMissionDescriptionInfo + * EnvConditions: NA + * CaseDescription: set details for a mission + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_058, TestSize.Level1) +{ + stackManager_->Init(); + EXPECT_TRUE(stackManager_); + auto result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + + auto topMissionRecord = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord = topMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(topMissionRecord); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + Want want; + AbilityInfo abilityInfo; + ApplicationInfo appInfo; + auto abilityRecord = std::make_shared(want, abilityInfo, appInfo); + + MissionDescriptionInfo missionDescriptionInfo; + missionDescriptionInfo.label = "123456"; + missionDescriptionInfo.iconPath = "loacl"; + + result = stackManager_->SetMissionDescriptionInfo(abilityRecord, missionDescriptionInfo); + EXPECT_EQ(SET_MISSION_INFO_FAILED, result); + + result = stackManager_->SetMissionDescriptionInfo(topAbilityRecord, missionDescriptionInfo); + EXPECT_EQ(ERR_OK, result); + + auto descriptionInfo = topMissionRecord->GetMissionDescriptionInfo(); + EXPECT_TRUE(descriptionInfo); + + EXPECT_TRUE(descriptionInfo->label == missionDescriptionInfo.label); + EXPECT_TRUE(descriptionInfo->iconPath == missionDescriptionInfo.iconPath); +} + +/* + * Feature: AbilityStackManager + * Function: SetMissionDescriptionInfo + * SubFunction: NA + * FunctionPoints: SetMissionDescriptionInfo + * EnvConditions: NA + * CaseDescription: can stop or can start mission state + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_059, TestSize.Level1) +{ + stackManager_->Init(); + EXPECT_TRUE(stackManager_); + auto result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + + auto topMissionRecord = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord = topMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(topMissionRecord); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto isCanStart = stackManager_->CanStartInLockMissionState(launcherAbilityRequest_, topAbilityRecord); + EXPECT_TRUE(isCanStart); + + // LOCK + auto MisionRecordId = topMissionRecord->GetMissionRecordId(); + auto result1 = stackManager_->StartLockMission(1000, MisionRecordId, false, true); + EXPECT_EQ(ERR_OK, result1); + + // check can terminal + auto isCanStop = stackManager_->CanStopInLockMissionState(topAbilityRecord); + EXPECT_FALSE(isCanStop); + + // check start agin + isCanStart = stackManager_->CanStartInLockMissionState(launcherAbilityRequest_, topAbilityRecord); + EXPECT_FALSE(isCanStart); + + // unlock + result1 = stackManager_->StartLockMission(1000, MisionRecordId, false, false); + EXPECT_EQ(ERR_OK, result1); + + isCanStop = stackManager_->CanStopInLockMissionState(topAbilityRecord); + EXPECT_TRUE(isCanStop); +} + +/* + * Feature: AbilityStackManager + * Function: SetMissionDescriptionInfo + * SubFunction: NA + * FunctionPoints: SetMissionDescriptionInfo + * EnvConditions: NA + * CaseDescription: when the uid defferent + */ +HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_060, TestSize.Level1) +{ + stackManager_->Init(); + EXPECT_TRUE(stackManager_); + auto result = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(0, result); + + auto topMissionRecord = stackManager_->GetTopMissionRecord(); + auto topAbilityRecord = topMissionRecord->GetTopAbilityRecord(); + EXPECT_TRUE(topMissionRecord); + EXPECT_TRUE(topAbilityRecord); + topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto isCanStart = stackManager_->CanStartInLockMissionState(launcherAbilityRequest_, topAbilityRecord); + EXPECT_TRUE(isCanStart); + + // LOCK + auto MisionRecordId = topMissionRecord->GetMissionRecordId(); + auto result1 = stackManager_->StartLockMission(99, MisionRecordId, false, true); + EXPECT_EQ(LOCK_MISSION_DENY_FAILED, result1); + + result1 = stackManager_->StartLockMission(100, MisionRecordId, false, true); + EXPECT_EQ(ERR_OK, result1); + + // unlock defferent uid(99) + result1 = stackManager_->StartLockMission(99, MisionRecordId, false, false); + EXPECT_EQ(LOCK_MISSION_DENY_FAILED, result1); + + result1 = stackManager_->StartLockMission(100, MisionRecordId, false, false); + EXPECT_EQ(ERR_OK, result1); +} + +/* + * Feature: AbilityStackManager + * Function: SetMissionDescriptionInfo + * SubFunction: NA + * FunctionPoints: SetMissionDescriptionInfo + * EnvConditions: NA + * CaseDescription: when the uid defferent + */ + } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/test/unittest/phone/ability_with_applications_test/mock_ability_scheduler.cpp b/services/abilitymgr/test/unittest/phone/ability_with_applications_test/mock_ability_scheduler.cpp index e63206b32907cd80a64e6df457af70d8146bc5a7..39bf55f2c1c5fa44af11261bc42aa9643102b55d 100644 --- a/services/abilitymgr/test/unittest/phone/ability_with_applications_test/mock_ability_scheduler.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_with_applications_test/mock_ability_scheduler.cpp @@ -104,8 +104,5 @@ int AbilityScheduler::BatchInsert(const Uri &uri, const std::vector &token, const MissionDescriptionInfo &info)); + MOCK_METHOD0(GetMissionLockModeState, int()); MOCK_METHOD2( GetWantSender, sptr(const WantSenderInfo &wantSenderInfo, const sptr &callerToken)); MOCK_METHOD2(SendWantSender, int(const sptr &target, const SenderInfo &senderInfo)); diff --git a/services/test/mock/include/mock_ability_scheduler.h b/services/test/mock/include/mock_ability_scheduler.h index 14d2b4fbd6b2d6a327366bd5d15e611623b8075e..88b60273fc14c1c3cb768f4379cf0c21f14b8518 100644 --- a/services/test/mock/include/mock_ability_scheduler.h +++ b/services/test/mock/include/mock_ability_scheduler.h @@ -35,7 +35,6 @@ public: MOCK_METHOD1(ScheduleSaveAbilityState, void(PacMap &outState)); MOCK_METHOD1(ScheduleRestoreAbilityState, void(const PacMap &inState)); MOCK_METHOD1(ScheduleNewWant, void(const Want &want)); - MOCK_METHOD0(DisplayUnlockMissionMessage, void()); std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) { diff --git a/services/test/mock/include/mock_ability_scheduler_stub.h b/services/test/mock/include/mock_ability_scheduler_stub.h index fbf524d236e6a17111b0e409f1a557c98d419b8d..bd0610296720009c5aba116c40a9a623539002fd 100644 --- a/services/test/mock/include/mock_ability_scheduler_stub.h +++ b/services/test/mock/include/mock_ability_scheduler_stub.h @@ -41,7 +41,6 @@ public: MOCK_METHOD2(OpenRawFile, int(const Uri &uri, const std::string &mode)); MOCK_METHOD2(Reload, bool(const Uri &uri, const PacMap &extras)); MOCK_METHOD2(BatchInsert, int(const Uri &uri, const std::vector &values)); - MOCK_METHOD0(DisplayUnlockMissionMessage, void()); }; } // namespace AAFwk diff --git a/services/test/mock/include/mock_bundle_mgr.h b/services/test/mock/include/mock_bundle_mgr.h index 2a993588adca020a65db96e9c94b92dfe4b9e59a..f02fc0731ca540b6b39186bc1a958ea994ea56cf 100644 --- a/services/test/mock/include/mock_bundle_mgr.h +++ b/services/test/mock/include/mock_bundle_mgr.h @@ -231,8 +231,10 @@ public: MOCK_METHOD1(UnregisterPermissionsChanged, bool(const sptr &callback)); MOCK_METHOD2(GetAppIdByBundleName, std::string(const std::string &bundleName, const int userId)); MOCK_METHOD1(GetAllFormsInfo, bool(std::vector &formInfos)); - MOCK_METHOD2(GetFormsInfoByApp, bool(const std::string &bundleName,std::vector &formInfos)); - MOCK_METHOD3(GetFormsInfoByModule, bool(const std::string &bundleName, const std::string &moduleName, std::vector &formInfos)); + MOCK_METHOD2(GetFormsInfoByApp, bool(const std::string &bundleName, std::vector &formInfos)); + MOCK_METHOD3(GetFormsInfoByModule, + bool(const std::string &bundleName, const std::string &moduleName, std::vector &formInfos)); + MOCK_METHOD2(GetShortcutInfos, bool(const std::string &bundleName, std::vector &shortcutInfos)); }; class BundleMgrStub : public IRemoteStub { @@ -249,7 +251,6 @@ public: MOCK_METHOD3(GetApplicationInfos, bool(const ApplicationFlag flag, const int userId, std::vector &appInfos)); MOCK_METHOD2(GetBundleInfos, bool(const BundleFlag flag, std::vector &bundleInfos)); - MOCK_METHOD2(GetUidByBundleName, int(const std::string &bundleName, const int userId)); MOCK_METHOD2(GetBundleNameForUid, bool(const int uid, std::string &bundleName)); MOCK_METHOD2(GetBundleGids, bool(const std::string &bundleName, std::vector &gids)); MOCK_METHOD1(GetAppType, std::string(const std::string &bundleName)); @@ -295,12 +296,17 @@ public: MOCK_METHOD1(UnregisterPermissionsChanged, bool(const sptr &callback)); MOCK_METHOD2(GetAppIdByBundleName, std::string(const std::string &bundleName, const int userId)); MOCK_METHOD1(GetAllFormsInfo, bool(std::vector &formInfos)); - MOCK_METHOD2(GetFormsInfoByApp, bool(const std::string &bundleName,std::vector &formInfos)); - MOCK_METHOD3(GetFormsInfoByModule, bool(const std::string &bundleName, const std::string &moduleName, std::vector &formInfos)); + MOCK_METHOD2(GetFormsInfoByApp, bool(const std::string &bundleName, std::vector &formInfos)); + MOCK_METHOD3(GetFormsInfoByModule, + bool(const std::string &bundleName, const std::string &moduleName, std::vector &formInfos)); + MOCK_METHOD2(GetShortcutInfos, bool(const std::string &bundleName, std::vector &shortcutInfos)); + MOCK_METHOD2(GetUidByBundleName, int(const std::string &bundleName, const int userId)); bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override; bool QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) override; bool GetApplicationInfo( const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override; + + BundleMgrService() { abilityInfoMap_.emplace(COM_IX_HIWORLD, HiWordInfo); diff --git a/services/test/moduletest/ability_mgr_service_test/BUILD.gn b/services/test/moduletest/ability_mgr_service_test/BUILD.gn index 260e89527a209a11978eca0cb70cb702b328c090..92214c2afcc7723b862fdc73dac6f1b509cb3450 100644 --- a/services/test/moduletest/ability_mgr_service_test/BUILD.gn +++ b/services/test/moduletest/ability_mgr_service_test/BUILD.gn @@ -15,16 +15,11 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") module_output_path = "aafwk_standard/mstabilitymgrservice" -EVENT_DIR = "//base/notification/ces_standard/cesfwk" ohos_moduletest("ability_mgr_module_test") { module_out_path = module_output_path - include_dirs = [ - "${services_path}/test/mock/include", - "${EVENT_DIR}/innerkits/include", - "${EVENT_DIR}/kits/native/include", - ] + include_dirs = [ "${services_path}/test/mock/include" ] sources = [ "ability_mgr_module_test.cpp" ] sources += [ @@ -82,8 +77,6 @@ ohos_moduletest("ability_mgr_module_test") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ - "${EVENT_DIR}/innerkits:cesfwk_innerkits", - "${EVENT_DIR}/kits/native:cesfwk_kits", "${innerkits_path}/want:want", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", "//foundation/aafwk/standard/services/abilitymgr:abilityms", @@ -99,6 +92,8 @@ ohos_moduletest("ability_mgr_module_test") { ] external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/test/moduletest/ability_record_test/BUILD.gn b/services/test/moduletest/ability_record_test/BUILD.gn index 7e36671bdf0f8f91d7ab8966f511beffd251385a..6962574439ae12f3dec20dd870b7730cbd3be1e0 100644 --- a/services/test/moduletest/ability_record_test/BUILD.gn +++ b/services/test/moduletest/ability_record_test/BUILD.gn @@ -15,14 +15,14 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") module_output_path = "aafwk_standard/mstabilitymgrservice" -EVENT_DIR = "//base/notification/ces_standard/cesfwk" +EVENT_DIR = "//base/notification/ces_standard" ohos_moduletest("AbilityRecordModuleTest") { module_out_path = module_output_path include_dirs = [ - "${EVENT_DIR}/innerkits/include", - "${EVENT_DIR}/kits/native/include", + "${EVENT_DIR}/frameworks/core/include", + "${EVENT_DIR}/interfaces/innerkits/native/include", ] sources = [ @@ -82,8 +82,6 @@ ohos_moduletest("AbilityRecordModuleTest") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ - "${EVENT_DIR}/innerkits:cesfwk_innerkits", - "${EVENT_DIR}/kits/native:cesfwk_kits", "${innerkits_path}/want:want", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", "//foundation/aafwk/standard/services/abilitymgr:abilityms", @@ -99,6 +97,8 @@ ohos_moduletest("AbilityRecordModuleTest") { ] external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/test/moduletest/ability_stack_test/BUILD.gn b/services/test/moduletest/ability_stack_test/BUILD.gn index 8ea019962943075b5952eb2641c272dc1d34cec5..bdd09eac61d10f628f4916eb32b14e421ae485df 100644 --- a/services/test/moduletest/ability_stack_test/BUILD.gn +++ b/services/test/moduletest/ability_stack_test/BUILD.gn @@ -15,16 +15,11 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") module_output_path = "aafwk_standard/mstabilitymgrservice" -EVENT_DIR = "//base/notification/ces_standard/cesfwk" ohos_moduletest("ability_stack_module_test") { module_out_path = module_output_path - include_dirs = [ - "${services_path}/test/mock/include", - "${EVENT_DIR}/innerkits/include", - "${EVENT_DIR}/kits/native/include", - ] + include_dirs = [ "${services_path}/test/mock/include" ] sources = [ "ability_stack_module_test.cpp" ] sources += [ @@ -67,6 +62,7 @@ ohos_moduletest("ability_stack_module_test") { "//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/sa_mgr/src/sa_mgr_client_mock.cpp", + "//foundation/aafwk/standard/services/test/mock/src/mock_bundle_mgr.cpp", ] configs = [ "${services_path}/test:aafwk_module_test_config", @@ -81,8 +77,6 @@ ohos_moduletest("ability_stack_module_test") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ - "${EVENT_DIR}/innerkits:cesfwk_innerkits", - "${EVENT_DIR}/kits/native:cesfwk_kits", "${innerkits_path}/want:want", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", "//foundation/aafwk/standard/services/abilitymgr:abilityms", @@ -98,6 +92,8 @@ ohos_moduletest("ability_stack_module_test") { ] external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] 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 611a294080c9abbfb5e3be805a5d05d8db48c5a1..7c67a41c1e1f57a41f9ab82c10d7b72d5ee83eff 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 @@ -27,6 +27,10 @@ #undef private #undef protected +#include "mock_bundle_mgr.h" +#include "sa_mgr_client.h" +#include "system_ability_definition.h" + using namespace testing::ext; using namespace OHOS::AppExecFwk; using namespace testing; @@ -45,7 +49,10 @@ public: AbilityRequest GenerateAbilityRequest(const std::string &deviceName, const std::string &abilityName, const std::string &appName, const std::string &bundleName); void makeScene(const std::string &abilityName, const std::string &bundleName, AbilityInfo &abilityInfo, Want &want); + +public: std::shared_ptr stackManager_; + BundleMgrService *bundleObject_ = nullptr; }; void AbilityStackModuleTest::SetUpTestCase(void) @@ -56,11 +63,23 @@ void AbilityStackModuleTest::TearDownTestCase(void) void AbilityStackModuleTest::SetUp(void) { - stackManager_ = std::make_shared(100); + bundleObject_ = new BundleMgrService(); + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( + OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject_); + + auto ams = DelayedSingleton::GetInstance(); + // stackManager_ = ams->GetStackManager(); + stackManager_ = std::make_shared(10); + auto bms = ams->GetBundleManager(); + ams->OnStart(); + EXPECT_NE(bms, nullptr); } void AbilityStackModuleTest::TearDown(void) -{} +{ + auto ams = DelayedSingleton::GetInstance(); + OHOS::DelayedSingleton::DestroyInstance(); +} AbilityRequest AbilityStackModuleTest::GenerateAbilityRequest(const std::string &deviceName, const std::string &abilityName, const std::string &appName, const std::string &bundleName) @@ -98,13 +117,14 @@ void AbilityStackModuleTest::makeScene( abilityInfo.type = AbilityType::PAGE; abilityInfo.applicationInfo.isLauncherApp = true; abilityInfo.process = "p"; + abilityInfo.launchMode = LaunchMode::SINGLETON; } if (bundleName == "com.ix.hiMusic") { abilityInfo.type = AbilityType::PAGE; abilityInfo.applicationInfo.isLauncherApp = false; - if (abilityName == "MusicAbility") { + if (abilityName == "MusicAbility" || abilityName == "MusicAbility2th") { abilityInfo.process = "p1"; abilityInfo.launchMode = LaunchMode::STANDARD; } @@ -523,12 +543,13 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_007, TestSize.Level1) curMissionStack->AddMissionRecordToTop(mission); auto appScheduler = OHOS::DelayedSingleton::GetInstance(); - auto mockAppMgrClient = std::make_unique(); - appScheduler->appMgrClient_.reset(mockAppMgrClient.get()); + MockAppMgrClient *mockAppMgrClient = new MockAppMgrClient(); + appScheduler->appMgrClient_.reset(mockAppMgrClient); OHOS::sptr abilityScheduler(new MockAbilityScheduler()); // ams handler is non statrt so times is 0 - EXPECT_CALL(*mockAppMgrClient, UpdateAbilityState(testing::_, testing::_)).Times(0); + EXPECT_CALL(*mockAppMgrClient, UpdateAbilityState(testing::_, testing::_)).Times(1); + EXPECT_TRUE(abilityRecord->GetToken()); stackManager_->AttachAbilityThread(abilityScheduler, abilityRecord->GetToken()); GTEST_LOG_(INFO) << "AbilityStackModuleTest ability_stack_test_007 end"; @@ -654,6 +675,14 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_010, TestSize.Level1) HWTEST_F(AbilityStackModuleTest, ability_stack_test_011, TestSize.Level1) { + auto appScheduler = OHOS::DelayedSingleton::GetInstance(); + MockAppMgrClient *mockAppMgrClient = new MockAppMgrClient(); + appScheduler->appMgrClient_.reset(mockAppMgrClient); + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)).Times(1).WillOnce(Return(AppMgrResultCode::RESULT_OK)); + EXPECT_CALL(*mockAppMgrClient, UpdateAbilityState(testing::_, testing::_)) + .Times(1) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + AbilityRequest launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); stackManager_->Init(); @@ -673,7 +702,8 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_011, TestSize.Level1) OHOS::sptr scheduler(new MockAbilityScheduler()); firstTopAbility->SetScheduler(scheduler); - // EXPECT_CALL(*scheduler, AsObject()).Times(testing::AtLeast(1)); + EXPECT_CALL(*scheduler, AsObject()).Times(testing::AtLeast(1)).WillOnce(Return(nullptr)); + EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(testing::_, testing::_)) .Times(testing::AtLeast(2)) .WillOnce(testing::Invoke(transactionDoneCaller)) @@ -687,6 +717,9 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_011, TestSize.Level1) auto recordVector = stackManager_->powerStorage_->GetPowerOffRecord(); EXPECT_TRUE(recordVector.empty()); + + testing::Mock::AllowLeak(mockAppMgrClient); + testing::Mock::AllowLeak(scheduler); } /* @@ -700,6 +733,15 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_011, TestSize.Level1) HWTEST_F(AbilityStackModuleTest, ability_stack_test_012, TestSize.Level1) { stackManager_->Init(); + + auto appScheduler = OHOS::DelayedSingleton::GetInstance(); + MockAppMgrClient *mockAppMgrClient = new MockAppMgrClient(); + appScheduler->appMgrClient_.reset(mockAppMgrClient); + + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); stackManager_->StartAbility(launcherAbilityRequest_); auto firstTopAbility = stackManager_->GetCurrentTopAbility(); @@ -715,10 +757,27 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_012, TestSize.Level1) stackManager_->CompleteBackground(firstTopAbility); }; + auto transactionDoneCaller2 = [&](const Want &want, const LifeCycleStateInfo &targetState) { + stackManager_->CompleteActive(firstTopAbility); + }; + + auto transactionDoneCaller3 = [&](const Want &want, const LifeCycleStateInfo &targetState) { + stackManager_->CompleteInactive(firstTopAbility); + }; + OHOS::sptr scheduler(new MockAbilityScheduler()); firstTopAbility->SetScheduler(scheduler); - EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(testing::_, testing::_)) + EXPECT_CALL(*scheduler, AsObject()) .Times(testing::AtLeast(1)) + .WillOnce(Return(nullptr)) + .WillOnce(Return(nullptr)) + .WillOnce(Return(nullptr)); + + EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(testing::_, testing::_)) + .Times(testing::AtLeast(3)) + .WillOnce(testing::Invoke(transactionDoneCaller)) + .WillOnce(testing::Invoke(transactionDoneCaller2)) + .WillOnce(testing::Invoke(transactionDoneCaller3)) .WillOnce(testing::Invoke(transactionDoneCaller)); auto transactionDoneCaller2_1 = [&](const Want &want, const LifeCycleStateInfo &targetState) { @@ -735,6 +794,12 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_012, TestSize.Level1) OHOS::sptr scheduler2(new MockAbilityScheduler()); secondTopAbility->SetScheduler(scheduler2); + EXPECT_CALL(*scheduler2, AsObject()) + .Times(testing::AtLeast(1)) + .WillOnce(Return(nullptr)) + .WillOnce(Return(nullptr)) + .WillOnce(Return(nullptr)); + EXPECT_CALL(*scheduler2, ScheduleAbilityTransaction(testing::_, testing::_)) .Times(testing::AtLeast(3)) .WillOnce(testing::Invoke(transactionDoneCaller2_1)) @@ -753,15 +818,401 @@ HWTEST_F(AbilityStackModuleTest, ability_stack_test_012, TestSize.Level1) for (const auto &it : recordVector) { EXPECT_EQ(it.ability.lock()->GetRecordId(), firstTopAbility->GetRecordId()); + EXPECT_EQ(it.ability.lock()->GetAbilityState(), OHOS::AAFwk::BACKGROUND); } + auto requestDone = [&](const sptr &token, const AppExecFwk::AbilityState state) -> AppMgrResultCode { + firstTopAbility->Activate(); + return AppMgrResultCode::RESULT_OK; + }; + + auto requestDone2 = [&](const sptr &token, + const AppExecFwk::AbilityState state) -> AppMgrResultCode { + secondTopAbility->Activate(); + return AppMgrResultCode::RESULT_OK; + }; + + auto requestDone3 = [&](const sptr &token, + const AppExecFwk::AbilityState state) -> AppMgrResultCode { + return AppMgrResultCode::RESULT_OK; + }; + + EXPECT_CALL(*mockAppMgrClient, UpdateAbilityState(testing::_, testing::_)) + .Times(3) + .WillOnce(Invoke(requestDone)) + .WillOnce(Invoke(requestDone2)) + .WillOnce(Invoke(requestDone3)); + result = stackManager_->PowerOn(); EXPECT_EQ(ERR_OK, result); - // mocke appmgr caller - usleep(500); - stackManager_->OnAbilityRequestDone(secondTopAbility->GetToken(), 2); - // EXPECT_EQ(OHOS::AAFwk::INACTIVE, firstTopAbility->GetAbilityState()); + + EXPECT_EQ(OHOS::AAFwk::BACKGROUND, firstTopAbility->GetAbilityState()); // end last move to background EXPECT_EQ(OHOS::AAFwk::ACTIVE, secondTopAbility->GetAbilityState()); + + testing::Mock::AllowLeak(mockAppMgrClient); +} + +/* + * Feature: AaFwk + * Function: StartLockMission + * SubFunction: NA + * FunctionPoints: lock a mission , It's locked mission top ability will be active + * EnvConditions: NA + * CaseDescription: lock a mission + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_013, TestSize.Level1) +{ + stackManager_->Init(); + int sysUid = 1000; + EXPECT_CALL(*bundleObject_, GetUidByBundleName(_, _)) + .Times(AtLeast(2)) + .WillOnce(Return(sysUid)) + .WillOnce(Return(sysUid)); + + auto appScheduler = OHOS::DelayedSingleton::GetInstance(); + MockAppMgrClient *mockAppMgrClient = new MockAppMgrClient(); + appScheduler->appMgrClient_.reset(mockAppMgrClient); + + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "LauncherAbility", "launcher", "com.ix.hiworld"); + stackManager_->StartAbility(launcherAbilityRequest_); + auto firstTopAbility = stackManager_->GetCurrentTopAbility(); + firstTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto musicAbilityRequest_ = GenerateAbilityRequest("device", "MusicAbility", "music", "com.ix.hiMusic"); + stackManager_->StartAbility(musicAbilityRequest_); + auto secondTopAbility = stackManager_->GetCurrentTopAbility(); + secondTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // lock LauncherAbility + auto launcherMisionRecord = firstTopAbility->GetMissionRecord(); + auto launcherMisionRecordId = launcherMisionRecord->GetMissionRecordId(); + auto result = stackManager_->StartLockMission(sysUid, launcherMisionRecordId, true, true); + EXPECT_EQ(ERR_OK, result); + + auto topRecord = stackManager_->GetCurrentTopAbility(); + auto abilityInfo = topRecord->GetAbilityInfo(); + EXPECT_EQ(abilityInfo.name, "LauncherAbility"); + topRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // unlock + result = stackManager_->StartLockMission(sysUid, launcherMisionRecordId, true, false); + EXPECT_EQ(ERR_OK, result); + + testing::Mock::AllowLeak(mockAppMgrClient); + testing::Mock::AllowLeak(bundleObject_); +} + +/* + * Feature: AaFwk + * Function: StartLockMissions + * SubFunction: NA + * FunctionPoints: lock a mission , It's locked mission top ability will be active + * EnvConditions: NA + * CaseDescription: multiple mission lock someone + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_014, TestSize.Level1) +{ + stackManager_->Init(); + int sysUid = 1000; + EXPECT_CALL(*bundleObject_, GetUidByBundleName(_, _)) + .Times(AtLeast(2)) + .WillOnce(Return(sysUid)) + .WillOnce(Return(sysUid)); + + auto appScheduler = OHOS::DelayedSingleton::GetInstance(); + MockAppMgrClient *mockAppMgrClient = new MockAppMgrClient(); + appScheduler->appMgrClient_.reset(mockAppMgrClient); + + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "MusicAbility", "launcher", "com.ix.hiworld"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto firstTopAbility = stackManager_->GetCurrentTopAbility(); + firstTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto musicAbilityRequest_ = GenerateAbilityRequest("device", "MusicAbility2th", "launcher", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto secondTopAbility = stackManager_->GetCurrentTopAbility(); + secondTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto redioAbilityRequest_ = GenerateAbilityRequest("device", "RadioTopAbility", "Radio", "com.ix.hiRadio"); + ref = stackManager_->StartAbility(redioAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto thirdTopAbility = stackManager_->GetCurrentTopAbility(); + thirdTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto transactionDoneCaller = [&](const Want &want, const LifeCycleStateInfo &targetState) { + stackManager_->CompleteActive(secondTopAbility); + }; + auto transactionDoneCaller2 = [&](const Want &want, const LifeCycleStateInfo &targetState) { + stackManager_->CompleteInactive(secondTopAbility); + }; + + OHOS::sptr scheduler(new MockAbilityScheduler()); + secondTopAbility->SetScheduler(scheduler); + EXPECT_CALL(*scheduler, ScheduleAbilityTransaction(testing::_, testing::_)) + .Times(testing::AtLeast(2)) + .WillOnce(testing::Invoke(transactionDoneCaller)) + .WillOnce(testing::Invoke(transactionDoneCaller2)); + + EXPECT_CALL(*scheduler, AsObject()).Times(testing::AtLeast(1)).WillOnce(Return(nullptr)); + auto transactionDoneCaller3 = [&](const Want &want, const LifeCycleStateInfo &targetState) { + stackManager_->CompleteInactive(thirdTopAbility); + }; + auto transactionDoneCaller4 = [&](const Want &want, const LifeCycleStateInfo &targetState) { + stackManager_->CompleteActive(thirdTopAbility); + }; + + OHOS::sptr scheduler2(new MockAbilityScheduler()); + thirdTopAbility->SetScheduler(scheduler2); + EXPECT_CALL(*scheduler2, ScheduleAbilityTransaction(testing::_, testing::_)) + .Times(testing::AtLeast(2)) + .WillOnce(testing::Invoke(transactionDoneCaller3)) + .WillOnce(testing::Invoke(transactionDoneCaller4)); + + EXPECT_CALL(*scheduler2, AsObject()).Times(testing::AtLeast(1)).WillOnce(Return(nullptr)); + + secondTopAbility->SetAbilityState(OHOS::AAFwk::INACTIVE); + auto musicMisionRecord = secondTopAbility->GetMissionRecord(); + auto musicMisionRecordId = musicMisionRecord->GetMissionRecordId(); + + auto result = stackManager_->StartLockMission(sysUid, musicMisionRecordId, false, true); + EXPECT_EQ(ERR_OK, result); + + auto topRecord = stackManager_->GetCurrentTopAbility(); + auto abilityInfo = topRecord->GetAbilityInfo(); + EXPECT_EQ(abilityInfo.name, "MusicAbility2th"); + + // unlock + result = stackManager_->StartLockMission(sysUid, musicMisionRecordId, false, false); + EXPECT_EQ(ERR_OK, result); + + testing::Mock::AllowLeak(mockAppMgrClient); + testing::Mock::AllowLeak(bundleObject_); +} + +/* + * Feature: AaFwk + * Function: StartLockMission + * SubFunction: NA + * FunctionPoints: lock a mission , It's locked mission top ability will be active + * EnvConditions: NA + * CaseDescription: when a misson locked other mission do not to statr ability + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_015, TestSize.Level1) +{ + stackManager_->Init(); + int userUid = 10; + EXPECT_CALL(*bundleObject_, GetUidByBundleName(_, _)) + .Times(AtLeast(2)) + .WillOnce(Return(userUid)) + .WillOnce(Return(userUid)); + + auto appScheduler = OHOS::DelayedSingleton::GetInstance(); + MockAppMgrClient *mockAppMgrClient = new MockAppMgrClient(); + appScheduler->appMgrClient_.reset(mockAppMgrClient); + + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + // start a SINGLETON ability + auto musicAbilityRequest_ = GenerateAbilityRequest("device", "MusicSAbility", "music", "com.ix.hiMusic"); + stackManager_->StartAbility(musicAbilityRequest_); + auto secondTopAbility = stackManager_->GetCurrentTopAbility(); + secondTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // lock + auto musicMisionRecord = stackManager_->GetTopMissionRecord(); + auto musicMisionRecordId = musicMisionRecord->GetMissionRecordId(); + auto result = stackManager_->StartLockMission(userUid, musicMisionRecordId, false, true); + EXPECT_EQ(ERR_OK, result); + + // not can start a ability + auto redioAbilityRequest_ = GenerateAbilityRequest("device", "RedioAbility", "music", "com.ix.hiRadio"); + auto ref = stackManager_->StartAbility(redioAbilityRequest_); + EXPECT_EQ(LOCK_MISSION_STATE_DENY_REQUEST, ref); + + auto topAbility = stackManager_->GetCurrentTopAbility(); + topAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + // unlock + result = stackManager_->StartLockMission(userUid, musicMisionRecordId, false, false); + EXPECT_EQ(ERR_OK, result); + + // can start a ability + ref = stackManager_->StartAbility(redioAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + testing::Mock::AllowLeak(mockAppMgrClient); + testing::Mock::AllowLeak(bundleObject_); +} + +/* + * Feature: AaFwk + * Function: StartLockMission + * SubFunction: NA + * FunctionPoints: lock a mission , It's locked mission top ability will be active + * EnvConditions: NA + * CaseDescription: when a mission locked, you cannot delete the last one + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_016, TestSize.Level1) +{ + stackManager_->Init(); + int userUid = 10; + EXPECT_CALL(*bundleObject_, GetUidByBundleName(_, _)) + .Times(AtLeast(2)) + .WillOnce(Return(userUid)) + .WillOnce(Return(userUid)); + + auto appScheduler = OHOS::DelayedSingleton::GetInstance(); + MockAppMgrClient *mockAppMgrClient = new MockAppMgrClient(); + appScheduler->appMgrClient_.reset(mockAppMgrClient); + + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + // start a SINGLETON ability + auto musicAbilityRequest_ = GenerateAbilityRequest("device", "MusicSAbility", "music", "com.ix.hiMusic"); + stackManager_->StartAbility(musicAbilityRequest_); + auto secondTopAbility = stackManager_->GetCurrentTopAbility(); + secondTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // lock + auto musicMisionRecord = stackManager_->GetTopMissionRecord(); + auto musicMisionRecordId = musicMisionRecord->GetMissionRecordId(); + auto result = stackManager_->StartLockMission(userUid, musicMisionRecordId, false, true); + EXPECT_EQ(ERR_OK, result); + + result = stackManager_->TerminateAbility(secondTopAbility->GetToken(), -1, nullptr); + EXPECT_EQ(LOCK_MISSION_STATE_DENY_REQUEST, result); + + // unlock + result = stackManager_->StartLockMission(userUid, musicMisionRecordId, false, false); + EXPECT_EQ(ERR_OK, result); + + result = stackManager_->TerminateAbility(secondTopAbility->GetToken(), -1, nullptr); + EXPECT_EQ(ERR_OK, result); + + testing::Mock::AllowLeak(mockAppMgrClient); + testing::Mock::AllowLeak(bundleObject_); +} + +/* + * Feature: AaFwk + * Function: StartLockMissions + * SubFunction: NA + * FunctionPoints: lock a mission , It's locked mission top ability will be active + * EnvConditions: NA + * CaseDescription: lock a multi ability mission + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_017, TestSize.Level1) +{ + stackManager_->Init(); + int sysUid = 1000; + EXPECT_CALL(*bundleObject_, GetUidByBundleName(_, _)) + .Times(AtLeast(2)) + .WillOnce(Return(sysUid)) + .WillOnce(Return(sysUid)); + + auto appScheduler = OHOS::DelayedSingleton::GetInstance(); + MockAppMgrClient *mockAppMgrClient = new MockAppMgrClient(); + appScheduler->appMgrClient_.reset(mockAppMgrClient); + + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + auto launcherAbilityRequest_ = GenerateAbilityRequest("device", "MusicAbility", "launcher", "com.ix.hiMusic"); + auto ref = stackManager_->StartAbility(launcherAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto firstTopAbility = stackManager_->GetCurrentTopAbility(); + firstTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto musicAbilityRequest_ = GenerateAbilityRequest("device", "MusicAbility2th", "launcher", "com.ix.hiMusic"); + ref = stackManager_->StartAbility(musicAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto secondTopAbility = stackManager_->GetCurrentTopAbility(); + secondTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + auto redioAbilityRequest_ = GenerateAbilityRequest("device", "RadioTopAbility", "Radio", "com.ix.hiRadio"); + ref = stackManager_->StartAbility(redioAbilityRequest_); + EXPECT_EQ(ERR_OK, ref); + auto thirdTopAbility = stackManager_->GetCurrentTopAbility(); + thirdTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + firstTopAbility->SetAbilityState(OHOS::AAFwk::BACKGROUND); + secondTopAbility->SetAbilityState(OHOS::AAFwk::BACKGROUND); + + auto musicMisionRecord = secondTopAbility->GetMissionRecord(); + auto musicMisionRecordId = musicMisionRecord->GetMissionRecordId(); + + auto result = stackManager_->StartLockMission(sysUid, musicMisionRecordId, true, true); + EXPECT_EQ(ERR_OK, result); + + auto topRecord = stackManager_->GetCurrentTopAbility(); + auto abilityInfo = topRecord->GetAbilityInfo(); + EXPECT_EQ(abilityInfo.name, "MusicAbility2th"); + + // unlock + result = stackManager_->StartLockMission(sysUid, musicMisionRecordId, true, false); + EXPECT_EQ(ERR_OK, result); + + testing::Mock::AllowLeak(mockAppMgrClient); + testing::Mock::AllowLeak(bundleObject_); +} + +/* + * Feature: AaFwk + * Function: StartLockMission + * SubFunction: NA + * FunctionPoints: lock a mission , It's locked mission top ability will be active + * EnvConditions: NA + * CaseDescription: when locked mission died + */ +HWTEST_F(AbilityStackModuleTest, ability_stack_test_018, TestSize.Level1) +{ + stackManager_->Init(); + int userUid = 10; + EXPECT_CALL(*bundleObject_, GetUidByBundleName(_, _)) + .Times(AtLeast(2)) + .WillOnce(Return(userUid)) + .WillOnce(Return(userUid)); + + auto appScheduler = OHOS::DelayedSingleton::GetInstance(); + MockAppMgrClient *mockAppMgrClient = new MockAppMgrClient(); + appScheduler->appMgrClient_.reset(mockAppMgrClient); + + EXPECT_CALL(*mockAppMgrClient, LoadAbility(_, _, _, _)) + .Times(AtLeast(1)) + .WillOnce(Return(AppMgrResultCode::RESULT_OK)); + + // start a SINGLETON ability + auto musicAbilityRequest_ = GenerateAbilityRequest("device", "MusicSAbility", "music", "com.ix.hiMusic"); + stackManager_->StartAbility(musicAbilityRequest_); + auto secondTopAbility = stackManager_->GetCurrentTopAbility(); + secondTopAbility->SetAbilityState(OHOS::AAFwk::ACTIVE); + + // lock + auto musicMisionRecord = stackManager_->GetTopMissionRecord(); + auto musicMisionRecordId = musicMisionRecord->GetMissionRecordId(); + auto result = stackManager_->StartLockMission(userUid, musicMisionRecordId, false, true); + EXPECT_EQ(ERR_OK, result); + + // let ability die + stackManager_->OnAbilityDied(secondTopAbility); + auto state = stackManager_->lockMissionContainer_->IsLockedMissionState(); + EXPECT_FALSE(state); + + testing::Mock::AllowLeak(mockAppMgrClient); + testing::Mock::AllowLeak(bundleObject_); } } // namespace AAFwk diff --git a/services/test/moduletest/panding_want_manager_test/BUILD.gn b/services/test/moduletest/panding_want_manager_test/BUILD.gn index 562fa161fc2514bdd8c1d3b6b03226d3773f620f..c8c2df23daef06eca99fbe52cceeace3a8faa9e5 100644 --- a/services/test/moduletest/panding_want_manager_test/BUILD.gn +++ b/services/test/moduletest/panding_want_manager_test/BUILD.gn @@ -16,31 +16,28 @@ import("//foundation/aafwk/standard/aafwk.gni") import("//foundation/aafwk/standard/services/abilitymgr/abilitymgr.gni") module_output_path = "aafwk_standard/mstabilitymgrservice" -EVENT_DIR = "//base/notification/ces_standard/cesfwk" ohos_moduletest("PandingWantMgrTest") { module_out_path = module_output_path include_dirs = [ - "${EVENT_DIR}/innerkits/include", - "${EVENT_DIR}/kits/native/include", "//foundation/aafwk/standard/services/test/mock/include", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmg", "//foundation/appexecfwk/standard/kits/appkit/native/app/include", - "//base/notification/ans_standard/kits/native/wantagent/include", + "//base/notification/ans_standard/interfaces/innerkits/wantagent/include", ] sources = abilityms_files sources += [ - "//base/notification/ans_standard/kits/native/wantagent/src/completed_dispatcher.cpp", - "//base/notification/ans_standard/kits/native/wantagent/src/pending_want.cpp", - "//base/notification/ans_standard/kits/native/wantagent/src/trigger_info.cpp", - "//base/notification/ans_standard/kits/native/wantagent/src/want_agent.cpp", - "//base/notification/ans_standard/kits/native/wantagent/src/want_agent_helper.cpp", - "//base/notification/ans_standard/kits/native/wantagent/src/want_agent_info.cpp", - "//base/notification/ans_standard/kits/native/wantagent/src/want_agent_log_wrapper.cpp", + "//base/notification/ans_standard/frameworks/wantagent/src/completed_dispatcher.cpp", + "//base/notification/ans_standard/frameworks/wantagent/src/pending_want.cpp", + "//base/notification/ans_standard/frameworks/wantagent/src/trigger_info.cpp", + "//base/notification/ans_standard/frameworks/wantagent/src/want_agent.cpp", + "//base/notification/ans_standard/frameworks/wantagent/src/want_agent_helper.cpp", + "//base/notification/ans_standard/frameworks/wantagent/src/want_agent_info.cpp", + "//base/notification/ans_standard/frameworks/wantagent/src/want_agent_log_wrapper.cpp", "//foundation/aafwk/standard/services/abilitymgr/src/ability_manager_client.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_bundle_mgr.cpp", @@ -55,8 +52,6 @@ ohos_moduletest("PandingWantMgrTest") { } deps = [ - "${EVENT_DIR}/innerkits:cesfwk_innerkits", - "${EVENT_DIR}/kits/native:cesfwk_kits", "${innerkits_path}/want:want", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", @@ -72,6 +67,8 @@ ohos_moduletest("PandingWantMgrTest") { ] external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/tools/test/mock/mock_ability_manager_stub.h b/tools/test/mock/mock_ability_manager_stub.h index d5a044586d6477f1a1074d78a0cb55fd0038ba62..a389a832015c868abf20a9a1ddc2692dea4bd13b 100644 --- a/tools/test/mock/mock_ability_manager_stub.h +++ b/tools/test/mock/mock_ability_manager_stub.h @@ -96,6 +96,8 @@ public: int PowerOn(); MOCK_METHOD1(LockMission, int(int)); MOCK_METHOD1(UnlockMission, int(int)); + MOCK_METHOD2(SetMissionDescriptionInfo, int(const sptr &token, const MissionDescriptionInfo &info)); + MOCK_METHOD0(GetMissionLockModeState, int()); public: std::string powerState_;