diff --git a/interfaces/innerkits/appexecfwk_base/include/ability_info.h b/interfaces/innerkits/appexecfwk_base/include/ability_info.h index 9b0c228a87e779cc259ca6e95ccabc19e749119d..4757ef77def0595fcd16e4d391476bb2eda1deee 100644 --- a/interfaces/innerkits/appexecfwk_base/include/ability_info.h +++ b/interfaces/innerkits/appexecfwk_base/include/ability_info.h @@ -159,7 +159,7 @@ struct AbilityInfo : public Parcelable { DisplayOrientation orientation = DisplayOrientation::UNSPECIFIED; LaunchMode launchMode = LaunchMode::STANDARD; std::string srcPath; - std::string srcLanguage="js"; + std::string srcLanguage = "js"; std::vector permissions; std::string process; diff --git a/interfaces/innerkits/appexecfwk_base/include/appexecfwk_errors.h b/interfaces/innerkits/appexecfwk_base/include/appexecfwk_errors.h index 999fd70b24ddc04e578970ae08ad1152716703ea..14ee10d64f7ccf8279f5c000ca18517c6ab17796 100644 --- a/interfaces/innerkits/appexecfwk_base/include/appexecfwk_errors.h +++ b/interfaces/innerkits/appexecfwk_base/include/appexecfwk_errors.h @@ -19,7 +19,6 @@ #include "errors.h" namespace OHOS { - enum { APPEXECFWK_MODULE_COMMON = 0x00, APPEXECFWK_MODULE_APPMGR = 0x01, @@ -109,63 +108,33 @@ enum { constexpr ErrCode APPEXECFWK_FORMMGR_ERR_OFFSET = ErrCodeOffset(SUBSYS_APPEXECFWK, APPEXECFWK_MODULE_FORMMGR); enum { ERR_APPEXECFWK_FORM_COMMON_CODE = APPEXECFWK_FORMMGR_ERR_OFFSET + 1, - ERR_APPEXECFWK_FORM_PERMISSION_DENY, - ERR_APPEXECFWK_FORM_INTENT_PARCEL, + ERR_APPEXECFWK_FORM_PERMISSION_DENY, ERR_APPEXECFWK_FORM_GET_INFO_FAILED, - ERR_APPEXECFWK_FORM_GET_SYSMGR_FAILED, ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED, - ERR_APPEXECFWK_FORM_GET_FMS_FAILED, - ERR_APPEXECFWK_FORM_ADD_DEATH_RECIPIENT_FAILED, - ERR_APPEXECFWK_FORM_BIND_FORMSUPPLY_FAILED, ERR_APPEXECFWK_FORM_INVALID_PARAM, ERR_APPEXECFWK_FORM_CFG_NOT_MATCH_ID, - ERR_APPEXECFWK_FORM_ADD_NOT_EXIST_ID, + ERR_APPEXECFWK_FORM_NOT_EXIST_ID, ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED, - ERR_APPEXECFWK_FORM_EXCEED_MAX_NUMBER, + ERR_APPEXECFWK_FORM_MAX_SYSTEM_FORMS, ERR_APPEXECFWK_FORM_EXCEED_INSTANCES_PER_FORM, ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, - ERR_APPEXECFWK_FORM_SUPPLIER_DEL_FAIL, + ERR_APPEXECFWK_FORM_PROVIDER_DEL_FAIL, + ERR_APPEXECFWK_FORM_MAX_FORMS_PER_CLIENT, + ERR_APPEXECFWK_FORM_MAX_SYSTEM_TEMP_FORMS, ERR_APPEXECFWK_FORM_NO_SUCH_MODULE, ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY, ERR_APPEXECFWK_FORM_NO_SUCH_DIMENSION, ERR_APPEXECFWK_FORM_FA_NOT_INSTALLED, - ERR_APPEXECFWK_FORM_INFO_NOT_EXIST, - ERR_APPEXECFWK_FORM_HOST_INFO_NOT_EXIST, - ERR_CODE_COMMON, - ERR_NOT_EXIST_ID, - ERR_MAX_RECORDS_PER_APP, - ERR_PERMISSION_DENY, - ERR_MAX_SYSTEM_FORMS, - ERR_MAX_INSTANCES_PER_FORM, - ERR_OPERATION_FORM_NOT_SELF, - ERR_PROVIDER_DEL_FAIL, - ERR_MAX_FORMS_PER_CLIENT, - ERR_MAX_REFRESH, - ERR_MAX_SYSTEM_TEMP_FORMS, - ERR_FORM_NO_SUCH_MODULE, - ERR_FORM_NO_SUCH_ABILITY, - ERR_FORM_NO_SUCH_DIMENSION, - ERR_FORM_FA_NOT_INSTALLED, - ERR_FORM_INVALID_PARAM, - ERR_DELETE_FORM_TIMER, - ERR_CFG_NOT_MATCH_ID, - ERR_APPEXECFWK_FORM_DBCACHE_FIND_FAIL, - ERR_APPEXECFWK_FORM_JSON_CREATE_DIR_FAIL, - ERR_APPEXECFWK_FORM_JSON_NEW_FILE_FAIL, - ERR_APPEXECFWK_FORM_JSON_NO_DIR, - ERR_APPEXECFWK_FORM_JSON_OPEN_FAIL, - ERR_APPEXECFWK_FORM_JSON_FILE_EMPTY, - ERR_APPEXECFWK_FORM_JSON_FIND_FAIL, - ERR_APPEXECFWK_FORM_JSON_PARSE_FAIL, - ERR_APPEXECFWK_FORM_JSON_DELETE_FAIL, + ERR_APPEXECFWK_FORM_MAX_REQUEST, + ERR_APPEXECFWK_FORM_MAX_REFRESH, + ERR_APPEXECFWK_FORM_GET_BMS_FAILED, - // error code in sdk - ERR_GET_FMS_RPC, - ERR_FORM_DUPLICATE_ADDED, - ERR_SEND_FMS_MSG, - ERR_GET_BMS_RPC, - ERR_SEND_BMS_MSG, - ERR_IN_RECOVER, + // error code in sdk + ERR_APPEXECFWK_FORM_GET_FMS_FAILED, + ERR_APPEXECFWK_FORM_SEND_FMS_MSG, + ERR_APPEXECFWK_FORM_FORM_DUPLICATE_ADDED, + ERR_APPEXECFWK_FORM_IN_RECOVER, + ERR_APPEXECFWK_FORM_GET_SYSMGR_FAILED }; constexpr ErrCode APPEXECFWK_APPEXECFWK_ERR_OFFSET = ErrCodeOffset(SUBSYS_APPEXECFWK, APPEXECFWK_MODULE_APPEXECFWK); enum { diff --git a/interfaces/innerkits/appexecfwk_base/include/form_info.h b/interfaces/innerkits/appexecfwk_base/include/form_info.h index 3b28190c973c738895925a1275ea296b91e4cffd..6048620d7fdef30262521fe34f478edfa0d02528 100644 --- a/interfaces/innerkits/appexecfwk_base/include/form_info.h +++ b/interfaces/innerkits/appexecfwk_base/include/form_info.h @@ -21,7 +21,6 @@ namespace OHOS { namespace AppExecFwk { - enum class FormsColorMode { AUTO_MODE = -1, DARK_MODE = 0, @@ -68,7 +67,6 @@ struct FormInfo : public Parcelable { virtual bool Marshalling(Parcel &parcel) const override; static FormInfo *Unmarshalling(Parcel &parcel); }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_FORM_H diff --git a/interfaces/innerkits/appexecfwk_base/include/form_provider_data.h b/interfaces/innerkits/appexecfwk_base/include/form_provider_data.h index 51f2a3ef4fcb45d9b9215c4ef526aa5de65ec331..e23be681025b11ab529ab0704d1c407fed8655ec 100644 --- a/interfaces/innerkits/appexecfwk_base/include/form_provider_data.h +++ b/interfaces/innerkits/appexecfwk_base/include/form_provider_data.h @@ -1,163 +1,164 @@ -/* - * 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_FORM_PROVIDER_DATA_H -#define FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_DATA_H - -#include -#include - -#include "ashmem.h" -#include "message_parcel.h" -#include "nlohmann/json.hpp" -#include "parcel.h" - -namespace OHOS { -namespace AppExecFwk { -/** - * @class FormProviderData - * Defines form provider data. - */ -class FormProviderData : public Parcelable { -public: - /** - * @brief Constructor. - */ - FormProviderData(); - - /** - * @brief A constructor used to create a {@code FormProviderData} instance with data of - * the {@code nlohmann::json} type specified. - * @param jsonData Indicates the data to be carried in the new {@code FormProviderData} instance, - * in {@code nlohmann::json} format. - */ - FormProviderData(nlohmann::json &jsonData); - - /** - * @brief A constructor used to create a {@code FormProviderData} instance with data of the {@code String} type - * specified. - * @param jsonDataString Indicates the data to be carried in the new {@code FormProviderData} instance, in JSON - * string format. - */ - FormProviderData(std::string jsonDataString); - - /** - * @brief Destructor. - */ - virtual ~FormProviderData(){}; - - /** - * @brief Updates form data in this {@code FormProviderData} object. - * @param jsonData Indicates the new data to use, in {@code nlohmann::json} format. - */ - void UpdateData(nlohmann::json &jsonData); - - /** - * @brief Obtains the form data stored in this {@code FormProviderData} object. - * @return Returns json string format - */ - std::string GetDataString() const; - - /** - * @brief Adds an image to this {@code FormProviderData} instance. - * @param picName Indicates the name of the image to add. - * @param data Indicates the binary data of the image content. - */ - void AddImageData(std::string picName, char *data); - - /** - * @brief Removes data of an image with the specified {@code picName} from this {@code FormProviderData} instance. - * @param picName Indicates the name of the image to remove. - */ - void RemoveImageData(std::string picName); - - /** - * @brief Obtains the add/remove state stored in this {@code FormProviderData} object. - * @return Returns the add/remove state of shared image data. - */ - int32_t GetImageDataState(); - - /** - * @brief Updates imageDataState in this {@code FormProviderData} object. - * @param imageDataState Indicates the imageDataState to update. - */ - void SetImageDataState(int32_t imageDataState); - - /** - * @brief Obtains the imageDataMap stored in this {@code FormProviderData} object. - * @return Returns the map that contains shared image data. - */ - std::map, int32_t>> GetImageDataMap(); - - /** - * @brief Updates imageDataMap in this {@code FormProviderData} object. - * @param imageDataMap Indicates the imageDataMap to update. - */ - void SetImageDataMap(std::map, int32_t>> imageDataMap); - - /** - * @brief Obtains the form data stored in this {@code FormProviderData} object. - * @return Returns json data - */ - nlohmann::json GetData() const; - /** - * @brief Set the form data stored from string string. - * @param Returns string string. - */ - void SetDataString(std::string &jsonDataString); - /** - * @brief Merge new data to FormProviderData. - * @param addJsonData data to merge to FormProviderData - */ - void MergeData(nlohmann::json &addJsonData); - - /** - * Read this {@code FormProviderData} object from a Parcel. - * @param parcel the parcel - * eturn Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. - */ - bool ReadFromParcel(Parcel &parcel); - /** - * @brief Marshals this {@code FormProviderData} object into a {@link ohos.utils.Parcel} object. - * @param parcel Indicates the {@code Parcel} object for marshalling. - * @return Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. - */ - virtual bool Marshalling(Parcel &parcel) const override; - - /** - * @brief Unmarshals this {@code FormProviderData} object from a {@link ohos.utils.Parcel} object. - * @param parcel Indicates the {@code Parcel} object for unmarshalling. - * @return Returns FormProviderData. - */ - static FormProviderData* Unmarshalling(Parcel &parcel); - - /** - * @brief Clear imageDataMap, rawImageBytesMap, imageDataState and jsonFormProviderData. - */ - void ClearData(); - -private: - bool WriteImageDataToParcel(Parcel &parcel, std::string picName, char *data) const; - -private: - nlohmann::json jsonFormProviderData_; - std::map, int32_t>> imageDataMap_; - std::map rawImageBytesMap_; - int32_t imageDataState_; -}; -} // namespace AppExecFwk -} // namespace OHOS - -#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_DATA_H +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_DATA_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_DATA_H + +#include +#include +#include + +#include "ashmem.h" +#include "message_parcel.h" +#include "nlohmann/json.hpp" +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormProviderData + * Defines form provider data. + */ +class FormProviderData : public Parcelable { +public: + /** + * @brief Constructor. + */ + FormProviderData(); + + /** + * @brief A constructor used to create a {@code FormProviderData} instance with data of + * the {@code nlohmann::json} type specified. + * @param jsonData Indicates the data to be carried in the new {@code FormProviderData} instance, + * in {@code nlohmann::json} format. + */ + FormProviderData(nlohmann::json &jsonData); + + /** + * @brief A constructor used to create a {@code FormProviderData} instance with data of the {@code String} type + * specified. + * @param jsonDataString Indicates the data to be carried in the new {@code FormProviderData} instance, in JSON + * string format. + */ + FormProviderData(std::string jsonDataString); + + /** + * @brief Destructor. + */ + virtual ~FormProviderData(){}; + + /** + * @brief Updates form data in this {@code FormProviderData} object. + * @param jsonData Indicates the new data to use, in {@code nlohmann::json} format. + */ + void UpdateData(nlohmann::json &jsonData); + + /** + * @brief Obtains the form data stored in this {@code FormProviderData} object. + * @return Returns json string format + */ + std::string GetDataString() const; + + /** + * @brief Adds an image to this {@code FormProviderData} instance. + * @param picName Indicates the name of the image to add. + * @param data Indicates the binary data of the image content. + */ + void AddImageData(std::string picName, char *data); + + /** + * @brief Removes data of an image with the specified {@code picName} from this {@code FormProviderData} instance. + * @param picName Indicates the name of the image to remove. + */ + void RemoveImageData(std::string picName); + + /** + * @brief Obtains the add/remove state stored in this {@code FormProviderData} object. + * @return Returns the add/remove state of shared image data. + */ + int32_t GetImageDataState(); + + /** + * @brief Updates imageDataState in this {@code FormProviderData} object. + * @param imageDataState Indicates the imageDataState to update. + */ + void SetImageDataState(int32_t imageDataState); + + /** + * @brief Obtains the imageDataMap stored in this {@code FormProviderData} object. + * @return Returns the map that contains shared image data. + */ + std::map, int32_t>> GetImageDataMap(); + + /** + * @brief Updates imageDataMap in this {@code FormProviderData} object. + * @param imageDataMap Indicates the imageDataMap to update. + */ + void SetImageDataMap(std::map, int32_t>> imageDataMap); + + /** + * @brief Obtains the form data stored in this {@code FormProviderData} object. + * @return Returns json data + */ + nlohmann::json GetData() const; + /** + * @brief Set the form data stored from string string. + * @param Returns string string. + */ + void SetDataString(std::string &jsonDataString); + /** + * @brief Merge new data to FormProviderData. + * @param addJsonData data to merge to FormProviderData + */ + void MergeData(nlohmann::json &addJsonData); + + /** + * Read this {@code FormProviderData} object from a Parcel. + * @param parcel the parcel + * eturn Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + /** + * @brief Marshals this {@code FormProviderData} object into a {@link ohos.utils.Parcel} object. + * @param parcel Indicates the {@code Parcel} object for marshalling. + * @return Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals this {@code FormProviderData} object from a {@link ohos.utils.Parcel} object. + * @param parcel Indicates the {@code Parcel} object for unmarshalling. + * @return Returns FormProviderData. + */ + static FormProviderData* Unmarshalling(Parcel &parcel); + + /** + * @brief Clear imageDataMap, rawImageBytesMap, imageDataState and jsonFormProviderData. + */ + void ClearData(); + +private: + bool WriteImageDataToParcel(Parcel &parcel, std::string picName, char *data) const; + +private: + nlohmann::json jsonFormProviderData_; + std::map, int32_t>> imageDataMap_; + std::map rawImageBytesMap_; + int32_t imageDataState_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_DATA_H diff --git a/interfaces/innerkits/appexecfwk_base/include/form_provider_info.h b/interfaces/innerkits/appexecfwk_base/include/form_provider_info.h index 73bfd4a478cf0b6a8c48a99b5600d4064c19f6ec..522b8584d0550a395022032aa42dd9a85c6d93f6 100644 --- a/interfaces/innerkits/appexecfwk_base/include/form_provider_info.h +++ b/interfaces/innerkits/appexecfwk_base/include/form_provider_info.h @@ -1,114 +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_FORM_PROVIDER_INFO_H -#define FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_INFO_H - -#include -#include "form_provider_data.h" -#include "parcel.h" - -namespace OHOS { -namespace AppExecFwk { -/** - * @struct FormProviderInfo - * Defines form provider info. - */ -class FormProviderInfo : public Parcelable { -public: - FormProviderInfo() = default; - ~FormProviderInfo() = default; - /** - * @brief Set the id of the form. - * @param formId the id of the form. - */ - inline void SetFormId(const int64_t formId) - { - formId_ = formId; - } - /** - * @brief Get the id of the form. - * @return the id of the form. - */ - inline int64_t GetFormId() const - { - return formId_; - } - /** - * @brief Set the form data. - * @param formProviderData The form data. - */ - inline void SetFormData(const FormProviderData &formProviderData) - { - jsBindingData_ = formProviderData; - } - - /** - * @brief Get the form data. - * @return the form data. - */ - inline FormProviderData GetFormData() const - { - return jsBindingData_; - } - /** - * @brief Get the form data. - * @return the form data. - */ - inline std::string GetFormDataString() const - { - return jsBindingData_.GetDataString(); - } - - /** - * @brief Set the upgrade flg. - * @param upgradeFlg The upgrade flg. - */ - inline void SetUpgradeFlg(const bool upgradeFlg) - { - upgradeFlg_ = upgradeFlg; - } - /** - * @brief Get the upgrade flg. - * @return the upgrade flg. - */ - inline bool GetUpgradeFlg() const - { - return upgradeFlg_; - } - - /** - * @brief Set form date by string. - * @param dataString string json data. - */ - void SetFormDataString(std::string &dataString); - - /** - * @brief Merge new data to FormProviderData. - * @param addJsonData data to merge to FormProviderData - */ - void MergeData(nlohmann::json &addJsonData); - - bool ReadFromParcel(Parcel &parcel); - virtual bool Marshalling(Parcel &parcel) const override; - static FormProviderInfo *Unmarshalling(Parcel &parcel); -private: - int64_t formId_; - FormProviderData jsBindingData_; - bool upgradeFlg_; -}; -} // namespace AppExecFwk -} // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_INFO_H +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_INFO_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_INFO_H + +#include +#include "form_provider_data.h" +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @struct FormProviderInfo + * Defines form provider info. + */ +class FormProviderInfo : public Parcelable { +public: + FormProviderInfo() = default; + ~FormProviderInfo() = default; + + /** + * @brief Set the form data. + * @param formProviderData The form data. + */ + inline void SetFormData(const FormProviderData &formProviderData) + { + jsBindingData_ = formProviderData; + } + + /** + * @brief Get the form data. + * @return the form data. + */ + inline FormProviderData GetFormData() const + { + return jsBindingData_; + } + /** + * @brief Get the form data. + * @return the form data. + */ + inline std::string GetFormDataString() const + { + return jsBindingData_.GetDataString(); + } + + /** + * @brief Set the upgrade flg. + * @param upgradeFlg The upgrade flg. + */ + inline void SetUpgradeFlg(const bool upgradeFlg) + { + upgradeFlg_ = upgradeFlg; + } + /** + * @brief Get the upgrade flg. + * @return the upgrade flg. + */ + inline bool GetUpgradeFlg() const + { + return upgradeFlg_; + } + + /** + * @brief Set form date by string. + * @param dataString string json data. + */ + void SetFormDataString(std::string &dataString); + + /** + * @brief Merge new data to FormProviderData. + * @param addJsonData data to merge to FormProviderData + */ + void MergeData(nlohmann::json &addJsonData); + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static FormProviderInfo *Unmarshalling(Parcel &parcel); +private: + FormProviderData jsBindingData_; + bool upgradeFlg_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_INFO_H diff --git a/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp b/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp index a71151fa06a767b9dda71e84012b1e0079e8bc2b..cbd638a7fbd422bc8fffe44a727a59ca85e3f37d 100644 --- a/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp @@ -79,7 +79,8 @@ const std::string JSON_KEY_LABEL_ID = "labelId"; const std::string JSON_KEY_DESCRIPTION_ID = "descriptionId"; const std::string JSON_KEY_ICON_ID = "iconId"; const std::string JSON_KEY_FORM_ENABLED = "formEnabled"; - +const std::string JSON_KEY_SRC_PATH = "srcPath"; +const std::string JSON_KEY_SRC_LANGUAGE = "srcLanguage"; } // namespace bool AbilityInfo::ReadFromParcel(Parcel &parcel) @@ -103,6 +104,8 @@ bool AbilityInfo::ReadFromParcel(Parcel &parcel) targetAbility = Str16ToStr8(parcel.ReadString16()); readPermission = Str16ToStr8(parcel.ReadString16()); writePermission = Str16ToStr8(parcel.ReadString16()); + srcPath = Str16ToStr8(parcel.ReadString16()); + srcLanguage = Str16ToStr8(parcel.ReadString16()); visible = parcel.ReadBool(); isLauncherAbility = parcel.ReadBool(); isNativeAbility = parcel.ReadBool(); @@ -233,6 +236,8 @@ bool AbilityInfo::Marshalling(Parcel &parcel) const WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(targetAbility)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(readPermission)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(writePermission)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(srcPath)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(srcLanguage)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, visible); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, isLauncherAbility); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, isNativeAbility); @@ -375,6 +380,8 @@ void to_json(nlohmann::json &jsonObject, const AbilityInfo &abilityInfo) {JSON_KEY_SUPPORT_PIP_MODE, abilityInfo.supportPipMode}, {JSON_KEY_READ_PERMISSION, abilityInfo.readPermission}, {JSON_KEY_WRITE_PERMISSION, abilityInfo.writePermission}, + {JSON_KEY_SRC_PATH, abilityInfo.srcPath}, + {JSON_KEY_SRC_LANGUAGE, abilityInfo.srcLanguage}, {JSON_KEY_CONFIG_CHANGES, abilityInfo.configChanges}, {JSON_KEY_FORM_ENTITY, abilityInfo.formEntity}, {JSON_KEY_MIN_FORM_HEIGHT, abilityInfo.minFormHeight}, @@ -449,6 +456,8 @@ void from_json(const nlohmann::json &jsonObject, AbilityInfo &abilityInfo) abilityInfo.supportPipMode = jsonObject.at(JSON_KEY_SUPPORT_PIP_MODE).get(); abilityInfo.readPermission = jsonObject.at(JSON_KEY_READ_PERMISSION).get(); abilityInfo.writePermission = jsonObject.at(JSON_KEY_WRITE_PERMISSION).get(); + abilityInfo.srcPath = jsonObject.at(JSON_KEY_SRC_PATH).get(); + abilityInfo.srcLanguage = jsonObject.at(JSON_KEY_SRC_LANGUAGE).get(); abilityInfo.configChanges = jsonObject.at(JSON_KEY_CONFIG_CHANGES).get>(); abilityInfo.formEntity = jsonObject.at(JSON_KEY_FORM_ENTITY).get(); abilityInfo.minFormHeight = jsonObject.at(JSON_KEY_MIN_FORM_HEIGHT).get(); diff --git a/interfaces/innerkits/appexecfwk_base/src/application_info.cpp b/interfaces/innerkits/appexecfwk_base/src/application_info.cpp index d24b23b86cacbe6310474a157e212c7a6bdc5e24..41ba13b3306eb06019a6bf43d7319c9b5fa1c5c3 100644 --- a/interfaces/innerkits/appexecfwk_base/src/application_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/application_info.cpp @@ -232,7 +232,7 @@ void ApplicationInfo::ConvertToCompatibleApplicationInfo(CompatibleApplicationIn compatibleApplicationInfo.permissions = permissions; compatibleApplicationInfo.moduleInfos = moduleInfos; compatibleApplicationInfo.supportedModes = supportedModes; - compatibleApplicationInfo.enabled = debug; + compatibleApplicationInfo.enabled = enabled; } } // namespace AppExecFwk diff --git a/interfaces/innerkits/appexecfwk_base/src/bundle_info.cpp b/interfaces/innerkits/appexecfwk_base/src/bundle_info.cpp index a0356c00a6db85d3a4740ba751ec02112ce2909b..21a4cf214586ea002b3418df221c04a3678177d0 100644 --- a/interfaces/innerkits/appexecfwk_base/src/bundle_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/bundle_info.cpp @@ -109,6 +109,16 @@ bool BundleInfo::ReadFromParcel(Parcel &parcel) } abilityInfos.emplace_back(*abilityInfo); } + + int32_t hapModuleInfosSize = parcel.ReadInt32(); + for (int32_t i = 0; i < hapModuleInfosSize; i++) { + std::unique_ptr hapModuleInfo(parcel.ReadParcelable()); + if (!hapModuleInfo) { + APP_LOGE("ReadParcelable failed"); + return false; + } + hapModuleInfos.emplace_back(*hapModuleInfo); + } return true; } @@ -180,6 +190,11 @@ bool BundleInfo::Marshalling(Parcel &parcel) const for (auto &abilityInfo : abilityInfos) { WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Parcelable, parcel, &abilityInfo); } + + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, hapModuleInfos.size()); + for (auto &hapModuleInfo : hapModuleInfos) { + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Parcelable, parcel, &hapModuleInfo); + } return true; } diff --git a/interfaces/innerkits/appexecfwk_base/src/form_info.cpp b/interfaces/innerkits/appexecfwk_base/src/form_info.cpp index 7f9f1d2e23f69f72ba35bea6f63113f9640b9d23..9e589c283d149557e8d2057d85149b45ba129780 100644 --- a/interfaces/innerkits/appexecfwk_base/src/form_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/form_info.cpp @@ -29,9 +29,7 @@ namespace OHOS { namespace AppExecFwk { - namespace { - const std::string JSON_KEY_COLOR_MODE = "colorMode"; const std::string JSON_KEY_PACKAGE = "package"; const std::string JSON_KEY_SUPPORT_DIMENSIONS = "supportDimensions"; @@ -57,7 +55,6 @@ const std::string JSON_KEY_FORM_VISIBLE_NOTIFY = "formVisibleNotify"; const std::string JSON_KEY_RELATED_BUNDLE_NAME = "relatedBundleName"; const std::string JSON_KEY_DEFAULT_FLAG = "defaultFlag"; const std::string JSON_KEY_PORTRAIT_LAYOUTS = "portraitLayouts"; - } // namespace bool FormInfo::ReadFromParcel(Parcel &parcel) @@ -184,12 +181,16 @@ bool FormInfo::Marshalling(Parcel &parcel) const void to_json(nlohmann::json &jsonObject, const FormCustomizeData &customizeDatas) { - jsonObject = nlohmann::json{{JSON_KEY_NAME, customizeDatas.name}, {JSON_KEY_VALUE, customizeDatas.value}}; + jsonObject = nlohmann::json{ + {JSON_KEY_NAME, customizeDatas.name}, + {JSON_KEY_VALUE, customizeDatas.value} + }; } void to_json(nlohmann::json &jsonObject, const FormInfo &formInfo) { - jsonObject = nlohmann::json{{JSON_KEY_NAME, formInfo.name}, + jsonObject = nlohmann::json{ + {JSON_KEY_NAME, formInfo.name}, {JSON_KEY_PACKAGE, formInfo.package}, {JSON_KEY_BUNDLE_NAME, formInfo.bundleName}, {JSON_KEY_MODULE_NAME, formInfo.moduleName}, @@ -212,7 +213,8 @@ void to_json(nlohmann::json &jsonObject, const FormInfo &formInfo) {JSON_KEY_SUPPORT_DIMENSIONS, formInfo.supportDimensions}, {JSON_KEY_CUSTOMIZE_DATA, formInfo.customizeDatas}, {JSON_KEY_LANDSCAPE_LAYOUTS, formInfo.landscapeLayouts}, - {JSON_KEY_PORTRAIT_LAYOUTS, formInfo.portraitLayouts}}; + {JSON_KEY_PORTRAIT_LAYOUTS, formInfo.portraitLayouts} + }; } void from_json(const nlohmann::json &jsonObject, FormCustomizeData &customizeDatas) @@ -248,6 +250,5 @@ void from_json(const nlohmann::json &jsonObject, FormInfo &formInfo) formInfo.landscapeLayouts = jsonObject.at(JSON_KEY_LANDSCAPE_LAYOUTS).get>(); formInfo.portraitLayouts = jsonObject.at(JSON_KEY_PORTRAIT_LAYOUTS).get>(); } - } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_base/src/form_js_info.cpp b/interfaces/innerkits/appexecfwk_base/src/form_js_info.cpp index df1deb988a0721179d6f4ac36ef2099404b73057..13a5d3c2684590d10ba36156844b6dda4c35fd5b 100644 --- a/interfaces/innerkits/appexecfwk_base/src/form_js_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/form_js_info.cpp @@ -1,91 +1,92 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "form_js_info.h" -#include "string_ex.h" - -namespace OHOS { -namespace AppExecFwk { -bool FormJsInfo::ReadFromParcel(Parcel &parcel) -{ - formId = parcel.ReadInt64(); - formName = Str16ToStr8(parcel.ReadString16()); - bundleName = Str16ToStr8(parcel.ReadString16()); - abilityName = Str16ToStr8(parcel.ReadString16()); - - formTempFlg = parcel.ReadBool(); - jsFormCodePath = Str16ToStr8(parcel.ReadString16()); - formData = Str16ToStr8(parcel.ReadString16()); - - auto bindingData = parcel.ReadParcelable(); - formProviderData = *bindingData; - - return true; -} - -FormJsInfo *FormJsInfo::Unmarshalling(Parcel &parcel) -{ - FormJsInfo *formJsInfo = new (std::nothrow) FormJsInfo(); - if (formJsInfo && !formJsInfo->ReadFromParcel(parcel)) { - delete formJsInfo; - formJsInfo = nullptr; - } - return formJsInfo; -} - -bool FormJsInfo::Marshalling(Parcel &parcel) const -{ - // write formId - if (!parcel.WriteInt64(formId)) { - return false; - } - // write formName - if (!parcel.WriteString16(Str8ToStr16(formName))) { - return false; - } - // write bundleName - if (!parcel.WriteString16(Str8ToStr16(bundleName))) { - return false; - } - // write abilityName - if (!parcel.WriteString16(Str8ToStr16(abilityName))) { - return false; - } - - // write tempFlag - if (!parcel.WriteBool(formTempFlg)) { - return false; - } - - // write jsFormCodePath - if (!parcel.WriteString16(Str8ToStr16(jsFormCodePath))) { - return false; - } - - // write formData - if (!parcel.WriteString16(Str8ToStr16(formData))) { - return false; - } - - // write formProviderData - if (!parcel.WriteParcelable(&formProviderData)) { - return false; - } - - - return true; -} -} // namespace AppExecFwk +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "form_js_info.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +bool FormJsInfo::ReadFromParcel(Parcel &parcel) +{ + formId = parcel.ReadInt64(); + formName = Str16ToStr8(parcel.ReadString16()); + bundleName = Str16ToStr8(parcel.ReadString16()); + abilityName = Str16ToStr8(parcel.ReadString16()); + + formTempFlg = parcel.ReadBool(); + jsFormCodePath = Str16ToStr8(parcel.ReadString16()); + formData = Str16ToStr8(parcel.ReadString16()); + + auto bindingData = parcel.ReadParcelable(); + formProviderData = *bindingData; + if (nullptr == bindingData){ + return false; + } + return true; +} + +FormJsInfo *FormJsInfo::Unmarshalling(Parcel &parcel) +{ + FormJsInfo *formJsInfo = new (std::nothrow) FormJsInfo(); + if (formJsInfo && !formJsInfo->ReadFromParcel(parcel)) { + delete formJsInfo; + formJsInfo = nullptr; + } + return formJsInfo; +} + +bool FormJsInfo::Marshalling(Parcel &parcel) const +{ + // write formId + if (!parcel.WriteInt64(formId)) { + return false; + } + // write formName + if (!parcel.WriteString16(Str8ToStr16(formName))) { + return false; + } + // write bundleName + if (!parcel.WriteString16(Str8ToStr16(bundleName))) { + return false; + } + // write abilityName + if (!parcel.WriteString16(Str8ToStr16(abilityName))) { + return false; + } + + // write tempFlag + if (!parcel.WriteBool(formTempFlg)) { + return false; + } + + // write jsFormCodePath + if (!parcel.WriteString16(Str8ToStr16(jsFormCodePath))) { + return false; + } + + // write formData + if (!parcel.WriteString16(Str8ToStr16(formData))) { + return false; + } + + // write formProviderData + if (!parcel.WriteParcelable(&formProviderData)) { + return false; + } + + return true; +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_base/src/form_provider_data.cpp b/interfaces/innerkits/appexecfwk_base/src/form_provider_data.cpp index e314d468e144efc2d81f3895e5c8874507c0fd7b..918a832f4048055e3191ddb7def4be7bb65e4648 100644 --- a/interfaces/innerkits/appexecfwk_base/src/form_provider_data.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/form_provider_data.cpp @@ -1,321 +1,324 @@ -/* - * 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 "app_log_wrapper.h" -#include "form_provider_data.h" -#include "message_parcel.h" -#include "string_ex.h" - -namespace OHOS { -namespace AppExecFwk { -const int IMAGE_DATA_STATE_REMOVED = -1; -const int IMAGE_DATA_STATE_NO_OPERATION = 0; -const int IMAGE_DATA_STATE_ADDED = 1; - -/** - * @brief Constructor. - */ -FormProviderData::FormProviderData() -{ - jsonFormProviderData_.clear(); -} - -/** - * @brief A constructor used to create a {@code FormProviderData} instance with data of - * the {@code nlohmann::json} type specified. - * @param jsonData Indicates the data to be carried in the new {@code FormProviderData} instance, - * in {@code nlohmann::json} format. - */ -FormProviderData::FormProviderData(nlohmann::json &jsonData) -{ - jsonFormProviderData_ = jsonData; -} - -/** - * @brief A constructor used to create a {@code FormProviderData} instance with data of the {@code String} type - * specified. - * @param jsonDataString Indicates the data to be carried in the new {@code FormProviderData} instance, - * in JSON string format. - */ -FormProviderData::FormProviderData(std::string jsonDataString) -{ - jsonFormProviderData_ = nlohmann::json::parse(jsonDataString); -} - -/** - * @brief Updates form data in this {@code FormProviderData} object. - * @param jsonData Indicates the new data to use, in {@code ZSONObject} format. - */ -void FormProviderData::UpdateData(nlohmann::json &jsonData) -{ - jsonFormProviderData_ = jsonData; -} -/** - * @brief Obtains the form data stored in this {@code FormProviderData} object. - * @return Returns json data - */ -nlohmann::json FormProviderData::GetData() const -{ - return jsonFormProviderData_; -} -/** - * @brief Obtains the form data stored in this {@code FormProviderData} object. - * @return Returns json string format - */ -std::string FormProviderData::GetDataString() const -{ - APP_LOGI("%{public}s called", __func__); - return jsonFormProviderData_.empty() ? "" : jsonFormProviderData_.dump(); -} - -/** - * @brief Adds an image to this {@code FormProviderData} instance. - * @param picName Indicates the name of the image to add. - * @param data Indicates the binary data of the image content. - */ -void FormProviderData::AddImageData(std::string picName, char *data) -{ - if ((picName.length() == 0) || (sizeof(data) == 0)) { - APP_LOGE("input param is NULL!"); - return; - } - - rawImageBytesMap_[picName] = data; - - imageDataState_ = IMAGE_DATA_STATE_ADDED; -} - -/** - * @brief Removes data of an image with the specified {@code picName} from this {@code FormProviderData} instance. - * @param picName Indicates the name of the image to remove. - */ -void FormProviderData::RemoveImageData(std::string picName) -{ - rawImageBytesMap_.erase(picName); -} - -/** - * @brief Set the form data stored from string string. - * @param Returns string string. - */ -void FormProviderData::SetDataString(std::string &jsonDataString) -{ - APP_LOGI("%{public}s called", __func__); - jsonFormProviderData_ = nlohmann::json::parse(jsonDataString); -} -/** - * @brief Merge new data to FormProviderData. - * @param addJsonData data to merge to FormProviderData - */ -void FormProviderData::MergeData(nlohmann::json &addJsonData) -{ - APP_LOGI("%{public}s called", __func__); - if (addJsonData.empty()) { - return; - } - - if (jsonFormProviderData_.empty()) { - jsonFormProviderData_ = addJsonData; - return; - } - - for (auto &it : addJsonData.items()) { - jsonFormProviderData_[it.key()] = it.value(); - } -} - -/** - * @brief Obtains the imageDataMap stored in this {@code FormProviderData} object. - * @return Returns the map that contains shared image data. - */ -std::map, int32_t>> FormProviderData::GetImageDataMap() -{ - return imageDataMap_; -} - -/** - * @brief Obtains the add/remove state stored in this {@code FormProviderData} object. - * @return Returns the add/remove state of shared image data. - */ -int32_t FormProviderData::GetImageDataState() -{ - return imageDataState_; -} - -/** - * @brief Updates imageDataState in this {@code FormProviderData} object. - * @param imageDataState Indicates the imageDataState to update. - */ -void FormProviderData::SetImageDataState(int32_t imageDataState) -{ - imageDataState_ = imageDataState; -} - -/** - * @brief Updates imageDataMap in this {@code FormProviderData} object. - * @param imageDataMap Indicates the imageDataMap to update. - */ -void FormProviderData::SetImageDataMap(std::map, int32_t>> imageDataMap) -{ - imageDataMap_ = imageDataMap; -} - -/** - * Read this {@code FormProviderData} object from a Parcel. - * @param parcel the parcel - * eturn Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. - */ -bool FormProviderData::ReadFromParcel(Parcel &parcel) -{ - jsonFormProviderData_ = nlohmann::json::parse(Str16ToStr8(parcel.ReadString16())); - // MessageParcel* messageParcel = dynamic_cast&parcel; // dynamic_cast need rtti - // if(messageParcel == nullptr) { - // return true; - // } - - imageDataState_ = parcel.ReadInt32(); - switch (imageDataState_) { - case IMAGE_DATA_STATE_ADDED: { - int32_t imageDataNum = parcel.ReadInt32(); - for (int32_t i = 0; i < imageDataNum; i++) { - MessageParcel* messageParcel = (MessageParcel*)&parcel; - sptr ashmem = messageParcel->ReadAshmem(); - if (ashmem == nullptr) { - APP_LOGE("%{public}s failed, ashmem is nullptr", __func__); - return false; - } - - int32_t len = parcel.ReadInt32(); - std::pair, int32_t> imageDataRecord = std::make_pair(ashmem, len); - imageDataMap_.emplace(Str16ToStr8(parcel.ReadString16()), imageDataRecord); - } - break; - } - case IMAGE_DATA_STATE_NO_OPERATION: - case IMAGE_DATA_STATE_REMOVED: - break; - default: - APP_LOGW("%{public}s failed, unexpected imageDataState_ %{public}d", __func__, imageDataState_); - break; - } - return true; -} - -/** - * @brief Marshals this {@code FormProviderData} object into a {@link ohos.utils.Parcel} object. - * @param parcel Indicates the {@code Parcel} object for marshalling. - * @return Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. - */ -bool FormProviderData::Marshalling(Parcel &parcel) const -{ - APP_LOGI("%{public}s called", __func__); - if (!parcel.WriteString16(Str8ToStr16(jsonFormProviderData_.empty() ? "" : jsonFormProviderData_.dump()))) { - return false; - } - // MessageParcel* messageParcel = dynamic_cast&parcel; // dynamic_cast need rtti - // if(messageParcel == nullptr) { - // return true; - // } - - parcel.WriteInt32(imageDataState_); - switch (imageDataState_) { - case IMAGE_DATA_STATE_ADDED: { - if (rawImageBytesMap_.size() == 0) { - APP_LOGE("%{public}s failed, rawImageBytesMap_ is empty", __func__); - return false; - } - parcel.WriteInt32(rawImageBytesMap_.size()); // firstly write the number of shared image to add - for (auto &entry : rawImageBytesMap_) { - if (!WriteImageDataToParcel(parcel, entry.first, entry.second)) { - APP_LOGE("%{public}s failed, the picture name is %{public}s", __func__, entry.first.c_str()); - return false; - } - parcel.WriteInt32(sizeof(entry.second)); - parcel.WriteString16(Str8ToStr16(entry.first)); - } - break; - } - case IMAGE_DATA_STATE_NO_OPERATION: - case IMAGE_DATA_STATE_REMOVED: - break; - default: - APP_LOGW("%{public}s failed, unexpected imageDataState_ %{public}d", __func__, imageDataState_); - break; - } - return true; -} - -/** - * @brief Unmarshals this {@code FormProviderData} object from a {@link ohos.utils.Parcel} object. - * @param parcel Indicates the {@code Parcel} object for unmarshalling. - * @return FormProviderData. - */ -FormProviderData* FormProviderData::Unmarshalling(Parcel &parcel) -{ - FormProviderData *formProviderData = new (std::nothrow) FormProviderData(); - if (formProviderData && !formProviderData->ReadFromParcel(parcel)) { - delete formProviderData; - formProviderData = nullptr; - } - - return formProviderData; -} - -/** - * @brief Clear imageDataMap, rawImageBytesMap_, imageDataState_ and jsonFormProviderData_. - */ -void FormProviderData::ClearData() -{ - jsonFormProviderData_.clear(); -} - -bool FormProviderData::WriteImageDataToParcel(Parcel &parcel, std::string picName, char *data) const -{ - sptr ashmem = Ashmem::CreateAshmem(picName.c_str(), sizeof(data)); - if (ashmem == nullptr) { - APP_LOGE("create shared memory fail"); - return false; - } - - bool ret = ashmem->MapReadAndWriteAshmem(); - if (!ret) { - APP_LOGE("map shared memory fail"); - return false; - } - - ret = ashmem->WriteToAshmem(data, sizeof(data), 0); - if (!ret) { - APP_LOGE("write image data to shared memory fail"); - return false; - } - - ashmem->UnmapAshmem(); - - MessageParcel* messageParcel = (MessageParcel*)&parcel; - ret = messageParcel->WriteAshmem(ashmem); - - ashmem->CloseAshmem(); // close ashmem after writeAshmem because writeAshmem will dup fd - if (!ret) { - APP_LOGE("writeAshmem fail, the picture name is %{public}s", picName.c_str()); - return false; - } - - return true; -} -} // namespace AppExecFwk -} // namespace OHOS +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "app_log_wrapper.h" +#include "form_provider_data.h" +#include "message_parcel.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +const int IMAGE_DATA_STATE_REMOVED = -1; +const int IMAGE_DATA_STATE_NO_OPERATION = 0; +const int IMAGE_DATA_STATE_ADDED = 1; +const std::string JSON_EMPTY_STRING = "{}"; + +/** + * @brief Constructor. + */ +FormProviderData::FormProviderData() +{ + jsonFormProviderData_.clear(); +} + +/** + * @brief A constructor used to create a {@code FormProviderData} instance with data of + * the {@code nlohmann::json} type specified. + * @param jsonData Indicates the data to be carried in the new {@code FormProviderData} instance, + * in {@code nlohmann::json} format. + */ +FormProviderData::FormProviderData(nlohmann::json &jsonData) +{ + jsonFormProviderData_ = jsonData; +} + +/** + * @brief A constructor used to create a {@code FormProviderData} instance with data of the {@code String} type + * specified. + * @param jsonDataString Indicates the data to be carried in the new {@code FormProviderData} instance, + * in JSON string format. + */ +FormProviderData::FormProviderData(std::string jsonDataString) +{ + if(jsonDataString.empty()) { + jsonDataString = JSON_EMPTY_STRING; + } + jsonFormProviderData_ = nlohmann::json::parse(jsonDataString); +} + +/** + * @brief Updates form data in this {@code FormProviderData} object. + * @param jsonData Indicates the new data to use, in {@code ZSONObject} format. + */ +void FormProviderData::UpdateData(nlohmann::json &jsonData) +{ + jsonFormProviderData_ = jsonData; +} +/** + * @brief Obtains the form data stored in this {@code FormProviderData} object. + * @return Returns json data + */ +nlohmann::json FormProviderData::GetData() const +{ + return jsonFormProviderData_; +} +/** + * @brief Obtains the form data stored in this {@code FormProviderData} object. + * @return Returns json string format + */ +std::string FormProviderData::GetDataString() const +{ + APP_LOGI("%{public}s called", __func__); + std::string dataStr = jsonFormProviderData_.empty() ? "" : jsonFormProviderData_.dump(); + APP_LOGI("%{public}s, data: %{public}s", __func__, dataStr.c_str()); + return dataStr; +} + +/** + * @brief Adds an image to this {@code FormProviderData} instance. + * @param picName Indicates the name of the image to add. + * @param data Indicates the binary data of the image content. + */ +void FormProviderData::AddImageData(std::string picName, char *data) +{ + if ((picName.length() == 0) || (sizeof(data) == 0)) { + APP_LOGE("input param is NULL!"); + return; + } + + rawImageBytesMap_[picName] = data; + + imageDataState_ = IMAGE_DATA_STATE_ADDED; +} + +/** + * @brief Removes data of an image with the specified {@code picName} from this {@code FormProviderData} instance. + * @param picName Indicates the name of the image to remove. + */ +void FormProviderData::RemoveImageData(std::string picName) +{ + rawImageBytesMap_.erase(picName); +} + +/** + * @brief Set the form data stored from string string. + * @param Returns string string. + */ +void FormProviderData::SetDataString(std::string &jsonDataString) +{ + APP_LOGI("%{public}s called", __func__); + if(jsonDataString.empty()) { + jsonDataString = JSON_EMPTY_STRING; + } + jsonFormProviderData_ = nlohmann::json::parse(jsonDataString); +} +/** + * @brief Merge new data to FormProviderData. + * @param addJsonData data to merge to FormProviderData + */ +void FormProviderData::MergeData(nlohmann::json &addJsonData) +{ + APP_LOGI("%{public}s called", __func__); + if (addJsonData.empty()) { + return; + } + + if (jsonFormProviderData_.empty()) { + jsonFormProviderData_ = addJsonData; + return; + } + + for (auto && [key, value] : addJsonData.items()) { + jsonFormProviderData_[key] = value; + } +} + +/** + * @brief Obtains the imageDataMap stored in this {@code FormProviderData} object. + * @return Returns the map that contains shared image data. + */ +std::map, int32_t>> FormProviderData::GetImageDataMap() +{ + return imageDataMap_; +} + +/** + * @brief Obtains the add/remove state stored in this {@code FormProviderData} object. + * @return Returns the add/remove state of shared image data. + */ +int32_t FormProviderData::GetImageDataState() +{ + return imageDataState_; +} + +/** + * @brief Updates imageDataState in this {@code FormProviderData} object. + * @param imageDataState Indicates the imageDataState to update. + */ +void FormProviderData::SetImageDataState(int32_t imageDataState) +{ + imageDataState_ = imageDataState; +} + +/** + * @brief Updates imageDataMap in this {@code FormProviderData} object. + * @param imageDataMap Indicates the imageDataMap to update. + */ +void FormProviderData::SetImageDataMap(std::map, int32_t>> imageDataMap) +{ + imageDataMap_ = imageDataMap; +} + +/** + * Read this {@code FormProviderData} object from a Parcel. + * @param parcel the parcel + * eturn Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. + */ +bool FormProviderData::ReadFromParcel(Parcel &parcel) +{ + jsonFormProviderData_ = nlohmann::json::parse(Str16ToStr8(parcel.ReadString16())); + + imageDataState_ = parcel.ReadInt32(); + switch (imageDataState_) { + case IMAGE_DATA_STATE_ADDED: { + int32_t imageDataNum = parcel.ReadInt32(); + for (int32_t i = 0; i < imageDataNum; i++) { + MessageParcel* messageParcel = (MessageParcel*)&parcel; + sptr ashmem = messageParcel->ReadAshmem(); + if (ashmem == nullptr) { + APP_LOGE("%{public}s failed, ashmem is nullptr", __func__); + return false; + } + + int32_t len = parcel.ReadInt32(); + std::pair, int32_t> imageDataRecord = std::make_pair(ashmem, len); + imageDataMap_.emplace(Str16ToStr8(parcel.ReadString16()), imageDataRecord); + } + break; + } + case IMAGE_DATA_STATE_NO_OPERATION: + case IMAGE_DATA_STATE_REMOVED: + break; + default: + APP_LOGW("%{public}s failed, unexpected imageDataState_ %{public}d", __func__, imageDataState_); + break; + } + return true; +} + +/** + * @brief Marshals this {@code FormProviderData} object into a {@link ohos.utils.Parcel} object. + * @param parcel Indicates the {@code Parcel} object for marshalling. + * @return Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. + */ +bool FormProviderData::Marshalling(Parcel &parcel) const +{ + APP_LOGI("%{public}s called, jsonFormProviderData_: %{public}s", __func__, jsonFormProviderData_.dump().c_str()); + if (!parcel.WriteString16(Str8ToStr16(jsonFormProviderData_.empty() ? JSON_EMPTY_STRING : jsonFormProviderData_.dump()))) { + return false; + } + + parcel.WriteInt32(imageDataState_); + switch (imageDataState_) { + case IMAGE_DATA_STATE_ADDED: { + if (rawImageBytesMap_.size() == 0) { + APP_LOGE("%{public}s failed, rawImageBytesMap_ is empty", __func__); + return false; + } + parcel.WriteInt32(rawImageBytesMap_.size()); // firstly write the number of shared image to add + for (auto &entry : rawImageBytesMap_) { + if (!WriteImageDataToParcel(parcel, entry.first, entry.second)) { + APP_LOGE("%{public}s failed, the picture name is %{public}s", __func__, entry.first.c_str()); + return false; + } + parcel.WriteInt32(sizeof(entry.second)); + parcel.WriteString16(Str8ToStr16(entry.first)); + } + break; + } + case IMAGE_DATA_STATE_NO_OPERATION: + case IMAGE_DATA_STATE_REMOVED: + break; + default: + APP_LOGW("%{public}s failed, unexpected imageDataState_ %{public}d", __func__, imageDataState_); + break; + } + return true; +} + +/** + * @brief Unmarshals this {@code FormProviderData} object from a {@link ohos.utils.Parcel} object. + * @param parcel Indicates the {@code Parcel} object for unmarshalling. + * @return FormProviderData. + */ +FormProviderData* FormProviderData::Unmarshalling(Parcel &parcel) +{ + FormProviderData *formProviderData = new (std::nothrow) FormProviderData(); + if (formProviderData && !formProviderData->ReadFromParcel(parcel)) { + delete formProviderData; + formProviderData = nullptr; + } + std::string str = formProviderData->GetDataString(); + APP_LOGI("%{public}s, , provider data length: %{public}zu, provider data: %{public}s", __func__, str.length(), str.c_str()); + return formProviderData; +} + +/** + * @brief Clear imageDataMap, rawImageBytesMap_, imageDataState_ and jsonFormProviderData_. + */ +void FormProviderData::ClearData() +{ + jsonFormProviderData_.clear(); +} + +bool FormProviderData::WriteImageDataToParcel(Parcel &parcel, std::string picName, char *data) const +{ + sptr ashmem = Ashmem::CreateAshmem(picName.c_str(), sizeof(data)); + if (ashmem == nullptr) { + APP_LOGE("create shared memory fail"); + return false; + } + + bool ret = ashmem->MapReadAndWriteAshmem(); + if (!ret) { + APP_LOGE("map shared memory fail"); + return false; + } + + ret = ashmem->WriteToAshmem(data, sizeof(data), 0); + if (!ret) { + APP_LOGE("write image data to shared memory fail"); + return false; + } + + ashmem->UnmapAshmem(); + + MessageParcel* messageParcel = (MessageParcel*)&parcel; + ret = messageParcel->WriteAshmem(ashmem); + + ashmem->CloseAshmem(); // close ashmem after writeAshmem because writeAshmem will dup fd + if (!ret) { + APP_LOGE("writeAshmem fail, the picture name is %{public}s", picName.c_str()); + return false; + } + + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_base/src/form_provider_info.cpp b/interfaces/innerkits/appexecfwk_base/src/form_provider_info.cpp index 64773c9d5afdbb863b9ed57dddfaaaf6290691e6..d6b83c82a9d2ba74296b33b3f7f157e93523eec5 100644 --- a/interfaces/innerkits/appexecfwk_base/src/form_provider_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/form_provider_info.cpp @@ -20,7 +20,6 @@ namespace OHOS { namespace AppExecFwk { bool FormProviderInfo::ReadFromParcel(Parcel &parcel) { - formId_ = parcel.ReadInt64(); auto bindingData = parcel.ReadParcelable(); jsBindingData_ = *bindingData; return true; @@ -38,9 +37,6 @@ FormProviderInfo *FormProviderInfo::Unmarshalling(Parcel &parcel) bool FormProviderInfo::Marshalling(Parcel &parcel) const { - if (!parcel.WriteInt64(formId_)) { - return false; - } if (!parcel.WriteParcelable(&jsBindingData_)) { return false; } diff --git a/interfaces/innerkits/appexecfwk_base/src/hap_module_info.cpp b/interfaces/innerkits/appexecfwk_base/src/hap_module_info.cpp index e1437ccd526790d0174c229718b44d950bfcd5ef..55c0184a3c834504b35dc0e32477222d92b92107 100644 --- a/interfaces/innerkits/appexecfwk_base/src/hap_module_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/hap_module_info.cpp @@ -32,6 +32,7 @@ bool HapModuleInfo::ReadFromParcel(Parcel &parcel) iconPath = Str16ToStr8(parcel.ReadString16()); label = Str16ToStr8(parcel.ReadString16()); backgroundImg = Str16ToStr8(parcel.ReadString16()); + mainAbility = Str16ToStr8(parcel.ReadString16()); supportedModes = parcel.ReadInt32(); int32_t reqCapabilitiesSize; @@ -81,6 +82,7 @@ bool HapModuleInfo::Marshalling(Parcel &parcel) const WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(iconPath)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(label)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(backgroundImg)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(mainAbility)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, supportedModes); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, reqCapabilities.size()); for (auto &reqCapability : reqCapabilities) { diff --git a/interfaces/innerkits/appexecfwk_base/src/module_usage_record.cpp b/interfaces/innerkits/appexecfwk_base/src/module_usage_record.cpp index 369f47976ab59af6c8775c75d394d72244b0a601..3ac88d068885906ffefa12f99f71cec9158986a6 100644 --- a/interfaces/innerkits/appexecfwk_base/src/module_usage_record.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/module_usage_record.cpp @@ -98,4 +98,4 @@ bool ModuleUsageRecord::FromJsonString(const std::string &jsonString) return true; } } // namespace AppExecFwk -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp index 52b27df27bb38e05c699c197d687b38e2ac52580..95724fedf293b7eb4dee9b758635233e354c1200 100644 --- a/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp @@ -1430,4 +1430,4 @@ bool BundleMgrProxy::SendTransactCmd(IBundleMgr::Message code, MessageParcel &da } } // namespace AppExecFwk -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_core/src/bundlemgr/launcher_service.cpp b/interfaces/innerkits/appexecfwk_core/src/bundlemgr/launcher_service.cpp index 16753cb5a2898e2ca612e1e45c345175e828495d..00158f14e39c76d62955ae6ce4ed3b9143cef365 100644 --- a/interfaces/innerkits/appexecfwk_core/src/bundlemgr/launcher_service.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/bundlemgr/launcher_service.cpp @@ -22,7 +22,6 @@ namespace OHOS { namespace AppExecFwk { - LauncherService::LauncherService() { init(); @@ -104,7 +103,7 @@ bool LauncherService::GetAbilityList( icon = appInfo.iconId; int64_t installTime = 0; - BundleFlag flags; + BundleFlag flags = BundleFlag::GET_BUNDLE_DEFAULT; flags = BundleFlag::GET_BUNDLE_WITH_ABILITIES; BundleInfo bundleInfo; if (!iBundleMgr->GetBundleInfo(bundleName, flags, bundleInfo)) { @@ -162,7 +161,7 @@ bool LauncherService::GetAbilityInfo(const Want &want, const int userId, Launche icon = appInfo.iconId; int64_t installTime = 0; - BundleFlag flags; + BundleFlag flags = BundleFlag::GET_BUNDLE_DEFAULT; flags = BundleFlag::GET_BUNDLE_WITH_ABILITIES; BundleInfo bundleInfo; if (!iBundleMgr->GetBundleInfo(bundleName, flags, bundleInfo)) { diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_proxy.cpp index c414aa53299a13264100fe6f48e1df3e29ebdfc9..077a19e82ca0c0a6d5ee6bc8a3d15dbbe702aafb 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_proxy.cpp @@ -38,8 +38,11 @@ void FormHostProxy::OnAcquired(const FormJsInfo &formInfo) APP_LOGE("%{public}s, failed to write formInfo", __func__); } - error = Remote()->SendRequest(static_cast(IFormHost::Message::FORM_HOST_ON_ACQUIRED), data, reply, - option); + error = Remote()->SendRequest( + static_cast(IFormHost::Message::FORM_HOST_ON_ACQUIRED), + data, + reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); } @@ -91,8 +94,11 @@ void FormHostProxy::OnUninstall(const std::vector &formIds) APP_LOGE("%{public}s, failed to write formIds", __func__); } - error = Remote()->SendRequest(static_cast(IFormHost::Message::FORM_HOST_ON_UNINSTALL), data, reply, - option); + error = Remote()->SendRequest( + static_cast(IFormHost::Message::FORM_HOST_ON_UNINSTALL), + data, + reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); } @@ -106,7 +112,7 @@ int FormHostProxy::GetParcelableInfos(MessageParcel &reply, std::vector &par std::unique_ptr info(reply.ReadParcelable()); if (!info) { APP_LOGE("%{public}s, failed to read Parcelable infos", __func__); - return ERR_NULL_OBJECT; + return ERR_APPEXECFWK_PARCEL_ERROR; } parcelableInfos.emplace_back(*info); } diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_stub.cpp index ce0612183151a8386f79aa061bab8c4384dc133f..edbd2a7173465428992b41132145068ebed63c2c 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_stub.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_stub.cpp @@ -12,7 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + +#include "appexecfwk_errors.h" #include "app_log_wrapper.h" #include "app_scheduler_interface.h" #include "errors.h" @@ -51,7 +52,7 @@ int FormHostStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessagePar std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { APP_LOGE("%{public}s failed, local descriptor is not equal to remote", __func__); - return ERR_INVALID_STATE; + return ERR_APPEXECFWK_FORM_INVALID_PARAM; } auto itFunc = memberFuncMap_.find(code); @@ -75,7 +76,7 @@ int FormHostStub::HandleAcquired(MessageParcel &data, MessageParcel &reply) std::unique_ptr formInfo(data.ReadParcelable()); if (!formInfo) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_NULL_OBJECT; + return ERR_APPEXECFWK_PARCEL_ERROR; } OnAcquired(*formInfo); reply.WriteInt32(ERR_OK); @@ -92,7 +93,7 @@ int FormHostStub::HandleOnUpdate(MessageParcel &data, MessageParcel &reply) std::unique_ptr formInfo(data.ReadParcelable()); if (!formInfo) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_NULL_OBJECT; + return ERR_APPEXECFWK_PARCEL_ERROR; } OnUpdate(*formInfo); reply.WriteInt32(ERR_OK); @@ -114,7 +115,7 @@ int FormHostStub::HandleOnUninstall(MessageParcel &data, MessageParcel &reply) reply.WriteInt32(ERR_OK); return ERR_OK; } - return ERR_INVALID_DATA; + return ERR_APPEXECFWK_PARCEL_ERROR; } } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_proxy.cpp index 606a06c01288fa3b823e842906b86e563726df1d..ea52dc1d756f13e2840e59ccb0368c9f596a5c3d 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_proxy.cpp @@ -30,8 +30,11 @@ FormMgrProxy::FormMgrProxy(const sptr &impl) : IRemoteProxy &callerToken, -FormJsInfo &formInfo) +int FormMgrProxy::AddForm( + const int64_t formId, + const Want &want, + const sptr &callerToken, + FormJsInfo &formInfo) { MessageParcel data; if (!WriteInterfaceToken(data)) { @@ -83,11 +86,14 @@ int FormMgrProxy::DeleteForm(const int64_t formId, const sptr &ca } MessageParcel reply; MessageOption option; - int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_DELETE_FORM), data, reply, - option); + int error = Remote()->SendRequest( + static_cast(IFormMgr::Message::FORM_MGR_DELETE_FORM), + data, + reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - return error; + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; } return reply.ReadInt32(); } @@ -121,11 +127,14 @@ int FormMgrProxy::ReleaseForm(const int64_t formId, const sptr &c MessageParcel reply; MessageOption option; - int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_RELEASE_FORM), data, reply, - option); + int error = Remote()->SendRequest( + static_cast(IFormMgr::Message::FORM_MGR_RELEASE_FORM), + data, + reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - return error; + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; } return reply.ReadInt32(); } @@ -137,8 +146,10 @@ int FormMgrProxy::ReleaseForm(const int64_t formId, const sptr &c * @param FormProviderData Form binding data. * @return Returns ERR_OK on success, others on failure. */ -int FormMgrProxy::UpdateForm(const int64_t formId, const std::string &bundleName, -const FormProviderData &FormProviderData) +int FormMgrProxy::UpdateForm( + const int64_t formId, + const std::string &bundleName, + const FormProviderData &FormProviderData) { MessageParcel data; if (!WriteInterfaceToken(data)) { @@ -160,11 +171,14 @@ const FormProviderData &FormProviderData) } MessageParcel reply; MessageOption option; - int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_UPDATE_FORM), data, reply, - option); + int error = Remote()->SendRequest( + static_cast(IFormMgr::Message::FORM_MGR_UPDATE_FORM), + data, + reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - return error; + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; } return reply.ReadInt32(); } @@ -194,11 +208,14 @@ int FormMgrProxy::SetNextRefreshTime(const int64_t formId, const int64_t nextTim return ERR_APPEXECFWK_PARCEL_ERROR; } MessageOption option; - int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_SET_NEXT_REFRESH_TIME), data, - reply, option); + int error = Remote()->SendRequest( + static_cast(IFormMgr::Message::FORM_MGR_SET_NEXT_REFRESH_TIME), + data, + reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - return error; + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; } return reply.ReadInt32(); } @@ -209,8 +226,10 @@ int FormMgrProxy::SetNextRefreshTime(const int64_t formId, const int64_t nextTim * @param updateType update type. * @return Returns ERR_OK on success, others on failure. */ -int FormMgrProxy::LifecycleUpdate(const std::vector &formIds, const sptr &callerToken, -const int32_t updateType) +int FormMgrProxy::LifecycleUpdate( + const std::vector &formIds, + const sptr &callerToken, + const int32_t updateType) { MessageParcel data; MessageParcel reply; @@ -232,11 +251,14 @@ const int32_t updateType) return ERR_APPEXECFWK_PARCEL_ERROR; } MessageOption option; - int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_LIFECYCLE_UPDATE), - data, reply, option); + int error = Remote()->SendRequest( + static_cast(IFormMgr::Message::FORM_MGR_LIFECYCLE_UPDATE), + data, + reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - return error; + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; } return reply.ReadInt32(); @@ -272,11 +294,14 @@ int FormMgrProxy::RequestForm(const int64_t formId, const sptr &c MessageParcel reply; MessageOption option; - int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_REQUEST_FORM), - data, reply, option); + int error = Remote()->SendRequest( + static_cast(IFormMgr::Message::FORM_MGR_REQUEST_FORM), + data, + reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - return error; + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; } return reply.ReadInt32(); } @@ -288,8 +313,10 @@ int FormMgrProxy::RequestForm(const int64_t formId, const sptr &c * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. * @return Returns ERR_OK on success, others on failure. */ -int FormMgrProxy::NotifyWhetherVisibleForms(const std::vector &formIds, -const sptr &callerToken, const int32_t formVisibleType) +int FormMgrProxy::NotifyWhetherVisibleForms( + const std::vector &formIds, + const sptr &callerToken, + const int32_t formVisibleType) { MessageParcel data; if (!WriteInterfaceToken(data)) { @@ -314,11 +341,14 @@ const sptr &callerToken, const int32_t formVisibleType) MessageParcel reply; MessageOption option; - int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_NOTIFY_FORM_WHETHER_VISIBLE), - data, reply, option); + int error = Remote()->SendRequest( + static_cast(IFormMgr::Message::FORM_MGR_NOTIFY_FORM_WHETHER_VISIBLE), + data, + reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - return error; + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; } return reply.ReadInt32(); } @@ -347,11 +377,15 @@ int FormMgrProxy::CastTempForm(const int64_t formId, const sptr & MessageParcel reply; MessageOption option; - int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_CAST_TEMP_FORM), - data, reply, option); + int error = Remote()->SendRequest( + static_cast( + IFormMgr::Message::FORM_MGR_CAST_TEMP_FORM), + data, + reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - return error; + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; } return reply.ReadInt32(); } @@ -456,11 +490,14 @@ int FormMgrProxy::MessageEvent(const int64_t formId, const Want &want, const spt MessageParcel reply; MessageOption option; - int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_MESSAGE_EVENT), data, - reply, option); + int error = Remote()->SendRequest( + static_cast(IFormMgr::Message::FORM_MGR_MESSAGE_EVENT), + data, + reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - return error; + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; } return reply.ReadInt32(); } @@ -473,7 +510,7 @@ int FormMgrProxy::GetParcelableInfos(MessageParcel &reply, std::vector &parc std::unique_ptr info(reply.ReadParcelable()); if (!info) { APP_LOGE("%{public}s, failed to Read Parcelable infos", __func__); - return ERR_NULL_OBJECT; + return ERR_APPEXECFWK_PARCEL_ERROR; } parcelableInfos.emplace_back(*info); } @@ -509,7 +546,7 @@ int FormMgrProxy::GetStringInfo(IFormMgr::Message code, MessageParcel &data, std } if (stringInfoList.empty()) { APP_LOGI("%{public}s, No string info", __func__); - return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + return ERR_APPEXECFWK_FORM_COMMON_CODE; } for (auto &info : stringInfoList) { stringInfo += info; @@ -554,7 +591,7 @@ int FormMgrProxy::SendTransactCmd(IFormMgr::Message code, MessageParcel &data, M int32_t result = remote->SendRequest(static_cast(code), data, reply, option); if (result != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d, cmd: %{public}d", __func__, result, code); - return result; + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; } return ERR_OK; } diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_stub.cpp index ce4f6173ab07a17d413b433bb16c04ec7eeb05ce..42c11f891676683a566f69fb89c235ec015955ff 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_stub.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_stub.cpp @@ -86,7 +86,7 @@ int FormMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParc std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { APP_LOGE("%{public}s failed, local descriptor is not equal to remote", __func__); - return ERR_INVALID_STATE; + return ERR_APPEXECFWK_FORM_INVALID_PARAM; } auto itFunc = memberFuncMap_.find(code); @@ -116,7 +116,7 @@ int32_t FormMgrStub::HandleAddForm(MessageParcel &data, MessageParcel &reply) sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to RemoteObject invalidate", __func__); - return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + return ERR_APPEXECFWK_PARCEL_ERROR; } FormJsInfo formInfo; @@ -137,7 +137,7 @@ int32_t FormMgrStub::HandleDeleteForm(MessageParcel &data, MessageParcel &reply) int64_t formId = data.ReadInt64(); sptr client = data.ReadParcelable(); if (client == nullptr) { - return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + return ERR_APPEXECFWK_PARCEL_ERROR; } int32_t result = DeleteForm(formId, client); reply.WriteInt32(result); @@ -154,7 +154,7 @@ int32_t FormMgrStub::HandleReleaseForm(MessageParcel &data, MessageParcel &reply int64_t formId = data.ReadInt64(); sptr client = data.ReadParcelable(); if (client == nullptr) { - return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + return ERR_APPEXECFWK_PARCEL_ERROR; } bool delCache = data.ReadBool(); @@ -207,7 +207,7 @@ int32_t FormMgrStub::HandleLifecycleUpdate(MessageParcel &data, MessageParcel &r sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + return ERR_APPEXECFWK_PARCEL_ERROR; } int32_t updateType = data.ReadInt32(); int32_t result = LifecycleUpdate(formIds, client, updateType); @@ -229,7 +229,7 @@ int32_t FormMgrStub::HandleRequestForm(MessageParcel &data, MessageParcel &reply sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + return ERR_APPEXECFWK_PARCEL_ERROR; } std::unique_ptr want(data.ReadParcelable()); @@ -258,7 +258,7 @@ int32_t FormMgrStub::HandleNotifyWhetherVisibleForms(MessageParcel &data, Messag sptr client = data.ReadParcelable(); if (client == nullptr) { - return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + return ERR_APPEXECFWK_PARCEL_ERROR; } int32_t formVisibleType = data.ReadInt32(); @@ -278,7 +278,7 @@ int32_t FormMgrStub::HandleCastTempForm(MessageParcel &data, MessageParcel &repl int64_t formId = data.ReadInt64(); sptr client = data.ReadParcelable(); if (client == nullptr) { - return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + return ERR_APPEXECFWK_PARCEL_ERROR; } int32_t result = CastTempForm(formId, client); @@ -374,7 +374,7 @@ int32_t FormMgrStub::HandleMessageEvent(MessageParcel &data, MessageParcel &repl sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + return ERR_APPEXECFWK_PARCEL_ERROR; } int32_t result = MessageEvent(formId, *want, client); diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_proxy.cpp index 9d94e233bc9324f79c319aeef1d9ff49d0a407a2..67b77fff067433432ada5054d586cf6a57ff6e9c 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_proxy.cpp @@ -25,8 +25,10 @@ namespace AppExecFwk { * @param callerToken Caller ability token. * @return Returns ERR_OK on success, others on failure. */ -int FormProviderProxy::AcquireProviderFormInfo(const int64_t formId, const Want &want, -const sptr &callerToken) +int FormProviderProxy::AcquireProviderFormInfo( + const int64_t formId, + const Want &want, + const sptr &callerToken) { int error; MessageParcel data; @@ -51,8 +53,11 @@ const sptr &callerToken) return ERR_APPEXECFWK_PARCEL_ERROR; } - error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_ACQUIRE_PROVIDER_FORM_INFO), - data, reply, option); + error = Remote()->SendRequest( + static_cast(IFormProvider::Message::FORM_ACQUIRE_PROVIDER_FORM_INFO), + data, + reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); return error; @@ -91,8 +96,11 @@ int FormProviderProxy::NotifyFormDelete(const int64_t formId, const Want &want, return ERR_APPEXECFWK_PARCEL_ERROR; } - error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_DELETE), - data, reply, option); + error = Remote()->SendRequest( + static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_DELETE), + data, + reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); return error; @@ -106,8 +114,10 @@ int FormProviderProxy::NotifyFormDelete(const int64_t formId, const Want &want, * @param callerToken Caller ability token. * @return Returns ERR_OK on success, others on failure. */ -int FormProviderProxy::NotifyFormsDelete(const std::vector &formIds, const Want &want, -const sptr &callerToken) +int FormProviderProxy::NotifyFormsDelete( + const std::vector &formIds, + const Want &want, + const sptr &callerToken) { int error; MessageParcel data; @@ -131,8 +141,11 @@ const sptr &callerToken) return ERR_APPEXECFWK_PARCEL_ERROR; } - error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORMS_DELETE), - data, reply, option); + error = Remote()->SendRequest( + static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORMS_DELETE), + data, + reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); return error; @@ -173,8 +186,11 @@ int FormProviderProxy::NotifyFormUpdate(const int64_t formId, const Want &want, return ERR_APPEXECFWK_PARCEL_ERROR; } - error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_UPDATE), - data, reply, option); + error = Remote()->SendRequest( + static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_UPDATE), + data, + reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); return error; @@ -224,8 +240,11 @@ int FormProviderProxy::EventNotify(const std::vector &formIds, const in return ERR_APPEXECFWK_PARCEL_ERROR; } - error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_PROVIDER_EVENT_NOTIFY), - data, reply, option); + error = Remote()->SendRequest( + static_cast(IFormProvider::Message::FORM_PROVIDER_EVENT_NOTIFY), + data, + reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); return error; @@ -240,8 +259,10 @@ int FormProviderProxy::EventNotify(const std::vector &formIds, const in * @param callerToken Caller ability token. * @return Returns ERR_OK on success, others on failure. */ -int FormProviderProxy::NotifyFormCastTempForm(const int64_t formId, const Want &want, -const sptr &callerToken) +int FormProviderProxy::NotifyFormCastTempForm( + const int64_t formId, + const Want &want, + const sptr &callerToken) { int error; MessageParcel data; @@ -253,7 +274,7 @@ const sptr &callerToken) return ERR_APPEXECFWK_PARCEL_ERROR; } - if (!data. WriteInt64(formId)) { + if (!data.WriteInt64(formId)) { APP_LOGE("%{public}s, failed to write formId", __func__); return ERR_APPEXECFWK_PARCEL_ERROR; } @@ -266,8 +287,11 @@ const sptr &callerToken) return ERR_APPEXECFWK_PARCEL_ERROR; } - error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_TEMP_FORM_CAST), - data, reply, option); + error = Remote()->SendRequest( + static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_TEMP_FORM_CAST), + data, + reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); return error; @@ -283,8 +307,11 @@ const sptr &callerToken) * @param callerToken Form provider proxy object. * @return Returns ERR_OK on success, others on failure. */ -int FormProviderProxy::FireFormEvent(const int64_t formId, const std::string &message, const Want &want, -const sptr &callerToken) +int FormProviderProxy::FireFormEvent( + const int64_t formId, + const std::string &message, + const Want &want, + const sptr &callerToken) { MessageParcel data; if (!WriteInterfaceToken(data)) { @@ -309,8 +336,11 @@ const sptr &callerToken) } MessageParcel reply; MessageOption option; - int error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_DELETE), - data, reply, option); + int error = Remote()->SendRequest( + static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_DELETE), + data, + reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); return error; diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_stub.cpp index 95203261c7fe4f7510dcd25ce32564438b20e9ea..5577337a202d69592a35af0edd4a58b5a30d6ebb 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_stub.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_stub.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#include "appexecfwk_errors.h" #include "app_log_wrapper.h" #include "app_scheduler_interface.h" #include "errors.h" @@ -59,7 +59,7 @@ int FormProviderStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Messag std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { APP_LOGE("%{public}s failed, local descriptor is not equal to remote", __func__); - return ERR_INVALID_STATE; + return ERR_APPEXECFWK_FORM_INVALID_PARAM; } auto itFunc = memberFuncMap_.find(code); @@ -84,13 +84,13 @@ int FormProviderStub::HandleAcquireProviderFormInfo(MessageParcel &data, Message std::unique_ptr want(data.ReadParcelable()); if (!want) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_NULL_OBJECT; + return ERR_APPEXECFWK_PARCEL_ERROR; } sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_NULL_OBJECT; + return ERR_APPEXECFWK_PARCEL_ERROR; } int32_t result = AcquireProviderFormInfo(formId, *want, client); @@ -109,13 +109,13 @@ int FormProviderStub::HandleNotifyFormDelete(MessageParcel &data, MessageParcel std::unique_ptr want(data.ReadParcelable()); if (!want) { APP_LOGE("%{public}s fail, ReadParcelable failed", __func__); - return ERR_NULL_OBJECT; + return ERR_APPEXECFWK_PARCEL_ERROR; } sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_NULL_OBJECT; + return ERR_APPEXECFWK_PARCEL_ERROR; } int32_t result = NotifyFormDelete(formId, *want, client); @@ -136,13 +136,13 @@ int FormProviderStub::HandleNotifyFormsDelete(MessageParcel &data, MessageParcel std::unique_ptr want(data.ReadParcelable()); if (!want) { APP_LOGE("%{public}s fail, ReadParcelable failed", __func__); - return ERR_NULL_OBJECT; + return ERR_APPEXECFWK_PARCEL_ERROR; } sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_NULL_OBJECT; + return ERR_APPEXECFWK_PARCEL_ERROR; } int32_t result = NotifyFormsDelete(formIds, *want, client); @@ -165,13 +165,13 @@ int FormProviderStub::HandleNotifyFormUpdate(MessageParcel &data, MessageParcel std::unique_ptr want(data.ReadParcelable()); if (!want) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_NULL_OBJECT; + return ERR_APPEXECFWK_PARCEL_ERROR; } sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_NULL_OBJECT; + return ERR_APPEXECFWK_PARCEL_ERROR; } int32_t result = NotifyFormUpdate(formId, *want, client); @@ -195,13 +195,13 @@ int FormProviderStub::HandleEventNotify(MessageParcel &data, MessageParcel &repl std::unique_ptr want(data.ReadParcelable()); if (!want) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_NULL_OBJECT; + return ERR_APPEXECFWK_PARCEL_ERROR; } sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_NULL_OBJECT; + return ERR_APPEXECFWK_PARCEL_ERROR; } int32_t result = EventNotify(formIds, formVisibleType, *want, client); @@ -225,13 +225,13 @@ int FormProviderStub::HandleNotifyFormCastTempForm(MessageParcel &data, MessageP std::unique_ptr want(data.ReadParcelable()); if (!want) { APP_LOGE("%{public}s fail, ReadParcelable failed", __func__); - return ERR_NULL_OBJECT; + return ERR_APPEXECFWK_PARCEL_ERROR; } sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_NULL_OBJECT; + return ERR_APPEXECFWK_PARCEL_ERROR; } int32_t result = NotifyFormCastTempForm(formId, *want, client); @@ -251,13 +251,13 @@ int FormProviderStub::HandleFireFormEvent(MessageParcel &data, MessageParcel &re std::unique_ptr want(data.ReadParcelable()); if (!want) { APP_LOGE("%{public}s fail, ReadParcelable failed", __func__); - return ERR_NULL_OBJECT; + return ERR_APPEXECFWK_PARCEL_ERROR; } sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_NULL_OBJECT; + return ERR_APPEXECFWK_PARCEL_ERROR; } int32_t result = FireFormEvent(formId, message, *want, client); diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_proxy.cpp index 190f65c5351d88eb2bb2419816eda8009ecf34b2..ced74caec8cb146472a1cb80d43907ffb1c77d4e 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_proxy.cpp @@ -1,113 +1,119 @@ -/* - * 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 "appexecfwk_errors.h" -#include "form_constants.h" -#include "form_supply_proxy.h" -#include "string_ex.h" - -namespace OHOS { -namespace AppExecFwk { -/** - * @brief Send form binding data from form provider to fms. - * @param providerFormInfo Form binding data. - * @param want input data. - * @return Returns ERR_OK on success, others on failure. - */ -int FormSupplyProxy::OnAcquire(const FormProviderInfo &formInfo, const Want& want) -{ - MessageParcel data; - if (!WriteInterfaceToken(data)) { - APP_LOGE("%{public}s, failed to WriteInterfaceToken", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - if (!data.WriteParcelable(&want)) { - APP_LOGE("%{public}s, failed to write want", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - - if (want.GetIntParam(Constants::PROVIDER_FLAG, ERR_OK) == ERR_OK) { - if (!data.WriteParcelable(&formInfo)) { - APP_LOGE("%{public}s, failed to write formInfo", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - } - - MessageParcel reply; - MessageOption option; - int error = Remote()->SendRequest(static_cast(IFormSupply::Message::TRANSACTION_FORM_ACQUIRED), - data, reply, option); - if (error != ERR_OK) { - APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - } - return error; -} - - -/** - * @brief Send other event to fms. - * @param want input data. - * @return Returns ERR_OK on success, others on failure. - */ -int FormSupplyProxy::OnEventHandle(const Want& want) -{ - MessageParcel data; - - if (!WriteInterfaceToken(data)) { - APP_LOGE("%{public}s, failed to write interface token", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - - if (!data.WriteParcelable(&want)) { - APP_LOGE("%{public}s, failed to write want", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - - MessageParcel reply; - MessageOption option; - int error = Remote()->SendRequest(static_cast(IFormSupply::Message::TRANSACTION_EVENT_HANDLE), - data, reply, option); - if (error != ERR_OK) { - APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - } - return error; -} - -template -int FormSupplyProxy::GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos) -{ - int32_t infoSize = reply.ReadInt32(); - for (int32_t i = 0; i < infoSize; i++) { - std::unique_ptr info(reply.ReadParcelable()); - if (!info) { - APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_INVALID_VALUE; - } - parcelableInfos.emplace_back(*info); - } - APP_LOGI("get parcelable infos success"); - return ERR_OK; -} - -bool FormSupplyProxy::WriteInterfaceToken(MessageParcel &data) -{ - if (!data.WriteInterfaceToken(FormSupplyProxy::GetDescriptor())) { - APP_LOGE("%{public}s, failed to write interface token failed", __func__); - return false; - } - return true; -} -} // namespace AppExecFwk -} // namespace OHOS +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "appexecfwk_errors.h" +#include "form_constants.h" +#include "form_supply_proxy.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Send form binding data from form provider to fms. + * @param providerFormInfo Form binding data. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyProxy::OnAcquire(const FormProviderInfo &formInfo, const Want& want) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to WriteInterfaceToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (want.GetIntParam(Constants::PROVIDER_FLAG, ERR_OK) == ERR_OK) { + if (!data.WriteParcelable(&formInfo)) { + APP_LOGE("%{public}s, failed to write formInfo", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + } + + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest( + static_cast(IFormSupply::Message::TRANSACTION_FORM_ACQUIRED), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + } + return error; +} + + +/** + * @brief Send other event to fms. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyProxy::OnEventHandle(const Want& want) +{ + MessageParcel data; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest( + static_cast(IFormSupply::Message::TRANSACTION_EVENT_HANDLE), + data, + reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + } + return error; +} + +template +int FormSupplyProxy::GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos) +{ + int32_t infoSize = reply.ReadInt32(); + for (int32_t i = 0; i < infoSize; i++) { + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_INVALID_VALUE; + } + parcelableInfos.emplace_back(*info); + } + APP_LOGI("get parcelable infos success"); + return ERR_OK; +} + +bool FormSupplyProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(FormSupplyProxy::GetDescriptor())) { + APP_LOGE("%{public}s, failed to write interface token failed", __func__); + return false; + } + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_stub.cpp index 89061b1607048824fe3b7401a4e03a3450b72ed1..0e6ba42ce5f02d3a57456534e76d3faa869455d0 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_stub.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_stub.cpp @@ -1,124 +1,124 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "appexecfwk_errors.h" -#include "app_log_wrapper.h" -#include "form_constants.h" -#include "form_supply_stub.h" -#include "ipc_skeleton.h" -#include "ipc_types.h" -#include "iremote_object.h" - -namespace OHOS { -namespace AppExecFwk { -FormSupplyStub::FormSupplyStub() -{ - memberFuncMap_[static_cast(IFormSupply::Message::TRANSACTION_FORM_ACQUIRED)] = - &FormSupplyStub::HandleOnAcquire; - memberFuncMap_[static_cast(IFormSupply::Message::TRANSACTION_EVENT_HANDLE)] = - &FormSupplyStub::HandleOnEventHandle; -} - -FormSupplyStub::~FormSupplyStub() -{ - memberFuncMap_.clear(); -} -/** - * @brief handle remote request. - * @param data input param. - * @param reply output param. - * @param option message option. - * @return Returns ERR_OK on success, others on failure. - */ -int FormSupplyStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) -{ - APP_LOGI("FormSupplyStub::OnReceived, code = %{public}d, flags= %{public}d.", code, option.GetFlags()); - std::u16string descriptor = FormSupplyStub::GetDescriptor(); - std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { - APP_LOGE("%{public}s failed, local descriptor is not equal to remote", __func__); - return ERR_INVALID_STATE; - } - - auto itFunc = memberFuncMap_.find(code); - if (itFunc != memberFuncMap_.end()) { - auto memberFunc = itFunc->second; - if (memberFunc != nullptr) { - return (this->*memberFunc)(data, reply); - } - } - - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); -} -/** - * @brief handle OnAcquire message. - * @param data input param. - * @param reply output param. - * @return Returns ERR_OK on success, others on failure. - */ -int FormSupplyStub::HandleOnAcquire(MessageParcel &data, MessageParcel &reply) -{ - std::unique_ptr want(data.ReadParcelable()); - if (!want) { - APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - reply.WriteInt32(ERR_INVALID_VALUE); - return ERR_INVALID_VALUE; - } - - int errCode = ERR_OK; - do { - errCode = want->GetIntParam(Constants::PROVIDER_FLAG, ERR_OK); - if (errCode != ERR_OK) { - APP_LOGE("%{public}s, provider error", __func__); - break; - } - std::unique_ptr formInfo(data.ReadParcelable()); - if (formInfo == nullptr) { - APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - errCode = ERR_INVALID_VALUE; - break; - } - int32_t result = OnAcquire(*formInfo, *want); - reply.WriteInt32(result); - return result; - } while (true); - - FormProviderInfo formProviderInfo; - want->SetParam(Constants::PROVIDER_FLAG, errCode); - OnAcquire(formProviderInfo, *want); - reply.WriteInt32(errCode); - return errCode; -} -/** - * @brief handle OnEventHandle message. - * @param data input param. - * @param reply output param. - * @return Returns ERR_OK on success, others on failure. - */ -int FormSupplyStub::HandleOnEventHandle(MessageParcel &data, MessageParcel &reply) -{ - std::unique_ptr want(data.ReadParcelable()); - if (!want) { - APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - reply.WriteInt32(ERR_INVALID_VALUE); - return ERR_INVALID_VALUE; - } - - int32_t result = OnEventHandle(*want); - reply.WriteInt32(result); - return result; -} -} // namespace AppExecFwk +/* + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_supply_stub.h" +#include "ipc_skeleton.h" +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +FormSupplyStub::FormSupplyStub() +{ + memberFuncMap_[static_cast(IFormSupply::Message::TRANSACTION_FORM_ACQUIRED)] = + &FormSupplyStub::HandleOnAcquire; + memberFuncMap_[static_cast(IFormSupply::Message::TRANSACTION_EVENT_HANDLE)] = + &FormSupplyStub::HandleOnEventHandle; +} + +FormSupplyStub::~FormSupplyStub() +{ + memberFuncMap_.clear(); +} +/** + * @brief handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + APP_LOGI("FormSupplyStub::OnReceived, code = %{public}d, flags= %{public}d.", code, option.GetFlags()); + std::u16string descriptor = FormSupplyStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGE("%{public}s failed, local descriptor is not equal to remote", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data, reply); + } + } + + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} +/** + * @brief handle OnAcquire message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyStub::HandleOnAcquire(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + reply.WriteInt32(ERR_APPEXECFWK_PARCEL_ERROR); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int errCode = ERR_OK; + do { + errCode = want->GetIntParam(Constants::PROVIDER_FLAG, ERR_OK); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s, provider error", __func__); + break; + } + std::unique_ptr formInfo(data.ReadParcelable()); + if (formInfo == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + errCode = ERR_APPEXECFWK_PARCEL_ERROR; + break; + } + int32_t result = OnAcquire(*formInfo, *want); + reply.WriteInt32(result); + return result; + } while (true); + + FormProviderInfo formProviderInfo; + want->SetParam(Constants::PROVIDER_FLAG, errCode); + OnAcquire(formProviderInfo, *want); + reply.WriteInt32(errCode); + return errCode; +} +/** + * @brief handle OnEventHandle message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyStub::HandleOnEventHandle(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + reply.WriteInt32(ERR_APPEXECFWK_PARCEL_ERROR); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int32_t result = OnEventHandle(*want); + reply.WriteInt32(result); + return result; +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_proxy.cpp index e966e7b0956e7bbb059b426619d100662773f100..eb433ebd4e68dce02e0bff470c13de67cb007f72 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_proxy.cpp @@ -30,7 +30,8 @@ namespace AppExecFwk { void ProviderConnectProxy::OnAbilityConnectDone( const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) { - APP_LOGD("%{public}s, abilityName:%{public}s,resultCode:%{public}d", __func__, element.GetAbilityName().c_str(), resultCode); + APP_LOGD("%{public}s, abilityName:%{public}s,resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), resultCode); int error; MessageParcel data; MessageParcel reply; diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_stub.cpp index 54323fdac89f43458456d34608c438637a6034c5..cee0890826f015e1247914e34c59aa5f6773395a 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_stub.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_stub.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ - +#include "appexecfwk_errors.h" #include "app_log_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" @@ -44,7 +44,7 @@ int ProviderConnectStub::OnRemoteRequest( case IAbilityConnection::ON_ABILITY_CONNECT_DONE: { if (element == nullptr) { APP_LOGE("%{public}s failed, callback stub receive element is nullptr", __func__); - return ERR_INVALID_VALUE; + return ERR_APPEXECFWK_PARCEL_ERROR; } auto remoteObject = data.ReadParcelable(); auto resultCode = data.ReadInt32(); @@ -55,7 +55,7 @@ int ProviderConnectStub::OnRemoteRequest( case IAbilityConnection::ON_ABILITY_DISCONNECT_DONE: { if (element == nullptr) { APP_LOGE("%{public}s failed, callback stub receive element is nullptr", __func__); - return ERR_INVALID_VALUE; + return ERR_APPEXECFWK_PARCEL_ERROR; } auto resultCode = data.ReadInt32(); OnAbilityDisconnectDone(*element, resultCode); diff --git a/interfaces/innerkits/fmskit/BUILD.gn b/interfaces/innerkits/fmskit/BUILD.gn index ced9a7112961085ee2fa9419940e206607121b25..5b10fb34c816c8381aea8274db6d70c356cb0464 100644 --- a/interfaces/innerkits/fmskit/BUILD.gn +++ b/interfaces/innerkits/fmskit/BUILD.gn @@ -36,6 +36,7 @@ ohos_shared_library("fmskit_native") { configs = [ ":fmskit_config" ] public_configs = [ ":fmskit_public_config" ] sources = [ + "$SUBSYSTEM_DIR/interfaces/innerkits/fmskit/native/src/form_errors.cpp", "$SUBSYSTEM_DIR/interfaces/innerkits/fmskit/native/src/form_host_client.cpp", "$SUBSYSTEM_DIR/interfaces/innerkits/fmskit/native/src/form_mgr.cpp", ] diff --git a/interfaces/innerkits/fmskit/native/include/form_errors.h b/interfaces/innerkits/fmskit/native/include/form_errors.h new file mode 100644 index 0000000000000000000000000000000000000000..1510f4670de36c19256f83fd8ffe2926ffd5cfbe --- /dev/null +++ b/interfaces/innerkits/fmskit/native/include/form_errors.h @@ -0,0 +1,55 @@ +/* + * 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_FORM_ERRORS_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_ERRORS_H + +#include +#include + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormErrors + * FormErrors is used to access form error message. + */ +class FormErrors final : public DelayedRefSingleton { + DECLARE_DELAYED_REF_SINGLETON(FormErrors) +public: + DISALLOW_COPY_AND_MOVE(FormErrors); + + /** + * @brief Get the error message content. + * + * @param errCode Error code. + * @return Message content. + */ + std::string GetErrorMessage(int errCode); + +private: + /** + * @brief Init error message map object. + * + */ + void InitErrorMessageMap(); + +private: + std::map errorMessageMap_; + + +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_ERRORS_H \ No newline at end of file diff --git a/interfaces/innerkits/fmskit/native/include/form_mgr.h b/interfaces/innerkits/fmskit/native/include/form_mgr.h index 4eaca5087e5ccc0b738caa37b40ca7ed4461bae3..ec455552e483cf19ee8f2772804020bc57c676fb 100644 --- a/interfaces/innerkits/fmskit/native/include/form_mgr.h +++ b/interfaces/innerkits/fmskit/native/include/form_mgr.h @@ -51,7 +51,7 @@ public: * @param formInfo Form info. * @return Returns ERR_OK on success, others on failure. */ - virtual int AddForm(const int64_t formId, const Want &want, const sptr &callerToken, + int AddForm(const int64_t formId, const Want &want, const sptr &callerToken, FormJsInfo &formInfo); /** @@ -197,6 +197,13 @@ public: */ bool CheckIsDeathCallbackRegistered(const std::shared_ptr &formDeathCallback); + /** + * @brief Get the error message content. + * + * @param errCode Error code. + * @return Message content. + */ + std::string GetErrorMessage(int errCode); private: /** * @brief Connect form manager service. diff --git a/interfaces/innerkits/fmskit/native/src/form_errors.cpp b/interfaces/innerkits/fmskit/native/src/form_errors.cpp new file mode 100644 index 0000000000000000000000000000000000000000..25861a6a41d297157709e5f3789d18d56a0f3114 --- /dev/null +++ b/interfaces/innerkits/fmskit/native/src/form_errors.cpp @@ -0,0 +1,139 @@ +/* + * 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 "appexecfwk_errors.h" +#include "form_errors.h" + +namespace OHOS { +namespace AppExecFwk { +FormErrors::FormErrors() +{ + InitErrorMessageMap(); +} +FormErrors::~FormErrors() +{ +} + +/** + * @brief Get the error message content. + * + * @param errCode Error code. + * @return Message content. + */ +std::string FormErrors::GetErrorMessage(int errCode) +{ + if(errorMessageMap_.find(errCode) != errorMessageMap_.end()) { + return errorMessageMap_[errCode]; + } + else { + return errorMessageMap_[ERR_APPEXECFWK_FORM_COMMON_CODE]; + } +} + +/** + * @brief Init error message map object. + * + */ +void FormErrors::InitErrorMessageMap() +{ + errorMessageMap_ = { // error + message + { + ERR_APPEXECFWK_FORM_COMMON_CODE, "some internal server error occurs.", + }, + { + ERR_APPEXECFWK_FORM_PERMISSION_DENY, + "check permission deny, need to request ohos.permission.REQUIRE_FORM.", + }, + { + ERR_APPEXECFWK_FORM_GET_INFO_FAILED, "can't get form info by the formName.", + }, + { + ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED, "the requested bundle name does not exist.", + }, + { + ERR_APPEXECFWK_FORM_INVALID_PARAM, "invalid params received on operating form.", + }, + { + ERR_APPEXECFWK_FORM_CFG_NOT_MATCH_ID, "the form id and form config are not matched.", + }, + { + ERR_APPEXECFWK_FORM_NOT_EXIST_ID, "the requested form id is not existed on fms.", + }, + { + ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED, "fms bind provider failed.", + }, + { + ERR_APPEXECFWK_FORM_MAX_SYSTEM_FORMS, "exceed max forms in system, current limit is 512.", + }, + { + ERR_APPEXECFWK_FORM_EXCEED_INSTANCES_PER_FORM, "exceed max instances per form, limit is 32.", + }, + { + ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, + "the form to be operated is not self-owned or has been deleted already.", + }, + { + ERR_APPEXECFWK_FORM_PROVIDER_DEL_FAIL, "fms notify provider to delete failed.", + }, + { + ERR_APPEXECFWK_FORM_MAX_FORMS_PER_CLIENT, "exceed max forms per client, limit is 256.", + }, + { + ERR_APPEXECFWK_FORM_MAX_SYSTEM_TEMP_FORMS, "exceed max temp forms in system, limit is 256.", + }, + { + ERR_APPEXECFWK_FORM_NO_SUCH_MODULE, "the module not exist in the bundle.", + }, + { + ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY, "the ability not exist in the module.", + }, + { + ERR_APPEXECFWK_FORM_NO_SUCH_DIMENSION, "the dimension not exist in the form.", + }, + { + ERR_APPEXECFWK_FORM_FA_NOT_INSTALLED, "the ability not installed,need install first.", + }, + { + ERR_APPEXECFWK_FORM_MAX_REQUEST, "too many request,try again later.", + }, + { + ERR_APPEXECFWK_FORM_MAX_REFRESH, "already refresh 50 times.", + }, + { + ERR_APPEXECFWK_FORM_GET_BMS_FAILED, "get bms rpc failed.", + }, + { + ERR_APPEXECFWK_FORM_GET_FMS_FAILED, "get fms rpc failed.", + }, + { + ERR_APPEXECFWK_FORM_SEND_FMS_MSG, "send request to fms failed.", + }, + { + ERR_APPEXECFWK_FORM_FORM_DUPLICATE_ADDED, "form do not support acquire same id twice.", + }, + { + ERR_APPEXECFWK_FORM_IN_RECOVER, "form is in recover status, can't do action on form.", + }, + { + ERR_APPEXECFWK_FORM_GET_SYSMGR_FAILED, "get system manager failed.", + }, + { + ERR_APPEXECFWK_PARCEL_ERROR, "read parcelable info failed.", + }, + }; +} + +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/fmskit/native/src/form_host_client.cpp b/interfaces/innerkits/fmskit/native/src/form_host_client.cpp index 2187e886b6eceb72216f5914b733b329266eacdb..f3a48d6e760e8b293723ddb2df18913c5def0891 100755 --- a/interfaces/innerkits/fmskit/native/src/form_host_client.cpp +++ b/interfaces/innerkits/fmskit/native/src/form_host_client.cpp @@ -105,7 +105,7 @@ void FormHostClient::RemoveForm(std::shared_ptr formCallb { std::lock_guard lock(lockMutex_); int64_t key = FindKeyByCallback(formCallback); - if(key == -1) { + if (key == -1) { APP_LOGE("%{public}s, failed to find callback.", __func__); return; } @@ -167,7 +167,8 @@ void FormHostClient::OnAcquired(const FormJsInfo &formJsInfo) APP_LOGE("%{public}s error, can't find target callback. formId: %{public}" PRId64 ".", __func__, formId); return; } - APP_LOGI("%{public}s, formId: %{public}" PRId64 ", data: %{public}s", __func__, formId, formJsInfo.formData.c_str()); + APP_LOGI("%{public}s, formId: %{public}" PRId64 ", jspath: %{public}s, data: %{public}s", __func__, formId, + formJsInfo.jsFormCodePath.c_str(), formJsInfo.formData.c_str()); targetCallback->ProcessFormUpdate(formJsInfo); } @@ -206,8 +207,8 @@ void FormHostClient::OnUninstall(const std::vector &formIds) APP_LOGE("%{public}s error, formIds is empty.", __func__); return; } - for(auto &formId : formIds) { - if (formId < 0) { + for (auto &formId : formIds) { + if (formId < 0) { APP_LOGE("%{public}s error, the passed form id can't be negative.", __func__); continue; } diff --git a/interfaces/innerkits/fmskit/native/src/form_mgr.cpp b/interfaces/innerkits/fmskit/native/src/form_mgr.cpp index 6531c5afe7dec6ecf8a7e44ecf98b5aad293aabc..b728408bb40fcda1279f829295e011411675cc1c 100644 --- a/interfaces/innerkits/fmskit/native/src/form_mgr.cpp +++ b/interfaces/innerkits/fmskit/native/src/form_mgr.cpp @@ -16,6 +16,7 @@ #include #include "appexecfwk_errors.h" #include "app_log_wrapper.h" +#include "form_errors.h" #include "form_mgr.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" @@ -43,8 +44,11 @@ FormMgr::~FormMgr() * @param formInfo Form info. * @return Returns ERR_OK on success, others on failure. */ -int FormMgr::AddForm(const int64_t formId, const Want &want, const sptr &callerToken, -FormJsInfo &formInfo) +int FormMgr::AddForm( + const int64_t formId, + const Want &want, + const sptr &callerToken, + FormJsInfo &formInfo) { APP_LOGI("%{public}s called.", __func__); @@ -142,8 +146,10 @@ int FormMgr::RequestForm(const int64_t formId, const sptr &caller * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. * @return Returns ERR_OK on success, others on failure. */ -int FormMgr::NotifyWhetherVisibleForms(const std::vector &formIds, const sptr &callerToken, -const int32_t formVisibleType) +int FormMgr::NotifyWhetherVisibleForms( + const std::vector &formIds, + const sptr &callerToken, + const int32_t formVisibleType) { int errCode = Connect(); if (errCode != ERR_OK) { @@ -256,8 +262,10 @@ int FormMgr::SetNextRefreshTime(const int64_t formId, const int64_t nextTime) * @param updateType Next refresh time. * @return Returns ERR_OK on success, others on failure. */ -int FormMgr::LifecycleUpdate(const std::vector &formIds, const sptr &callerToken, -const int32_t updateType) +int FormMgr::LifecycleUpdate( + const std::vector &formIds, + const sptr &callerToken, + const int32_t updateType) { int errCode = Connect(); if (errCode != ERR_OK) { @@ -290,6 +298,17 @@ void FormMgr::SetRecoverStatus(int recoverStatus) recoverStatus_ = recoverStatus; } +/** + * @brief Get the error message content. + * + * @param errCode Error code. + * @return Message content. + */ +std::string FormMgr::GetErrorMessage(int errCode) +{ + return FormErrors::GetInstance().GetErrorMessage(errCode); +} + /** * @brief Register death callback. * @@ -438,11 +457,11 @@ ErrCode FormMgr::Connect() deathRecipient_ = sptr(new FormMgrDeathRecipient()); if (deathRecipient_ == nullptr) { APP_LOGE("%{public}s :Failed to create FormMgrDeathRecipient!", __func__); - return ERR_NO_MEMORY; + return ERR_APPEXECFWK_FORM_COMMON_CODE; } if ((remoteObject->IsProxyObject()) && (!remoteObject->AddDeathRecipient(deathRecipient_))) { APP_LOGE("%{public}s :Add death recipient to FormMgrService failed.", __func__); - return ERR_APPEXECFWK_FORM_ADD_DEATH_RECIPIENT_FAILED; + return ERR_APPEXECFWK_FORM_COMMON_CODE; } remoteProxy_ = iface_cast(remoteObject); diff --git a/interfaces/innerkits/libeventhandler/include/event_handler.h b/interfaces/innerkits/libeventhandler/include/event_handler.h index 013c5067ef5716d697a215ac1e5d9a2f20cf2397..d232a1a195082090f420507ca7dfe0c7000a4aa6 100644 --- a/interfaces/innerkits/libeventhandler/include/event_handler.h +++ b/interfaces/innerkits/libeventhandler/include/event_handler.h @@ -27,7 +27,7 @@ enum class EventType { TIMING_EVENT = 2, }; -template +template class ThreadLocalData; class EventHandler : public std::enable_shared_from_this { @@ -154,7 +154,7 @@ public: * @param delayTime Process the event after 'delayTime' milliseconds. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendEvent(uint32_t innerEventId, const std::shared_ptr &object, int64_t delayTime = 0) { return SendEvent(InnerEvent::Get(innerEventId, object), delayTime); @@ -168,7 +168,7 @@ public: * @param delayTime Process the event after 'delayTime' milliseconds. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendEvent(uint32_t innerEventId, const std::weak_ptr &object, int64_t delayTime = 0) { return SendEvent(InnerEvent::Get(innerEventId, object), delayTime); @@ -182,7 +182,7 @@ public: * @param delayTime Process the event after 'delayTime' milliseconds. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendEvent(uint32_t innerEventId, std::unique_ptr &object, int64_t delayTime = 0) { return SendEvent(InnerEvent::Get(innerEventId, object), delayTime); @@ -196,7 +196,7 @@ public: * @param delayTime Process the event after 'delayTime' milliseconds. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendEvent(uint32_t innerEventId, std::unique_ptr &&object, int64_t delayTime = 0) { return SendEvent(InnerEvent::Get(innerEventId, object), delayTime); @@ -243,7 +243,7 @@ public: * @param object Shared pointer of object. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendImmediateEvent(uint32_t innerEventId, const std::shared_ptr &object) { return SendImmediateEvent(InnerEvent::Get(innerEventId, object)); @@ -256,7 +256,7 @@ public: * @param object Weak pointer of object. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendImmediateEvent(uint32_t innerEventId, const std::weak_ptr &object) { return SendImmediateEvent(InnerEvent::Get(innerEventId, object)); @@ -269,7 +269,7 @@ public: * @param object Unique pointer of object. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendImmediateEvent(uint32_t innerEventId, std::unique_ptr &object) { return SendImmediateEvent(InnerEvent::Get(innerEventId, object)); @@ -282,7 +282,7 @@ public: * @param object Unique pointer of object. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendImmediateEvent(uint32_t innerEventId, std::unique_ptr &&object) { return SendImmediateEvent(InnerEvent::Get(innerEventId, object)); @@ -333,7 +333,7 @@ public: * @param delayTime Process the event after 'delayTime' milliseconds. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendHighPriorityEvent(uint32_t innerEventId, const std::shared_ptr &object, int64_t delayTime = 0) { return SendHighPriorityEvent(InnerEvent::Get(innerEventId, object), delayTime); @@ -347,7 +347,7 @@ public: * @param delayTime Process the event after 'delayTime' milliseconds. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendHighPriorityEvent(uint32_t innerEventId, const std::weak_ptr &object, int64_t delayTime = 0) { return SendHighPriorityEvent(InnerEvent::Get(innerEventId, object), delayTime); @@ -361,7 +361,7 @@ public: * @param delayTime Process the event after 'delayTime' milliseconds. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendHighPriorityEvent(uint32_t innerEventId, std::unique_ptr &object, int64_t delayTime = 0) { return SendHighPriorityEvent(InnerEvent::Get(innerEventId, object), delayTime); @@ -375,7 +375,7 @@ public: * @param delayTime Process the event after 'delayTime' milliseconds. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendHighPriorityEvent(uint32_t innerEventId, std::unique_ptr &&object, int64_t delayTime = 0) { return SendHighPriorityEvent(InnerEvent::Get(innerEventId, object), delayTime); @@ -539,7 +539,7 @@ public: * @param priority Priority of the event queue for this event, IDLE is not permitted for sync event. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendSyncEvent( uint32_t innerEventId, const std::shared_ptr &object, Priority priority = Priority::LOW) { @@ -554,7 +554,7 @@ public: * @param priority Priority of the event queue for this event, IDLE is not permitted for sync event. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendSyncEvent(uint32_t innerEventId, const std::weak_ptr &object, Priority priority = Priority::LOW) { return SendSyncEvent(InnerEvent::Get(innerEventId, object), priority); @@ -568,7 +568,7 @@ public: * @param priority Priority of the event queue for this event, IDLE is not permitted for sync event. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendSyncEvent(uint32_t innerEventId, std::unique_ptr &object, Priority priority = Priority::LOW) { return SendSyncEvent(InnerEvent::Get(innerEventId, object), priority); @@ -582,7 +582,7 @@ public: * @param priority Priority of the event queue for this event, IDLE is not permitted for sync event. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendSyncEvent(uint32_t innerEventId, std::unique_ptr &&object, Priority priority = Priority::LOW) { return SendSyncEvent(InnerEvent::Get(innerEventId, object), priority); @@ -686,7 +686,7 @@ public: * @param priority Priority of the event queue for this event * @return Returns true if event has been sent successfully. */ - template + template inline bool SendTimingEvent( uint32_t innerEventId, const std::shared_ptr &object, int64_t taskTime, Priority priority = Priority::LOW) { @@ -702,7 +702,7 @@ public: * @param priority Priority of the event queue for this event * @return Returns true if event has been sent successfully. */ - template + template inline bool SendTimingEvent( uint32_t innerEventId, const std::weak_ptr &object, int64_t taskTime, Priority priority = Priority::LOW) { @@ -718,7 +718,7 @@ public: * @param priority Priority of the event queue for this event * @return Returns true if event has been sent successfully. */ - template + template inline bool SendTimingEvent( uint32_t innerEventId, std::unique_ptr &object, int64_t taskTime, Priority priority = Priority::LOW) { @@ -734,7 +734,7 @@ public: * @param priority Priority of the event queue for this event * @return Returns true if event has been sent successfully. */ - template + template inline bool SendTimingEvent( uint32_t innerEventId, std::unique_ptr &&object, int64_t taskTime, Priority priority = Priority::LOW) { diff --git a/interfaces/innerkits/libeventhandler/include/inner_event.h b/interfaces/innerkits/libeventhandler/include/inner_event.h index ca13bf30a7e703c46aed1163871819f8326e3ad8..0cd2e3f1aea2d3b2617c5ec31060fa9465bcaa8b 100644 --- a/interfaces/innerkits/libeventhandler/include/inner_event.h +++ b/interfaces/innerkits/libeventhandler/include/inner_event.h @@ -67,7 +67,7 @@ public: * @param param Basic parameter of the event, default is 0. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, const std::shared_ptr &object, int64_t param = 0) { auto event = Get(innerEventId, param); @@ -83,7 +83,7 @@ public: * @param param Basic parameter of the event, default is 0. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, const std::weak_ptr &object, int64_t param = 0) { auto event = Get(innerEventId, param); @@ -99,7 +99,7 @@ public: * @param param Basic parameter of the event, default is 0. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, std::unique_ptr &&object, int64_t param = 0) { auto event = Get(innerEventId, param); @@ -115,7 +115,7 @@ public: * @param param Basic parameter of the event, default is 0. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, std::unique_ptr &object, int64_t param = 0) { auto event = Get(innerEventId, param); @@ -131,7 +131,7 @@ public: * @param object Shared pointer of the object. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, int64_t param, const std::shared_ptr &object) { auto event = Get(innerEventId, param); @@ -147,7 +147,7 @@ public: * @param object Weak pointer of the object. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, int64_t param, const std::weak_ptr &object) { auto event = Get(innerEventId, param); @@ -163,7 +163,7 @@ public: * @param object Unique pointer of the object. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, int64_t param, std::unique_ptr &&object) { auto event = Get(innerEventId, param); @@ -179,7 +179,7 @@ public: * @param object Unique pointer of the object. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, int64_t param, std::unique_ptr &object) { auto event = Get(innerEventId, param); @@ -290,7 +290,7 @@ public: * * @return Returns shared pointer of saved object. */ - template + template std::shared_ptr GetSharedObject() const { const std::shared_ptr &sharedObject = *reinterpret_cast *>(smartPtr_); @@ -312,7 +312,7 @@ public: * * @return Returns unique pointer of saved object. */ - template + template std::unique_ptr GetUniqueObject() const { std::unique_ptr &object = *reinterpret_cast *>(smartPtr_); @@ -329,7 +329,7 @@ public: * * @return Returns unique pointer of saved object. */ - template + template std::unique_ptr GetUniqueObject() const { std::unique_ptr &object = *reinterpret_cast *>(smartPtr_); @@ -401,7 +401,7 @@ private: static void WarnSmartPtrCastMismatch(); - template + template static void ReleaseSmartPtr(void *smartPtr) { if (smartPtr != nullptr) { @@ -409,7 +409,7 @@ private: } } - template + template inline void SaveSharedPtr(const T &object) { smartPtr_ = new T(object); @@ -417,7 +417,7 @@ private: smartPtrTypeId_ = CalculateSmartPtrTypeId(object); } - template + template inline void SaveUniquePtr(T &object) { smartPtr_ = new T(std::move(object)); @@ -430,7 +430,7 @@ private: */ #ifdef __GXX_RTTI // If RTTI(Run-Time Type Info) is enabled, use hash code of type info. - template + template static inline size_t CalculateSmartPtrTypeId(const T &) { return typeid(T).hash_code(); @@ -442,25 +442,25 @@ private: static const size_t UNIQUE_PTR_TYPE = 0x30000000; static const size_t UNIQUE_PTR_ARRAY_TYPE = 0x40000000; - template + template static inline size_t CalculateSmartPtrTypeId(const std::shared_ptr &) { return (sizeof(T) | SHARED_PTR_TYPE); } - template + template static inline size_t CalculateSmartPtrTypeId(const std::weak_ptr &) { return (sizeof(T) | WEAK_PTR_TYPE); } - template + template static inline size_t CalculateSmartPtrTypeId(const std::unique_ptr &) { return (sizeof(T) | (sizeof(D) - 1) | UNIQUE_PTR_TYPE); } - template + template static inline size_t CalculateSmartPtrTypeId(const std::unique_ptr &) { return (sizeof(T) | (sizeof(D) - 1) | UNIQUE_PTR_ARRAY_TYPE); diff --git a/interfaces/innerkits/task_dispatcher/include/dispatcher/base_task_dispatcher.h b/interfaces/innerkits/task_dispatcher/include/dispatcher/base_task_dispatcher.h index 106b6619b9654307381ed05ca1fcb3b97d27c248..96326fb7fd18ef0d41168f8c3cec626a7283069b 100644 --- a/interfaces/innerkits/task_dispatcher/include/dispatcher/base_task_dispatcher.h +++ b/interfaces/innerkits/task_dispatcher/include/dispatcher/base_task_dispatcher.h @@ -28,7 +28,7 @@ namespace OHOS { namespace AppExecFwk { /** - *Base implementation for interface of TaskDispatcher. + * Base implementation for interface of TaskDispatcher. */ class BaseTaskDispatcher : public TaskDispatcher { diff --git a/interfaces/innerkits/task_dispatcher/include/dispatcher/serial_task_dispatcher.h b/interfaces/innerkits/task_dispatcher/include/dispatcher/serial_task_dispatcher.h index 9388e9ce0c9619f08469b99a27133732320d5f23..af3847c8caf7c64d45ccae9f15ff976ef4a45870 100644 --- a/interfaces/innerkits/task_dispatcher/include/dispatcher/serial_task_dispatcher.h +++ b/interfaces/innerkits/task_dispatcher/include/dispatcher/serial_task_dispatcher.h @@ -35,51 +35,7 @@ namespace AppExecFwk { * Dispatcher for serial thread model. */ class SerialTaskDispatcher : public BaseTaskDispatcher, public std::enable_shared_from_this { -private: - static std::string DISPATCHER_TAG; - static std::string ASYNC_DISPATCHER_TAG; - static std::string SYNC_DISPATCHER_TAG; - static std::string DELAY_DISPATCHER_TAG; - - std::atomic running_; - ConcurrentQueue> workingTasks_; - - std::shared_ptr executor_; - std::mutex mutex_; - -private: - ErrCode OnNewTaskIn(std::shared_ptr &task); - - ErrCode Prepare(std::shared_ptr &task); - - /** - * Callback for task when finish. - * - */ - void OnTaskDone(); - - bool Schedule(); - - /** - * Do task in turn, until the task queue is empty. - * - * @param isExhausted is an inaccurate judge indicate that the workingTasks is empty. If true, do double-check. - * @return true if has work remain to do else false. - * - */ - bool DoNext(bool isExhausted); - - void DoWork(std::shared_ptr &task); - public: - /** - * Constructs a serial TaskDispatcher using priority. - * - * @param dispatcherName is the identity for dispatcher. It's for debug purpose. - * @param priority is the priority for tasks dispatched by this Dispatcher. - * @param executor contains thread pool(s) for executing tasks concurrently. - * - */ SerialTaskDispatcher( const std::string &dispatcherName, const TaskPriority priority, const std::shared_ptr &executor); ~SerialTaskDispatcher(){}; @@ -127,6 +83,40 @@ public: * */ std::shared_ptr DelayDispatch(const std::shared_ptr &runnable, long delayMs); +private: + ErrCode OnNewTaskIn(std::shared_ptr &task); + + ErrCode Prepare(std::shared_ptr &task); + + /** + * Callback for task when finish. + * + */ + void OnTaskDone(); + + bool Schedule(); + + /** + * Do task in turn, until the task queue is empty. + * + * @param isExhausted is an inaccurate judge indicate that the workingTasks is empty. If true, do double-check. + * @return true if has work remain to do else false. + * + */ + bool DoNext(bool isExhausted); + + void DoWork(std::shared_ptr &task); +private: + static std::string DISPATCHER_TAG; + static std::string ASYNC_DISPATCHER_TAG; + static std::string SYNC_DISPATCHER_TAG; + static std::string DELAY_DISPATCHER_TAG; + + std::atomic running_; + ConcurrentQueue> workingTasks_; + + std::shared_ptr executor_; + std::mutex mutex_; }; } // namespace AppExecFwk diff --git a/interfaces/innerkits/task_dispatcher/include/task/task.h b/interfaces/innerkits/task_dispatcher/include/task/task.h index 82a5c0d4a8877941b57c8d13ee87dfd5c64d604f..4d58c0e9b44d70e53b7ac99a3d429d86a0d111cc 100644 --- a/interfaces/innerkits/task_dispatcher/include/task/task.h +++ b/interfaces/innerkits/task_dispatcher/include/task/task.h @@ -37,52 +37,52 @@ public: virtual ~Task(); /** - *@brief invoke the function to execute the task + * @brief invoke the function to execute the task */ virtual void Run(); /** - * @brief Gets the priority. - * @return The priority. + * @brief Gets the priority. + * @return The priority. */ TaskPriority GetPriority() const; /** - * @brief Sets the sequence. - * @param sequence The sequence + * @brief Sets the sequence. + * @param sequence The sequence */ void SetSequence(long sequence); /** - *@brief Gets the sequence. - *@return The sequence. + * @brief Gets the sequence. + * @return The sequence. */ long GetSequence() const; /** - *@brief Revoke this task if hasn't run. - *@return true if set revoked or already revoked. False if the task has start executing. + * @brief Revoke this task if hasn't run. + * @return true if set revoked or already revoked. False if the task has start executing. */ bool Revoke() override; /** - *@brief Adds a task listener. - *@param listener The listener + * @brief Adds a task listener. + * @param listener The listener */ void AddTaskListener(const std::shared_ptr &listener); /** - *@brief Called when task is about to run. + * @brief Called when task is about to run. */ void BeforeTaskExecute(); /** - *@brief Called when task is done. + * @brief Called when task is done. */ void AfterTaskExecute(); /** - *@brief Called when task is canceled. + * @brief Called when task is canceled. */ void OnTaskCanceled(); @@ -102,9 +102,9 @@ private: }; /** - *@brief Return true if not executed or revoked, and if not executed or revoked, ensure |EXECUTED| to be set. - *@param - - *@return bool + * @brief Return true if not executed or revoked, and if not executed or revoked, ensure |EXECUTED| to be set. + * @param - + * @return bool */ bool EnterExecute(); diff --git a/interfaces/innerkits/task_dispatcher/include/task/task_listener.h b/interfaces/innerkits/task_dispatcher/include/task/task_listener.h index 4ba73a96b61cce7f19bde0abb6a1643ac5a76e9e..27ff313fffcb70f78e1c3c1b611d083047ab96c9 100644 --- a/interfaces/innerkits/task_dispatcher/include/task/task_listener.h +++ b/interfaces/innerkits/task_dispatcher/include/task/task_listener.h @@ -27,9 +27,9 @@ class TaskListener { public: virtual ~TaskListener(){}; /** - *@brief Called when task stage changed. - *@param stage The stage - *@return void + * @brief Called when task stage changed. + * @param stage The stage + * @return void */ virtual void OnChanged(const TaskStage &stage) = 0; }; diff --git a/interfaces/innerkits/task_dispatcher/include/threading/concurrent_queue.h b/interfaces/innerkits/task_dispatcher/include/threading/concurrent_queue.h index 76090d0e4cdfc4f32f6fe6dae14fae6322ff94bf..6126745ee0422a347a8c931192e8f8c491e182fc 100644 --- a/interfaces/innerkits/task_dispatcher/include/threading/concurrent_queue.h +++ b/interfaces/innerkits/task_dispatcher/include/threading/concurrent_queue.h @@ -24,7 +24,7 @@ namespace OHOS { namespace AppExecFwk { -template +template class ConcurrentQueue { public: ConcurrentQueue() : empty_(){}; diff --git a/interfaces/innerkits/task_dispatcher/src/dispatcher/group_impl.cpp b/interfaces/innerkits/task_dispatcher/src/dispatcher/group_impl.cpp index ed3b982aca4b115e217a776d030c419018657b6f..578b4132722c19191bb91312bb3cf5cb58fa678c 100644 --- a/interfaces/innerkits/task_dispatcher/src/dispatcher/group_impl.cpp +++ b/interfaces/innerkits/task_dispatcher/src/dispatcher/group_impl.cpp @@ -111,7 +111,7 @@ bool GroupImpl::AddNotification(const std::shared_ptr ¬ification) return true; } /** - * @brief Notify all tasks and remove from queue. + * @brief Notify all tasks and remove from queue. * Attention: Notifications added after all tasks done is not guaranteed. */ void GroupImpl::DrainNotifications() diff --git a/interfaces/innerkits/task_dispatcher/src/dispatcher/parallel_task_dispatcher_base.cpp b/interfaces/innerkits/task_dispatcher/src/dispatcher/parallel_task_dispatcher_base.cpp index de9e3e011b20b3043b639690e0260b189ecf0951..ddce41c646bac8f8742499b33f3bea021804824b 100644 --- a/interfaces/innerkits/task_dispatcher/src/dispatcher/parallel_task_dispatcher_base.cpp +++ b/interfaces/innerkits/task_dispatcher/src/dispatcher/parallel_task_dispatcher_base.cpp @@ -122,8 +122,7 @@ std::shared_ptr ParallelTaskDispatcherBase::DelayDispatch( return nullptr; } TracePointBeforePost(innerTask, true, DELAY_DISPATCHER_TAG); - std::function callback = - std::bind(&ParallelTaskDispatcherBase::InterceptedExecute, shared_from_this(), innerTask); + std::function < void()> callback = std::bind(&ParallelTaskDispatcherBase::InterceptedExecute, shared_from_this(), innerTask); bool executeFlag = executor_->DelayExecute(callback, delayMs); if (!executeFlag) { APP_LOGE("ParallelTaskDispatcherBase::DelayDispatch execute failed"); diff --git a/interfaces/innerkits/task_dispatcher/src/dispatcher/serial_task_dispatcher.cpp b/interfaces/innerkits/task_dispatcher/src/dispatcher/serial_task_dispatcher.cpp index 48e37f068ef063c144b9a35af6d466a9853dd858..42fc5720c7a3e2dbb2293b25113748066096953b 100644 --- a/interfaces/innerkits/task_dispatcher/src/dispatcher/serial_task_dispatcher.cpp +++ b/interfaces/innerkits/task_dispatcher/src/dispatcher/serial_task_dispatcher.cpp @@ -108,7 +108,7 @@ std::shared_ptr SerialTaskDispatcher::DelayDispatch(const std::shared } TracePointBeforePost(innerTask, true, DELAY_DISPATCHER_TAG); // bind parameter to avoid deconstruct. - std::function callback = std::bind(&SerialTaskDispatcher::OnNewTaskIn, this, innerTask); + std::function < void()> callback = std::bind(&SerialTaskDispatcher::OnNewTaskIn, this, innerTask); bool executeFlag = executor_->DelayExecute(callback, delayMs); if (!executeFlag) { APP_LOGE("SerialTaskDispatcher::DelayDispatch execute failed"); diff --git a/interfaces/innerkits/task_dispatcher/src/dispatcher/task_dispatcher_context.cpp b/interfaces/innerkits/task_dispatcher/src/dispatcher/task_dispatcher_context.cpp index 9e22e53a262b679e845cfa591503af978625e593..e2c737e8914e4a08b270f61ef3dd1d1043c8a568 100644 --- a/interfaces/innerkits/task_dispatcher/src/dispatcher/task_dispatcher_context.cpp +++ b/interfaces/innerkits/task_dispatcher/src/dispatcher/task_dispatcher_context.cpp @@ -128,6 +128,8 @@ int TaskDispatcherContext::MapPriorityIndex(TaskPriority priority) const return DEFAULT_PRIORITY_INDEX; case TaskPriority::LOW: return LOW_PRIORITY_INDEX; + default: + return DEFAULT_PRIORITY_INDEX; } APP_LOGE("TaskDispatcherContext.mapPriorityIndex unhandled priority=%{public}d", priority); diff --git a/interfaces/innerkits/task_dispatcher/src/task/barrier_handler.cpp b/interfaces/innerkits/task_dispatcher/src/task/barrier_handler.cpp index a8d0c7a42f4dae87d84caf7959f6a70c019fa7b3..0f4706ac1abbd1a1cee09166eeed1ce0ceb86957 100644 --- a/interfaces/innerkits/task_dispatcher/src/task/barrier_handler.cpp +++ b/interfaces/innerkits/task_dispatcher/src/task/barrier_handler.cpp @@ -171,9 +171,9 @@ bool BarrierHandler::HasTask(const std::set> &tasks) std::set> BarrierHandler::CreateTaskSet(std::shared_ptr &firstTask) { - std::set> newSet; - newSet.insert(firstTask); - return newSet; + std::set> taskSet; + taskSet.insert(firstTask); + return taskSet; } } // namespace AppExecFwk diff --git a/interfaces/innerkits/task_dispatcher/src/task/task.cpp b/interfaces/innerkits/task_dispatcher/src/task/task.cpp index dd23ef89d615203af10abce79e6924d646deeb24..6f73cfc53f54db4add6838e27b3120808629a72c 100644 --- a/interfaces/innerkits/task_dispatcher/src/task/task.cpp +++ b/interfaces/innerkits/task_dispatcher/src/task/task.cpp @@ -37,9 +37,9 @@ Task::~Task() {} /** - *@brief invoke the function to execute the task - *@param None - *@return None + * @brief invoke the function to execute the task + * @param None + * @return None */ void Task::Run() { @@ -57,9 +57,9 @@ void Task::Run() } /** - * @brief Gets the priority. - * @param None - * @return The priority. + * @brief Gets the priority. + * @param None + * @return The priority. */ TaskPriority Task::GetPriority() const { @@ -67,10 +67,10 @@ TaskPriority Task::GetPriority() const } /** - * @brief Sets the sequence. - * @param None - * @param sequence The sequence - * @return None + * @brief Sets the sequence. + * @param None + * @param sequence The sequence + * @return None */ void Task::SetSequence(long sequence) { @@ -78,9 +78,9 @@ void Task::SetSequence(long sequence) } /** - *@brief Gets the sequence. - *@param None - *@return The sequence. + * @brief Gets the sequence. + * @param None + * @return The sequence. */ long Task::GetSequence() const { @@ -88,9 +88,9 @@ long Task::GetSequence() const } /** - *@brief Revoke this task if hasn't run. - *@param None - *@return true if set revoked or already revoked. False if the task has start executing. + * @brief Revoke this task if hasn't run. + * @param None + * @return true if set revoked or already revoked. False if the task has start executing. */ bool Task::Revoke() { @@ -107,9 +107,9 @@ bool Task::Revoke() } /** - *@brief Adds a task listener. - *@param listener The listener - *@return None + * @brief Adds a task listener. + * @param listener The listener + * @return None */ void Task::AddTaskListener(const std::shared_ptr &listener) { @@ -118,9 +118,9 @@ void Task::AddTaskListener(const std::shared_ptr &listener) } /** - *@brief Called when task is about to run. - *@param None - *@return None + * @brief Called when task is about to run. + * @param None + * @return None */ void Task::BeforeTaskExecute() { @@ -130,9 +130,9 @@ void Task::BeforeTaskExecute() } /** - *@brief Called when task is done. - *@param None - *@return None + * @brief Called when task is done. + * @param None + * @return None */ void Task::AfterTaskExecute() { @@ -143,9 +143,9 @@ void Task::AfterTaskExecute() } /** - *@brief Called when task is canceled. - *@param None - *@return None + * @brief Called when task is canceled. + * @param None + * @return None */ void Task::OnTaskCanceled() { @@ -154,9 +154,9 @@ void Task::OnTaskCanceled() } /** - *@brief Return true if not executed or revoked, and if not executed or revoked, ensure |EXECUTED| to be set. - *@param None - *@return bool + * @brief Return true if not executed or revoked, and if not executed or revoked, ensure |EXECUTED| to be set. + * @param None + * @return bool */ bool Task::EnterExecute() { diff --git a/interfaces/innerkits/task_dispatcher/src/threading/task_executor.cpp b/interfaces/innerkits/task_dispatcher/src/threading/task_executor.cpp index 406f79dd31a2506163532de044de66a5838cd0cc..197f1ae4e528b9103cb62bbc8287c379ed06e849 100644 --- a/interfaces/innerkits/task_dispatcher/src/threading/task_executor.cpp +++ b/interfaces/innerkits/task_dispatcher/src/threading/task_executor.cpp @@ -94,7 +94,7 @@ std::shared_ptr TaskExecutor::GetTask(const std::shared_ptr std::shared_ptr nullRunnable = nullptr; std::shared_ptr next = nullptr; - for (;;) { + for(;;) { if (terminated_.load() && pendingTasks_->Empty()) { APP_LOGI("TaskExecutor::GetTask end: loop thread %{public}s is terminated", workerThread->GetThreadName().c_str()); @@ -204,7 +204,7 @@ bool TaskExecutor::EnsureConsumeStarted() void TaskExecutor::Consume() { - for (;;) { + for(;;) { if (terminated_.load() && delayTasks_->Empty()) { APP_LOGI("TaskExecutor::Consume delay task is empty"); break; diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/barrier_handler_test/barrier_handler_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/barrier_handler_test/barrier_handler_test.cpp index 90a170230aeecf83d69f2370c060a6d3f5f18aeb..57eedb0cf9657977627c8e13fc5f1893f1f6e89a 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/barrier_handler_test/barrier_handler_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/barrier_handler_test/barrier_handler_test.cpp @@ -76,7 +76,6 @@ HWTEST(BarrierHandlerTest, BarrierHandler_interceptTest_001, TestSize.Level0) auto name = std::string("BarrierHandler_interceptTest_001"); GTEST_LOG_(INFO) << name << " start"; std::shared_ptr barrierHandler = CreateBarrierHandler(); - //每次添加组任务, 给任务添加监听,当任务完成时候。。。。。判断任务是否应该执行(前面有屏障时候,不立即执行)。 std::shared_ptr runnable = std::make_shared([&]() { GTEST_LOG_(INFO) << name << " Runnable"; }); std::shared_ptr task = std::make_shared(runnable, TaskPriority::DEFAULT, nullptr); ErrCode result = barrierHandler->Intercept(task); diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/groupImpl_test/groupImpl_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/groupImpl_test/groupImpl_test.cpp index 0daf94b2784c4f5bb94ac7cb21f7097c15266113..2a9931d164d40993ff0c34db86bde717061e9bdc 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/groupImpl_test/groupImpl_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/groupImpl_test/groupImpl_test.cpp @@ -175,9 +175,9 @@ HWTEST(GroupImplTest, AppExecFwk_GroupImpl_AddNotification_002, TestSize.Level0) std::make_shared([&]() { GTEST_LOG_(INFO) << "GroupImpl AddNotification"; }); groupPtr->AddNotification(notification); } - std::shared_ptr newNotification = + std::shared_ptr notificationTask = std::make_shared([&]() { GTEST_LOG_(INFO) << "GroupImpl AddNotification"; }); - bool result = groupPtr->AddNotification(newNotification); + bool result = groupPtr->AddNotification(notificationTask); EXPECT_TRUE(result); GTEST_LOG_(INFO) << name << " end"; } @@ -198,9 +198,9 @@ HWTEST(GroupImplTest, AppExecFwk_GroupImpl_AddNotification_003, TestSize.Level0) std::make_shared([&]() { GTEST_LOG_(INFO) << "GroupImpl AddNotification"; }); groupPtr->AddNotification(notification); } - std::shared_ptr newNotification = + std::shared_ptr notificationTask = std::make_shared([&]() { GTEST_LOG_(INFO) << "GroupImpl AddNotification"; }); - bool result = groupPtr->AddNotification(newNotification); + bool result = groupPtr->AddNotification(notificationTask); EXPECT_FALSE(result); GTEST_LOG_(INFO) << name << " end"; } diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/parallel_task_dispatcher_base_test/parallel_task_dispatcher_base_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/parallel_task_dispatcher_base_test/parallel_task_dispatcher_base_test.cpp index 5347daaca1ff5357f1c146140a5356e7f9d4636c..a7e924cf0234769f389676492b8b6b03d87e4b14 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/parallel_task_dispatcher_base_test/parallel_task_dispatcher_base_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/parallel_task_dispatcher_base_test/parallel_task_dispatcher_base_test.cpp @@ -194,7 +194,6 @@ HWTEST(ParallelTaskDispatcherBaseTest, ParallelTaskDispatcherBase_AsyncGroupDisp CreateParallelTaskDispatcherBase(name, TaskPriority::DEFAULT); std::atomic count(0); EXPECT_EQ(count.load(), 0); - //添加个group1 std::shared_ptr group1 = parallelTaskDispatcherBase->CreateDispatchGroup(); std::shared_ptr group1Run1 = std::make_shared([&]() { std::this_thread::sleep_for(std::chrono::milliseconds(800)); @@ -209,7 +208,6 @@ HWTEST(ParallelTaskDispatcherBaseTest, ParallelTaskDispatcherBase_AsyncGroupDisp GTEST_LOG_(INFO) << name << " Group1 : Runnable2"; }); parallelTaskDispatcherBase->AsyncGroupDispatch(group1, group1Run2); - //添加group2 std::shared_ptr group2 = parallelTaskDispatcherBase->CreateDispatchGroup(); std::shared_ptr group2Run = std::make_shared([&]() { count.fetch_add(1); diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/spec_task_dispatcher_test/spec_task_dispatcher_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/spec_task_dispatcher_test/spec_task_dispatcher_test.cpp index 8c4ad4db71213c977e0af2d1bfb6469eec01996b..07212360d09691672937333f42bf650d061381d0 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/spec_task_dispatcher_test/spec_task_dispatcher_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/spec_task_dispatcher_test/spec_task_dispatcher_test.cpp @@ -59,17 +59,10 @@ void SpecTaskDispatcherTest::SetUp() void SpecTaskDispatcherTest::TearDown() {} -std::string Now() -{ - time_t now = std::time(0); - char mbstr[10]; - std::strftime(mbstr, sizeof(mbstr), "%T", std::localtime(&now)); - return mbstr; -} const std::string Prefix(const std::string &name) { - return std::string(">>> ") + Now() + std::string(" ") + name + std::string(": "); + return std::string(">>> prefix :") + std::string(" ") + name + std::string(": "); } std::shared_ptr CreateSpecTaskDispatcher() diff --git a/interfaces/innerkits/test/moduletest/task_dispatcher/serial_task_dispatcher_module_test/serial_task_dispatcher_module_test.cpp b/interfaces/innerkits/test/moduletest/task_dispatcher/serial_task_dispatcher_module_test/serial_task_dispatcher_module_test.cpp index b267e283e1d06a68bc2b96c8894b586061cc52f0..ee540863f7bea3473a55fb9d1ed25d8b7618f0dd 100644 --- a/interfaces/innerkits/test/moduletest/task_dispatcher/serial_task_dispatcher_module_test/serial_task_dispatcher_module_test.cpp +++ b/interfaces/innerkits/test/moduletest/task_dispatcher/serial_task_dispatcher_module_test/serial_task_dispatcher_module_test.cpp @@ -194,7 +194,7 @@ HWTEST_F(SerialTaskDispatcherModuleTest, SerialTaskDispatcher_AsyncDispatchTest_ int index = count.fetch_add(1); GTEST_LOG_(INFO) << "SerialTaskDispatcher_AsyncDispatchTest_002 task" + std::to_string(index) + "end"; })); - wait += 1; + wait += 10; } EXPECT_TRUE(count.load() < total); auto time = std::chrono::milliseconds(wait + 1000); diff --git a/kits/appkit/napi/bundlemgr/bundle_mgr.cpp b/kits/appkit/napi/bundlemgr/bundle_mgr.cpp index 2f02deeccf5a892a76ffc88ffc02bc8085a76a08..1d01da1a0235cb0ca36da56066c531e1ab682846 100644 --- a/kits/appkit/napi/bundlemgr/bundle_mgr.cpp +++ b/kits/appkit/napi/bundlemgr/bundle_mgr.cpp @@ -956,7 +956,7 @@ static napi_value ParseInt(napi_env env, int ¶m, napi_value args) NAPI_CALL(env, napi_typeof(env, args, &valuetype)); HILOG_INFO("param=%{public}d.", valuetype); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. int32 expected."); - int32_t value; + int32_t value = 0; napi_get_value_int32(env, args, &value); HILOG_INFO("param=%{public}d.", value); param = value; @@ -1031,7 +1031,7 @@ napi_value GetApplicationInfos(napi_env env, napi_callback_info info) applicationFlag = ApplicationFlag::GET_BASIC_APPLICATION_INFO; } - AsyncApplicationInfosCallbackInfo *asyncCallbackInfo = new AsyncApplicationInfosCallbackInfo{ + AsyncApplicationInfosCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncApplicationInfosCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .applicationFlag = applicationFlag, .userId = userId}; if (asyncCallbackInfo == nullptr) { return nullptr; @@ -1072,6 +1072,7 @@ napi_value GetApplicationInfos(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -1114,6 +1115,7 @@ napi_value GetApplicationInfos(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -1258,6 +1260,7 @@ napi_value QueryAbilityInfo(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -1300,6 +1303,7 @@ napi_value QueryAbilityInfo(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -1363,7 +1367,7 @@ napi_value GetApplicationInfo(napi_env env, napi_callback_info info) if (flag == static_cast(ApplicationFlag::GET_BASIC_APPLICATION_INFO)) { applicationFlag = ApplicationFlag::GET_BASIC_APPLICATION_INFO; } - AsyncApplicationInfoCallbackInfo *asyncCallbackInfo = new AsyncApplicationInfoCallbackInfo{.env = env, + AsyncApplicationInfoCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncApplicationInfoCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleName = bundleName, @@ -1416,6 +1420,7 @@ napi_value GetApplicationInfo(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -1466,6 +1471,7 @@ napi_value GetApplicationInfo(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -1533,7 +1539,7 @@ napi_value GetBundleInfos(napi_env env, napi_callback_info info) if (flag == static_cast(BundleFlag::GET_BUNDLE_DEFAULT)) { bundleFlag = BundleFlag::GET_BUNDLE_DEFAULT; } - AsyncBundleInfosCallbackInfo *asyncCallbackInfo = new AsyncBundleInfosCallbackInfo{ + AsyncBundleInfosCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncBundleInfosCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleFlag = bundleFlag}; if (asyncCallbackInfo == nullptr) { return nullptr; @@ -1574,6 +1580,7 @@ napi_value GetBundleInfos(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -1616,6 +1623,7 @@ napi_value GetBundleInfos(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -1665,7 +1673,7 @@ napi_value GetBundleInfo(napi_env env, napi_callback_info info) if (flag == static_cast(BundleFlag::GET_BUNDLE_DEFAULT)) { bundleFlag = BundleFlag::GET_BUNDLE_DEFAULT; } - AsyncBundleInfoCallbackInfo *asyncCallbackInfo = new AsyncBundleInfoCallbackInfo{ + AsyncBundleInfoCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncBundleInfoCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .param = bundleName, .bundleFlag = bundleFlag}; if (asyncCallbackInfo == nullptr) { return nullptr; @@ -1706,6 +1714,7 @@ napi_value GetBundleInfo(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -1749,6 +1758,7 @@ napi_value GetBundleInfo(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -1798,7 +1808,7 @@ napi_value GetBundleArchiveInfo(napi_env env, napi_callback_info info) if (flag == static_cast(BundleFlag::GET_BUNDLE_DEFAULT)) { bundleFlag = BundleFlag::GET_BUNDLE_DEFAULT; } - AsyncBundleInfoCallbackInfo *asyncCallbackInfo = new AsyncBundleInfoCallbackInfo{ + AsyncBundleInfoCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncBundleInfoCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .param = hapFilePath, .bundleFlag = bundleFlag}; if (asyncCallbackInfo == nullptr) { return nullptr; @@ -1839,6 +1849,7 @@ napi_value GetBundleArchiveInfo(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -1881,6 +1892,7 @@ napi_value GetBundleArchiveInfo(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -1983,7 +1995,7 @@ napi_value GetPermissionDef(napi_env env, napi_callback_info info) HILOG_INFO("argc = [%{public}zu]", argc); std::string permissionName; ParseString(env, permissionName, argv[PARAM0]); - AsyncPermissionDefCallbackInfo *asyncCallbackInfo = new AsyncPermissionDefCallbackInfo{ + AsyncPermissionDefCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncPermissionDefCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .permissionName = permissionName}; if (asyncCallbackInfo == nullptr) { return nullptr; @@ -2024,6 +2036,7 @@ napi_value GetPermissionDef(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -2064,6 +2077,7 @@ napi_value GetPermissionDef(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -2158,6 +2172,7 @@ napi_value GetBundleInstaller(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -2194,6 +2209,7 @@ napi_value GetBundleInstaller(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -2391,7 +2407,7 @@ napi_value Install(napi_env env, napi_callback_info info) ParseStringArray(env, bundleFilePaths, argv[PARAM0]); InstallParam installParam; ParseInstallParam(env, installParam, argv[PARAM1]); - AsyncInstallCallbackInfo *asyncCallbackInfo = new AsyncInstallCallbackInfo{ + AsyncInstallCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncInstallCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, @@ -2447,6 +2463,7 @@ napi_value Install(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -2497,6 +2514,7 @@ napi_value Install(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -2553,7 +2571,7 @@ napi_value Uninstall(napi_env env, napi_callback_info info) ParseString(env, bundleName, argv[PARAM0]); InstallParam installParam; ParseInstallParam(env, installParam, argv[PARAM1]); - AsyncInstallCallbackInfo *asyncCallbackInfo = new AsyncInstallCallbackInfo{ + AsyncInstallCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncInstallCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, @@ -2607,6 +2625,7 @@ napi_value Uninstall(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -2656,6 +2675,7 @@ napi_value Uninstall(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -2760,6 +2780,7 @@ napi_value GetAllFormsInfo(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -2802,6 +2823,7 @@ napi_value GetAllFormsInfo(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -2845,7 +2867,7 @@ napi_value GetFormsInfoByModule(napi_env env, napi_callback_info info) ParseString(env, bundleName, argv[PARAM0]); ParseString(env, moduleName, argv[PARAM1]); - AsyncFormInfosByModuleCallbackInfo *asyncCallbackInfo = new AsyncFormInfosByModuleCallbackInfo{ + AsyncFormInfosByModuleCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncFormInfosByModuleCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleName = bundleName, .moduleName = moduleName}; if (asyncCallbackInfo == nullptr) { return nullptr; @@ -2886,6 +2908,7 @@ napi_value GetFormsInfoByModule(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -2928,6 +2951,7 @@ napi_value GetFormsInfoByModule(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -2969,7 +2993,7 @@ napi_value GetFormsInfoByApp(napi_env env, napi_callback_info info) std::string bundleName; ParseString(env, bundleName, argv[PARAM0]); - AsyncFormInfosByAppCallbackInfo *asyncCallbackInfo = new AsyncFormInfosByAppCallbackInfo{ + AsyncFormInfosByAppCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncFormInfosByAppCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleName = bundleName}; if (asyncCallbackInfo == nullptr) { return nullptr; @@ -3010,6 +3034,7 @@ napi_value GetFormsInfoByApp(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -3051,6 +3076,7 @@ napi_value GetFormsInfoByApp(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -3111,7 +3137,7 @@ napi_value GetShortcutInfos(napi_env env, napi_callback_info info) HILOG_INFO("ARGCSIZE is =%{public}zu.", argc); std::string bundleName; ParseString(env, bundleName, argv[PARAM0]); - AsyncShortcutInfosCallbackInfo *asyncCallbackInfo = new AsyncShortcutInfosCallbackInfo{ + AsyncShortcutInfosCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncShortcutInfosCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleName = bundleName}; if (asyncCallbackInfo == nullptr) { return nullptr; @@ -3152,6 +3178,7 @@ napi_value GetShortcutInfos(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -3193,6 +3220,7 @@ napi_value GetShortcutInfos(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -3253,7 +3281,7 @@ napi_value GetModuleUsageRecords(napi_env env, napi_callback_info info) HILOG_INFO("ARGCSIZE is =%{public}zu.", argc); int number; ParseInt(env, number, argv[PARAM0]); - AsyncModuleUsageRecordsCallbackInfo *asyncCallbackInfo = new AsyncModuleUsageRecordsCallbackInfo{ + AsyncModuleUsageRecordsCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncModuleUsageRecordsCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .number = number}; if (asyncCallbackInfo == nullptr) { return nullptr; @@ -3294,6 +3322,7 @@ napi_value GetModuleUsageRecords(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -3335,6 +3364,7 @@ napi_value GetModuleUsageRecords(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -3399,8 +3429,8 @@ static napi_value ParseInt32Array(napi_env env, std::vector &uids, napi uids.emplace_back(uid); } // create result code - napi_value result; - napi_status status; + napi_value result = nullptr; + napi_status status = napi_ok; status = napi_create_int32(env, NAPI_RETURN_ONE, &result); NAPI_ASSERT(env, status == napi_ok, "napi_create_int32 error!"); return result; @@ -3475,6 +3505,7 @@ napi_value RegisterAllPermissionsChanged(napi_env env, napi_callback_info info) AsyncRegisterPermissions *asyncCallbackInfo = (AsyncRegisterPermissions *)data; napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -3495,6 +3526,9 @@ napi_value RegisterAllPermissionsChanged(napi_env env, napi_callback_info info) } else if (permissionEvent == ANY_PERMISSION_CHANGE && argc == ARGS_SIZE_TWO) { AsyncRegisterAllPermissions *asyncCallbackInfo = new AsyncRegisterAllPermissions{.env = env, .asyncWork = nullptr}; + if (asyncCallbackInfo == nullptr) { + return nullptr; + } HILOG_INFO("RegisterAllPermissionsChanged anyPermissionChange asyncCallback."); napi_valuetype valuetype = napi_undefined; napi_typeof(env, argv[ARGS_SIZE_ONE], &valuetype); @@ -3514,6 +3548,7 @@ napi_value RegisterAllPermissionsChanged(napi_env env, napi_callback_info info) AsyncRegisterAllPermissions *asyncCallbackInfo = (AsyncRegisterAllPermissions *)data; napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -3616,7 +3651,7 @@ napi_value UnregisterPermissionsChanged(napi_env env, napi_callback_info info) ParseString(env, permissionEvent, argv[PARAM0]); if (permissionEvent == ANY_PERMISSION_CHANGE && argc == ARGS_SIZE_TWO) { - AsyncUnregisterPermissions *asyncCallbackInfo = new AsyncUnregisterPermissions{ + AsyncUnregisterPermissions *asyncCallbackInfo = new (std::nothrow) AsyncUnregisterPermissions{ .env = env, .asyncWork = nullptr, }; @@ -3652,6 +3687,7 @@ napi_value UnregisterPermissionsChanged(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -3706,6 +3742,7 @@ napi_value UnregisterPermissionsChanged(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -3756,7 +3793,7 @@ napi_value CheckPermission(napi_env env, napi_callback_info info) std::string permission; ParseString(env, permission, argv[PARAM1]); - AsyncPermissionCallbackInfo *asyncCallbackInfo = new AsyncPermissionCallbackInfo{ + AsyncPermissionCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncPermissionCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleName = bundleName, .permission = permission}; if (asyncCallbackInfo == nullptr) { return nullptr; @@ -3797,6 +3834,7 @@ napi_value CheckPermission(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); @@ -3839,6 +3877,7 @@ napi_value CheckPermission(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); diff --git a/kits/appkit/napi/bundlemgr/permission_callback.cpp b/kits/appkit/napi/bundlemgr/permission_callback.cpp index 3b8d3b4f955da7a232fdb9e40298ae000d538f51..071b8d8c6f9bbd429f8019641cb13dd60dcb376d 100644 --- a/kits/appkit/napi/bundlemgr/permission_callback.cpp +++ b/kits/appkit/napi/bundlemgr/permission_callback.cpp @@ -18,7 +18,6 @@ #include "hilog_wrapper.h" namespace { - constexpr size_t ARGS_SIZE_TWO = 2; } @@ -38,17 +37,28 @@ void PermissionCallback::OnChanged(const int32_t uid) #if NAPI_VERSION >= 2 napi_get_uv_event_loop(env_, &loop); #endif // NAPI_VERSION >= 2 + if (loop == nullptr) { + HILOG_INFO("loop instance is nullptr"); + return; + } - uv_work_t *work = new uv_work_t; + uv_work_t *work = new (std::nothrow) uv_work_t; + if (work == nullptr) { + HILOG_ERROR("new uv_work_t failed"); + return; + } CallbackInfo *callbackInfo = new (std::nothrow) CallbackInfo{ .env = env_, .callback = callback_, .uid = uid, }; - + if (callbackInfo == nullptr) { + HILOG_ERROR("new CallbackInfo failed"); + return; + } work->data = (void *)callbackInfo; - uv_queue_work( + int rev = uv_queue_work( loop, work, [](uv_work_t *work) {}, @@ -74,8 +84,17 @@ void PermissionCallback::OnChanged(const int32_t uid) napi_get_reference_value(event->env, event->callback, &callback); napi_call_function(event->env, undefined, callback, ARGS_SIZE_TWO, &result[0], &callbackResult); delete event; + event = nullptr; delete work; + work = nullptr; }); - + if (rev != 0) { + if (callbackInfo != nullptr) { + delete callbackInfo; + } + if (work != nullptr) { + delete work; + } + } HILOG_INFO("OnChanged, end"); } \ No newline at end of file diff --git a/kits/appkit/native/app/include/app_loader.h b/kits/appkit/native/app/include/app_loader.h index a1197ca895bb38ecf4adada31bfc2377bc4a32e6..5b751c7e1d452dc97391331562d05b7d3752714b 100644 --- a/kits/appkit/native/app/include/app_loader.h +++ b/kits/appkit/native/app/include/app_loader.h @@ -80,7 +80,7 @@ private: __attribute__((constructor)) void REGISTER_APPLICATION##className() \ { \ ApplicationLoader::GetInstance().RegisterApplication( \ - #bundleName, []() -> OHOSApplication * { return new (std::nothrow) className; }); \ + #bundleName, []()->OHOSApplication * { return new (std::nothrow) className; }); \ } } // namespace AppExecFwk diff --git a/kits/appkit/native/app/include/main_thread.h b/kits/appkit/native/app/include/main_thread.h index 21f43ad89a418f91edd8abb71fbf82f27a325443..fda5783d3e80de134215766a0f195916544e3d7d 100644 --- a/kits/appkit/native/app/include/main_thread.h +++ b/kits/appkit/native/app/include/main_thread.h @@ -24,13 +24,16 @@ #include "app_mgr_interface.h" #include "ability_record_mgr.h" #include "application_impl.h" +#include "resource_manager.h" #include "ohos/aafwk/base/ipc_singleton.h" #define ABILITY_LIBRARY_LOADER namespace OHOS { namespace AppExecFwk { +using namespace OHOS::Global; enum class MainThreadState { INIT, ATTACH, READY, RUNNING }; - +class ContextDeal; +// class Global::Resource::ResourceManager; class AppMgrDeathRecipient : public IRemoteObject::DeathRecipient { public: /** @@ -400,6 +403,8 @@ private: */ void LoadAbilityLibrary(const std::vector &libraryPaths); + void LoadAppLibrary(); + /** * * @brief Close the ability library loaded. @@ -427,6 +432,12 @@ private: * */ bool CheckFileType(const std::string &fileName, const std::string &extensionName); + + bool InitCreate(std::shared_ptr &contextDeal, ApplicationInfo &appInfo, ProcessInfo &processInfo, + Profile &appProfile); + bool CheckForHandleLaunchApplication(const AppLaunchData &appLaunchData); + bool InitResourceManager(std::shared_ptr &resourceManager, + std::shared_ptr &contextDeal, ApplicationInfo &appInfo); std::vector fileEntries_; std::vector handleAbilityLib_; // the handler of ACE Library. #endif // ABILITY_LIBRARY_LOADER diff --git a/kits/appkit/native/app/include/task_dispatcher.h b/kits/appkit/native/app/include/task_dispatcher.h index ad06df59eaaef82f64d2164e337864277e2cf3dd..4ddee5b9834a4da0693ac826be2a3504b8d28c2e 100644 --- a/kits/appkit/native/app/include/task_dispatcher.h +++ b/kits/appkit/native/app/include/task_dispatcher.h @@ -25,7 +25,7 @@ namespace OHOS { namespace AppExecFwk { -template +template using IteratableTask = std::function; class TaskDispatcher { @@ -33,31 +33,15 @@ public: virtual ~TaskDispatcher() = default; /** - * Dispatches a task and waits until the task is complete in the current thread. + * @brief Dispatches a task and waits until the task is complete in the current thread. * - *

The current thread is blocked before the given task is complete. Therefore, a deadlock occurs in the - * following cases: - *

- *
    - *
  1. - * {@code SyncDispatch} is cyclically called on a serial task dispatcher or a task dispatcher that is dedicated - * to a specific thread. For example, {@code SyncDispatch} is called to dispatch a task from dispatcher A to - * dispatcher A, or to dispatch a task from dispatcher A to dispatcher B and then back to dispatcher A. - *
  2. - *
  3. - * Too many threads are blocked on {@code SyncDispatch}. As a result, the internal thread pool is used up and - * cannot process other tasks any more. - *
  4. - *
- *
* @param runnable Indicates the task to be executed. This parameter includes all information required for the task * execution. - * @since 1 */ virtual ErrCode SyncDispatch(const std::shared_ptr &runnable) = 0; /** - * Asynchronously dispatches a task. + * @brief Asynchronously dispatches a task. * *

This method dispatches a task and returns a value immediately without waiting for the task to execute.

* @@ -65,12 +49,11 @@ public: * execution. * @return Returns a {@link std::shared_ptr} instance used for revoking the given task * if it has not been invoked. - * @since 1 */ virtual std::shared_ptr AsyncDispatch(const std::shared_ptr &runnable) = 0; /** - * Dispatches a task after the given delay. + * @brief Dispatches a task after the given delay. * *

This is an asynchronous execution and returns a value immediately without waiting. The task will be * dispatched to the queue after the given delay specified by {@code delayMs}, and its actual execution time @@ -83,12 +66,11 @@ public: * @param delayMs Indicates the time period that the given task has to wait before being dispatched. * @return Returns a {@link std::shared_ptr} instance used for revoking the given task * if it has not been invoked. - * @since 1 */ virtual std::shared_ptr DelayDispatch(const std::shared_ptr &runnable, long delayMs) = 0; /** - * Sets an execution barrier in a task group for the given task and waits for the task to be executed after all + * @brief Sets an execution barrier in a task group for the given task and waits for the task to be executed after all * tasks in the task group are finished. * *

The current thread is blocked until the given task is complete. Incorrect use of this method may cause a @@ -96,12 +78,11 @@ public: * If too many threads are blocked, resources in the thread pool will be used up.

* * @param runnable Indicates the task to be executed. - * @since 1 */ virtual ErrCode SyncDispatchBarrier(const std::shared_ptr &runnable) = 0; /** - * Sets an execution barrier for the given task to be executed only after all tasks in the task group are + * @brief Sets an execution barrier for the given task to be executed only after all tasks in the task group are * finished. This method does not wait for the given task to execute. * *

Task execution barriers are unavailable on global task dispatchers. Example code for setting a task @@ -122,21 +103,17 @@ public: * std::cout << "after barrier" << std::endl; * })); * - * // Result will be: - * // before barrier - * // Barrier - * // after barrier + * // Result will be: 1.before barrier; 2.Barrier; 3.after barrier. * } * * * @param runnable Indicates the task to be executed. This parameter includes all information required for the task * execution. - * @since 1 */ virtual ErrCode AsyncDispatchBarrier(const std::shared_ptr &runnable) = 0; /** - * Creates a task group. + * @brief Creates a task group. * *

The {@link std::shared_ptr} object returned by this method does not contain any task. * If you need to dispatch tasks asynchronously, you can use {@link #asyncGroupDispatch} to associate this object @@ -170,21 +147,12 @@ public: * std::cout << "2" << std::endl; * } * - * //Possible results are as follows: - * // 1 - * // 2 - * // Finished downloading URL 2 - * // Finished downloading URL 1 - * // All tasks finished. Do shutdown. - * } - * * @return Returns a {@link std::shared_ptr} object. - * @since 1 */ virtual std::shared_ptr CreateDispatchGroup() = 0; /** - * Adds a task to a task group asynchronously. + * @brief Adds a task to a task group asynchronously. * *

This method returns a value immediately without waiting for the task to execute.

* @@ -193,55 +161,34 @@ public: * execution. * @return Returns a {@link std::shared_ptr} instance used for revoking the given task * if it has not been invoked. - * @since 1 */ virtual std::shared_ptr AsyncGroupDispatch( const std::shared_ptr &group, const std::shared_ptr &runnable) = 0; /** - * Waits all tasks in a task group to finish. + * @brief Waits all tasks in a task group to finish. * * @param group Indicates the task group containing the waiting tasks. * @param timeout Indicates the maximum waiting time for a task. * @return Returns {@code true} if all tasks are correctly executed; returns {@code false} if any task times out. - * @since 1 */ virtual bool GroupDispatchWait(const std::shared_ptr &group, long timeout) = 0; /** - * Executes a task after all tasks in the task group are finished. + * @brief Executes a task after all tasks in the task group are finished. * * @param group Indicates the task group containing the waiting tasks. * @param runnable Indicates the task to be executed after all tasks are finished. - * @since 1 */ virtual ErrCode GroupDispatchNotify( const std::shared_ptr &group, const std::shared_ptr &runnable) = 0; /** - * Executes a task multiple times without waiting. - * - *

Example code: - *

{@code
-     * std::string names[] = {"Rafael Nadal", "Novak Djokovic",
-     *         "Stanislas Wawrinka",
-     *         "David Ferrer","Roger Federer",
-     *         "Andy Murray","Tomas Berdych",
-     *         "Juan Martin Del Potro"};
-     * int num = atp.length;
-     * std::shared_ptr dispatcher = context.getGlobalTaskDispatcher(TaskPriority.DEFAULT);
-     * // Concurrently dispatches tasks using names in |names|.
-     * dispatcher->ApplyDispatch([](i) {
-     *     std::cout << names[i] << std::endl;
-     * }, num);
-     * // The result to be returned depends on thread scheduling of the system.
-     * }
-     * 
+ * @brief Executes a task multiple times without waiting. * * @param task Indicates the task to be executed. This parameter includes all information required for the task * execution. * @param iterations Indicates the number of times the task is executed. The value must be a positive integer. - * @since 1 */ virtual ErrCode ApplyDispatch(const std::shared_ptr> &task, long iterations) = 0; }; diff --git a/kits/appkit/native/app/src/context_deal.cpp b/kits/appkit/native/app/src/context_deal.cpp index 12830529e858e5187f51d198c08c2e5d303d1a96..861a209ad9ac3bbd3fae0cef694b41f0bb0fff78 100755 --- a/kits/appkit/native/app/src/context_deal.cpp +++ b/kits/appkit/native/app/src/context_deal.cpp @@ -737,9 +737,11 @@ sptr ContextDeal::GetToken() */ void ContextDeal::initResourceManager(const std::shared_ptr &resourceManager) { + APP_LOGI("ContextDeal::initResourceManager. Start."); resourceManager_ = resourceManager; + APP_LOGI("ContextDeal::initResourceManager. End."); } - + /** * @brief Obtains information about the caller of this ability. * @@ -888,7 +890,6 @@ void ContextDeal::SetTheme(int themeId) return; } - // hapModInfo->themeId = themeId; APP_LOGI("ContextDeal::SetTheme end"); return; } @@ -947,7 +948,6 @@ int ContextDeal::GetThemeId() { auto hapModInfo = GetHapModuleInfo(); if (hapModInfo != nullptr) { - // return hapModInfo->themeId; return -1; } else { APP_LOGE("ContextDeal::GetThemeId hapModInfo is nullptr"); diff --git a/kits/appkit/native/app/src/main_thread.cpp b/kits/appkit/native/app/src/main_thread.cpp index 93957deea8413614bbeda20c208074a8b1133c01..6200031819421b692a6e0edc7685248129289d89 100644 --- a/kits/appkit/native/app/src/main_thread.cpp +++ b/kits/appkit/native/app/src/main_thread.cpp @@ -542,74 +542,43 @@ void MainThread::HandleProcessSecurityExit() APP_LOGI("MainThread::HandleProcessSecurityExit called end."); } -/** - * - * @brief Launch the application. - * - * @param appLaunchData The launchdata of the application witch launced. - * - */ -void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData) +bool MainThread::InitCreate( + std::shared_ptr &contextDeal, ApplicationInfo &appInfo, ProcessInfo &processInfo, Profile &appProfile) { - APP_LOGI("MainThread::handleLaunchApplication called start."); - if (application_ != nullptr) { - APP_LOGE("MainThread::handleLaunchApplication already create application"); - return; - } - - if (!CheckLaunchApplicationParam(appLaunchData)) { - APP_LOGE("MainThread::handleLaunchApplication appLaunchData invalid"); - return; - } - -#ifdef ABILITY_LIBRARY_LOADER - APP_LOGI("MainThread::handleLaunchApplication Start calling LoadAbilityLibrary."); - LoadAbilityLibrary(appLaunchData.GetApplicationInfo().moduleSourceDirs); - APP_LOGI("MainThread::handleLaunchApplication End calling LoadAbilityLibrary."); -#endif // ABILITY_LIBRARY_LOADER -#ifdef APPLICATION_LIBRARY_LOADER - std::string appPath = applicationLibraryPath; - APP_LOGI("MainThread::handleLaunchApplication Start calling dlopen. appPath=%{public}s", appPath.c_str()); - handleAppLib_ = dlopen(appPath.c_str(), RTLD_NOW | RTLD_GLOBAL); - if (handleAppLib_ == nullptr) { - APP_LOGE("Fail to dlopen %{public}s, [%{public}s]", appPath.c_str(), dlerror()); - exit(-1); - } - APP_LOGI("MainThread::handleLaunchApplication End calling dlopen."; -#endif // APPLICATION_LIBRARY_LOADER - - ApplicationInfo appInfo = appLaunchData.GetApplicationInfo(); - ProcessInfo processInfo = appLaunchData.GetProcessInfo(); - Profile appProfile = appLaunchData.GetProfile(); - applicationInfo_ = std::make_shared(appInfo); if (applicationInfo_ == nullptr) { - APP_LOGE("MainThread::handleLaunchApplication create applicationInfo_ failed"); - return; + APP_LOGE("MainThread::InitCreate create applicationInfo_ failed"); + return false; } processInfo_ = std::make_shared(processInfo); if (processInfo_ == nullptr) { - APP_LOGE("MainThread::handleLaunchApplication create processInfo_ failed"); - return; + APP_LOGE("MainThread::InitCreate create processInfo_ failed"); + return false; } appProfile_ = std::make_shared(appProfile); if (appProfile_ == nullptr) { - APP_LOGE("MainThread::handleLaunchApplication create appProfile_ failed"); - return; + APP_LOGE("MainThread::InitCreate create appProfile_ failed"); + return false; } applicationImpl_ = std::make_shared(); if (applicationImpl_ == nullptr) { - APP_LOGE("MainThread::handleLaunchApplication create applicationImpl_ failed"); - return; + APP_LOGE("MainThread::InitCreate create applicationImpl_ failed"); + return false; + } + + abilityRecordMgr_ = std::make_shared(); + if (abilityRecordMgr_ == nullptr) { + APP_LOGE("MainThread::InitCreate create AbilityRecordMgr failed"); + return false; } - std::shared_ptr contextDeal = std::make_shared(); + contextDeal = std::make_shared(); if (contextDeal == nullptr) { - APP_LOGE("MainThread::handleLaunchApplication create contextDeal failed"); - return; + APP_LOGE("MainThread::InitCreate create contextDeal failed"); + return false; } contextDeal->SetProcessInfo(processInfo_); @@ -617,27 +586,31 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData) contextDeal->SetProfile(appProfile_); contextDeal->SetBundleCodePath(applicationInfo_->codePath); // BMS need to add cpath - // BMS should set the type (native or ace) of application - bool isNativeApp = true; - std::string appName = isNativeApp ? appInfo.name : aceApplicationName_; - application_ = std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName(appName)); - if (application_ == nullptr) { - APP_LOGE("HandleLaunchApplication::application launch failed"); - return; + return true; +} + +bool MainThread::CheckForHandleLaunchApplication(const AppLaunchData &appLaunchData) +{ + if (application_ != nullptr) { + APP_LOGE("MainThread::handleLaunchApplication already create application"); + return false; } - // init resourceManager. - std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); - if (resourceManager == nullptr) { - APP_LOGE("MainThread::handleLaunchApplication create resourceManager failed"); - return; + if (!CheckLaunchApplicationParam(appLaunchData)) { + APP_LOGE("MainThread::handleLaunchApplication appLaunchData invalid"); + return false; } + return true; +} - APP_LOGI("MainThread::handleLaunchApplication. Start calling GetBundleManager."); +bool MainThread::InitResourceManager(std::shared_ptr &resourceManager, + std::shared_ptr &contextDeal, ApplicationInfo &appInfo) +{ + APP_LOGI("MainThread::InitResourceManager. Start calling GetBundleManager."); sptr bundleMgr = contextDeal->GetBundleManager(); if (bundleMgr == nullptr) { APP_LOGE("MainThread::handleLaunchApplication GetBundleManager is nullptr"); - return; + return false; } APP_LOGI("MainThread::handleLaunchApplication. End calling GetBundleManager."); @@ -647,7 +620,8 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData) appInfo.bundleName.c_str()); bundleMgr->GetBundleInfo(appInfo.bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); - APP_LOGI("MainThread::handleLaunchApplication moduleResPaths count: %{public}zu start", bundleInfo.moduleResPaths.size()); + APP_LOGI("MainThread::handleLaunchApplication moduleResPaths count: %{public}zu start", + bundleInfo.moduleResPaths.size()); for (auto moduleResPath : bundleInfo.moduleResPaths) { if (!moduleResPath.empty()) { APP_LOGI("MainThread::handleLaunchApplication length: %{public}zu, moduleResPath: %{public}s", @@ -678,28 +652,60 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData) APP_LOGI("MainThread::handleLaunchApplication. Start calling UpdateResConfig."); resourceManager->UpdateResConfig(*resConfig); APP_LOGI("MainThread::handleLaunchApplication. End calling UpdateResConfig."); + return true; +} +/** + * + * @brief Launch the application. + * + * @param appLaunchData The launchdata of the application witch launced. + * + */ +void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData) +{ + APP_LOGI("MainThread::handleLaunchApplication called start."); + if (!CheckForHandleLaunchApplication(appLaunchData)) { + APP_LOGE("MainThread::handleLaunchApplication CheckForHandleLaunchApplication failed"); + return; + } + LoadAbilityLibrary(appLaunchData.GetApplicationInfo().moduleSourceDirs); + LoadAppLibrary(); - APP_LOGI("MainThread::handleLaunchApplication. Start calling initResourceManager."); - contextDeal->initResourceManager(resourceManager); - APP_LOGI("MainThread::handleLaunchApplication. End calling initResourceManager."); + ApplicationInfo appInfo = appLaunchData.GetApplicationInfo(); + ProcessInfo processInfo = appLaunchData.GetProcessInfo(); + Profile appProfile = appLaunchData.GetProfile(); - APP_LOGI("MainThread::handleLaunchApplication. Start calling SetApplicationContext."); - contextDeal->SetApplicationContext(application_); - APP_LOGI("MainThread::handleLaunchApplication. End calling SetApplicationContext."); + std::shared_ptr contextDeal = nullptr; + if (!InitCreate(contextDeal, appInfo, processInfo, appProfile)) { + APP_LOGE("MainThread::handleLaunchApplication InitCreate failed"); + return; + } - APP_LOGI("MainThread::handleLaunchApplication. Start calling AttachBaseContext."); - application_->AttachBaseContext(contextDeal); - APP_LOGI("MainThread::handleLaunchApplication. End calling AttachBaseContext."); + // BMS should set the type (native or ace) of application + bool isNativeApp = true; + std::string appName = isNativeApp ? appInfo.name : aceApplicationName_; + application_ = std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName(appName)); + if (application_ == nullptr) { + APP_LOGE("HandleLaunchApplication::application launch failed"); + return; + } - abilityRecordMgr_ = std::make_shared(); - if (abilityRecordMgr_ == nullptr) { - APP_LOGE("HandleLaunchApplication::application create AbilityRecordMgr failed"); + // init resourceManager. + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); + if (resourceManager == nullptr) { + APP_LOGE("MainThread::handleLaunchApplication create resourceManager failed"); return; } - APP_LOGI("MainThread::handleLaunchApplication. Start calling SetAbilityRecordMgr."); + if (!InitResourceManager(resourceManager, contextDeal, appInfo)) { + APP_LOGE("MainThread::handleLaunchApplication InitResourceManager failed"); + return; + } + + contextDeal->initResourceManager(resourceManager); + contextDeal->SetApplicationContext(application_); + application_->AttachBaseContext(contextDeal); application_->SetAbilityRecordMgr(abilityRecordMgr_); - APP_LOGI("MainThread::handleLaunchApplication. End calling SetAbilityRecordMgr."); applicationImpl_->SetRecordId(appLaunchData.GetRecordId()); applicationImpl_->SetApplication(application_); @@ -1114,6 +1120,7 @@ bool MainThread::IsApplicationReady() const */ void MainThread::LoadAbilityLibrary(const std::vector &libraryPaths) { +#ifdef ABILITY_LIBRARY_LOADER APP_LOGI("MainThread::LoadAbilityLibrary called start"); #ifdef ACEABILITY_LIBRARY_LOADER std::string acelibdir("/system/lib/libace.z.so"); @@ -1163,6 +1170,21 @@ void MainThread::LoadAbilityLibrary(const std::vector &libraryPaths } } APP_LOGI("MainThread::LoadAbilityLibrary called end."); +#endif // ABILITY_LIBRARY_LOADER +} + +void MainThread::LoadAppLibrary() +{ +#ifdef APPLICATION_LIBRARY_LOADER + std::string appPath = applicationLibraryPath; + APP_LOGI("MainThread::handleLaunchApplication Start calling dlopen. appPath=%{public}s", appPath.c_str()); + handleAppLib_ = dlopen(appPath.c_str(), RTLD_NOW | RTLD_GLOBAL); + if (handleAppLib_ == nullptr) { + APP_LOGE("Fail to dlopen %{public}s, [%{public}s]", appPath.c_str(), dlerror()); + exit(-1); + } + APP_LOGI("MainThread::handleLaunchApplication End calling dlopen."; +#endif // APPLICATION_LIBRARY_LOADER } /** diff --git a/kits/appkit/native/app/src/ohos_application.cpp b/kits/appkit/native/app/src/ohos_application.cpp index dd11ac95de1c4ebdb26ffa54fd7812b9d7304a8e..b0155a9a0f2ce9dd7c66ac33fd5e91d8daeb7844 100644 --- a/kits/appkit/native/app/src/ohos_application.cpp +++ b/kits/appkit/native/app/src/ohos_application.cpp @@ -118,13 +118,15 @@ void OHOSApplication::DumpApplication() */ void OHOSApplication::SetAbilityRecordMgr(const std::shared_ptr &abilityRecordMgr) { + APP_LOGI("OHOSApplication::SetAbilityRecordMgr. Start"); if (abilityRecordMgr == nullptr) { APP_LOGE("ContextDeal::SetAbilityRecordMgr failed, abilityRecordMgr is nullptr"); return; } abilityRecordMgr_ = abilityRecordMgr; + APP_LOGI("OHOSApplication::SetAbilityRecordMgr. End"); } - + /** * * Register AbilityLifecycleCallbacks with OHOSApplication diff --git a/kits/appkit/native/test/unittest/application_impl_test.cpp b/kits/appkit/native/test/unittest/application_impl_test.cpp index 0e3729c8b96f6bfb680eb92cd44c44ce878dcfcb..7896d1ec62ab39996444e89ea38f71bc0cfeaaf6 100644 --- a/kits/appkit/native/test/unittest/application_impl_test.cpp +++ b/kits/appkit/native/test/unittest/application_impl_test.cpp @@ -26,13 +26,11 @@ using namespace OHOS::AppExecFwk; class ApplicationImplTest : public testing::Test { public: - ApplicationImplTest() : applicationImpl_(nullptr) + ApplicationImplTest() {} ~ApplicationImplTest() - { - applicationImpl_ = nullptr; - } - ApplicationImpl *applicationImpl_ = nullptr; + {} + std::shared_ptr applicationImpl_ = nullptr; static void SetUpTestCase(void); static void TearDownTestCase(void); void SetUp(); @@ -47,14 +45,11 @@ void ApplicationImplTest::TearDownTestCase(void) void ApplicationImplTest::SetUp(void) { - applicationImpl_ = new (std::nothrow) ApplicationImpl(); + applicationImpl_ = std::make_shared(); } void ApplicationImplTest::TearDown(void) -{ - delete applicationImpl_; - applicationImpl_ = nullptr; -} +{} /** * @tc.number: AppExecFwk_ApplicationImpl_PerformAppReady_0100 diff --git a/kits/appkit/native/test/unittest/application_test.cpp b/kits/appkit/native/test/unittest/application_test.cpp index 08ea6c739764af10fb629e52127af78d47831657..1c476997376b357b051d7d3721f41f3cf925d598 100644 --- a/kits/appkit/native/test/unittest/application_test.cpp +++ b/kits/appkit/native/test/unittest/application_test.cpp @@ -28,13 +28,11 @@ namespace OHOS { namespace AppExecFwk { class ApplicationTest : public testing::Test { public: - ApplicationTest() : ApplicationTest_(nullptr) + ApplicationTest() {} ~ApplicationTest() - { - ApplicationTest_ = nullptr; - } - OHOSApplication *ApplicationTest_ = nullptr; + {} + std::shared_ptr ApplicationTest_ = nullptr; static void SetUpTestCase(void); static void TearDownTestCase(void); void SetUp(); @@ -49,14 +47,11 @@ void ApplicationTest::TearDownTestCase(void) void ApplicationTest::SetUp(void) { - ApplicationTest_ = new (std::nothrow) OHOSApplication(); + ApplicationTest_ = std::make_shared(); } void ApplicationTest::TearDown(void) -{ - delete ApplicationTest_; - ApplicationTest_ = nullptr; -} +{} /** * @tc.number: AppExecFwk_Application_RegisterAbilityLifecycleCallbacks_0100 diff --git a/kits/appkit/native/test/unittest/context_deal_interface1_test.cpp b/kits/appkit/native/test/unittest/context_deal_interface1_test.cpp index aa6da460fe1f77151ff50e7598fddc865bc64d4c..f9bf13577ecc746e996139e84444d12d95b1ab51 100644 --- a/kits/appkit/native/test/unittest/context_deal_interface1_test.cpp +++ b/kits/appkit/native/test/unittest/context_deal_interface1_test.cpp @@ -131,7 +131,6 @@ HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_SetTheme_0100, Functio resourceManager->SetThemeById(testValue, testList); contextDeal->initResourceManager(resourceManager); contextDeal->SetTheme(testValue); - // EXPECT_EQ(testValue, contextDeal->GetHapModuleInfo()->themeId); GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_SetTheme_0100 end"; } @@ -146,7 +145,6 @@ HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_SetTheme_0200, Functio int testValue = 1; std::shared_ptr contextDeal = std::make_shared(); contextDeal->SetTheme(testValue); - // EXPECT_NE(testValue, contextDeal->GetHapModuleInfo()->themeId); GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_SetTheme_0200 end"; } @@ -249,7 +247,6 @@ HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetTheme_0100, Functio contextDeal->initResourceManager(resourceManager); std::map retVal = contextDeal->GetTheme(); - // EXPECT_TRUE((retVal == testList)); GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetTheme_0100 end"; } @@ -279,12 +276,6 @@ HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetString_ById_0100, F HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetString_ByIdAndFormat_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetString_ByIdAndFormat_0100 start"; - // std::shared_ptr resourceManager(Global::Resource::CreateResourceManager2()); - // std::shared_ptr contextDeal = std::make_shared(); - // int testCount = 0; - // std::string testByName = ""; - // std::string retVal = contextDeal->GetString(testCount, testByName); - // EXPECT_TRUE(false); GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetString_ByIdAndFormat_0100 end"; } @@ -410,10 +401,6 @@ HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetColor_0200, Functio HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetThemeId_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetThemeId_0100 start"; - // std::shared_ptr contextDeal = std::make_shared(); - // const int testValue = 1; - // contextDeal->GetHapModuleInfo()->themeId = testValue; - // EXPECT_EQ(testValue, contextDeal->GetThemeId()); GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetThemeId_0100 end"; } diff --git a/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_first.cpp b/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_first.cpp index d1ee4a6c993d50b4eeb93c3dbf3e2ba6b6be0910..3284e86ac4b49e735ac06e77aaf2d6052736e9d8 100644 --- a/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_first.cpp +++ b/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_first.cpp @@ -29,6 +29,8 @@ using namespace testing::ext; using namespace OHOS::AppExecFwk; using namespace OHOS; using namespace OHOS::AAFwk; +const int TestProcessInfo = 9999; +const int USleepTime = 200; class AppkitNativeModuleTestFirst : public testing::Test { public: @@ -70,14 +72,14 @@ void AppkitNativeModuleTestFirst::TearDown(void) GTEST_LOG_(INFO) << "AppkitNativeModuleTestFirst TearDown"; AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleTerminateApplication(); } @@ -93,12 +95,12 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_Start_0100, Function | MediumTest | Le GTEST_LOG_(INFO) << "App_Start_0100 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleTerminateApplication(); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); - usleep(200); + usleep(USleepTime); GTEST_LOG_(INFO) << "App_Start_0100 end"; } @@ -112,7 +114,7 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_Start_0200, Function | MediumTest | Le { GTEST_LOG_(INFO) << "App_Start_0200 start"; runner_->Run(); - usleep(200); + usleep(USleepTime); EXPECT_EQ(false, mockAppMgr->IsAttached()); runner_->Stop(); GTEST_LOG_(INFO) << "App_Start_0200 end"; @@ -132,30 +134,30 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0100, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0100 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleForegroundApplication(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleBackgroundApplication(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleTerminateApplication(); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -174,11 +176,11 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0200, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0200 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleForegroundApplication(); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -197,11 +199,11 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0300, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0300 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleBackgroundApplication(); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -220,11 +222,11 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0400, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0400 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleTerminateApplication(); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -243,22 +245,22 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0500, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0500 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleBackgroundApplication(); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -277,22 +279,22 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0600, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0600 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleTerminateApplication(); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -311,22 +313,22 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0700, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0700 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -345,26 +347,26 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0800, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0800 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleForegroundApplication(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleTerminateApplication(); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -383,26 +385,26 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0900, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0900 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleForegroundApplication(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -421,26 +423,26 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_1000, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1000 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleForegroundApplication(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleForegroundApplication(); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -459,30 +461,30 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_1100, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1100 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleForegroundApplication(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleBackgroundApplication(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -501,30 +503,30 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_1200, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1200 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleForegroundApplication(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleBackgroundApplication(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleForegroundApplication(); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); diff --git a/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_fourth.cpp b/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_fourth.cpp index d41d3d77a5e02ab1fce94aa31ba251f9d5434f5e..5a14d27b09bee5750feb60d1f47751edc5d3352d 100644 --- a/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_fourth.cpp +++ b/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_fourth.cpp @@ -29,7 +29,8 @@ using namespace testing::ext; using namespace OHOS::AppExecFwk; using namespace OHOS; using namespace OHOS::AAFwk; - +const int TestProcessInfo = 9999; +const int USleepTime = 50; class AppkitNativeModuleTestThird : public testing::Test { public: AppkitNativeModuleTestThird() : AppMgrObject_(nullptr), mockAppMgr(nullptr), mockHandler_(nullptr), runner_(nullptr) @@ -70,14 +71,14 @@ void AppkitNativeModuleTestThird::TearDown(void) GTEST_LOG_(INFO) << "AppkitNativeModuleTestThird TearDown"; AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); mockAppMgr->ScheduleTerminateApplication(); } @@ -96,28 +97,28 @@ HWTEST_F(AppkitNativeModuleTestThird, App_CleanAbility_0100, Function | MediumTe GTEST_LOG_(INFO) << "App_CleanAbility_0100 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); AbilityInfo abilityinf; sptr token = new (std::nothrow) MockAbilityToken(); mockAppMgr->ScheduleLaunchAbility(abilityinf, token); - usleep(50); + usleep(USleepTime); mockAppMgr->ScheduleCleanAbility(token); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -138,12 +139,12 @@ HWTEST_F(AppkitNativeModuleTestThird, App_CleanAbility_0200, Function | MediumTe GTEST_LOG_(INFO) << "App_CleanAbility_0200 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); sptr token = new (std::nothrow) MockAbilityToken(); mockAppMgr->ScheduleCleanAbility(token); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -164,23 +165,23 @@ HWTEST_F(AppkitNativeModuleTestThird, App_CleanAbility_0300, Function | MediumTe GTEST_LOG_(INFO) << "App_CleanAbility_0300 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); sptr token = new (std::nothrow) MockAbilityToken(); mockAppMgr->ScheduleCleanAbility(token); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -201,28 +202,28 @@ HWTEST_F(AppkitNativeModuleTestThird, App_CleanAbility_0400, Function | MediumTe GTEST_LOG_(INFO) << "App_CleanAbility_0400 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); AbilityInfo abilityinf; sptr token = new (std::nothrow) MockAbilityToken(); mockAppMgr->ScheduleLaunchAbility(abilityinf, token); - usleep(50); + usleep(USleepTime); mockAppMgr->ScheduleCleanAbility(nullptr); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -243,28 +244,28 @@ HWTEST_F(AppkitNativeModuleTestThird, App_CleanAbility_0500, Function | MediumTe GTEST_LOG_(INFO) << "App_CleanAbility_0500 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); AbilityInfo abilityinf; sptr token = new (std::nothrow) MockAbilityToken(); mockAppMgr->ScheduleLaunchAbility(abilityinf, token); - usleep(50); + usleep(USleepTime); sptr tokenOhter = new (std::nothrow) MockAbilityToken(); mockAppMgr->ScheduleCleanAbility(tokenOhter); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -284,7 +285,7 @@ HWTEST_F(AppkitNativeModuleTestThird, App_ElementsCallbacks_0100, Function | Med GTEST_LOG_(INFO) << "App_ElementsCallbacks_0100 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; @@ -295,20 +296,20 @@ HWTEST_F(AppkitNativeModuleTestThird, App_ElementsCallbacks_0100, Function | Med lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); mockAppMgr->ScheduleShrinkMemory(10); - usleep(50); + usleep(USleepTime); OHOS::AppExecFwk::Configuration config("testConfig"); mockAppMgr->ScheduleConfigurationUpdated(config); - usleep(50); + usleep(USleepTime); mockAppMgr->ScheduleTerminateApplication(); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -332,7 +333,7 @@ HWTEST_F(AppkitNativeModuleTestThird, App_AbilityLifecycleCallbacks_0100, Functi GTEST_LOG_(INFO) << "App_AbilityLifecycleCallbacks_0100 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; @@ -343,7 +344,7 @@ HWTEST_F(AppkitNativeModuleTestThird, App_AbilityLifecycleCallbacks_0100, Functi lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); diff --git a/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_second.cpp b/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_second.cpp index e42c61c8e6cf95ddfd49920f5c5ea8bc44304592..65edcd5018d528e2ee579b99356696d4e25f496d 100644 --- a/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_second.cpp +++ b/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_second.cpp @@ -29,7 +29,8 @@ using namespace testing::ext; using namespace OHOS::AppExecFwk; using namespace OHOS; using namespace OHOS::AAFwk; - +const int TestProcessInfo = 9999; +const int USleepTime = 50; class AppkitNativeModuleTestSecond : public testing::Test { public: AppkitNativeModuleTestSecond() @@ -71,14 +72,14 @@ void AppkitNativeModuleTestSecond::TearDown(void) GTEST_LOG_(INFO) << "AppkitNativeModuleTestSecond TearDown"; AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); mockAppMgr->ScheduleTerminateApplication(); } @@ -95,30 +96,30 @@ HWTEST_F(AppkitNativeModuleTestSecond, App_ApplicationLifeCycle_1300, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1300 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); mockAppMgr->ScheduleForegroundApplication(); - usleep(50); + usleep(USleepTime); mockAppMgr->ScheduleBackgroundApplication(); - usleep(50); + usleep(USleepTime); mockAppMgr->ScheduleBackgroundApplication(); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -137,18 +138,18 @@ HWTEST_F(AppkitNativeModuleTestSecond, App_ApplicationLifeCycle_1400, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1400 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -167,18 +168,18 @@ HWTEST_F(AppkitNativeModuleTestSecond, App_ApplicationLifeCycle_1500, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1500 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -198,18 +199,18 @@ HWTEST_F(AppkitNativeModuleTestSecond, App_LaunchAblity_0100, Function | MediumT GTEST_LOG_(INFO) << "App_LaunchAblity_0100 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); AbilityInfo abilityinf; sptr token = new (std::nothrow) MockAbilityToken(); @@ -233,7 +234,7 @@ HWTEST_F(AppkitNativeModuleTestSecond, App_LaunchAblity_0200, Function | MediumT GTEST_LOG_(INFO) << "App_LaunchAblity_0200 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AbilityInfo abilityinf; sptr token = new (std::nothrow) MockAbilityToken(); @@ -258,18 +259,18 @@ HWTEST_F(AppkitNativeModuleTestSecond, App_LaunchAblity_0300, Function | MediumT GTEST_LOG_(INFO) << "App_LaunchAblity_0300 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); AbilityInfo abilityinf; mockAppMgr->ScheduleLaunchAbility(abilityinf, nullptr); diff --git a/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_third.cpp b/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_third.cpp index 4e21ad58c4bd60cd1ee2c9d840a178830865d8ad..a6d6b603469827de49cc2f9f10fea9ab29bad1ea 100644 --- a/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_third.cpp +++ b/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_third.cpp @@ -29,7 +29,8 @@ using namespace testing::ext; using namespace OHOS::AppExecFwk; using namespace OHOS; using namespace OHOS::AAFwk; - +const int TestProcessInfo = 9999; +const int USleepTime = 50; class AppkitNativeModuleTestThird : public testing::Test { public: AppkitNativeModuleTestThird() : AppMgrObject_(nullptr), mockAppMgr(nullptr), mockHandler_(nullptr), runner_(nullptr) @@ -70,14 +71,14 @@ void AppkitNativeModuleTestThird::TearDown(void) GTEST_LOG_(INFO) << "AppkitNativeModuleTestThird TearDown"; AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); mockAppMgr->ScheduleTerminateApplication(); } @@ -95,7 +96,7 @@ HWTEST_F(AppkitNativeModuleTestThird, App_Context_ApplicationContext_0100, Funct GTEST_LOG_(INFO) << "App_Context_ApplicationContext_0100 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; @@ -110,12 +111,12 @@ HWTEST_F(AppkitNativeModuleTestThird, App_Context_ApplicationContext_0100, Funct lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); - usleep(50); + usleep(USleepTime); GTEST_LOG_(INFO) << "App_Context_ApplicationContext_0100 end"; } } // namespace AppExecFwk diff --git a/libs/libeventhandler/src/event_queue.cpp b/libs/libeventhandler/src/event_queue.cpp index dc1fc3d957a1dab6896a3ecb5de80c15a7eadd2f..c426aef047aca6c65b40d7309eba253fe577d472 100644 --- a/libs/libeventhandler/src/event_queue.cpp +++ b/libs/libeventhandler/src/event_queue.cpp @@ -48,7 +48,7 @@ void RemoveFileDescriptorListenerLocked(std::mapsecond)) { ioWaiter->RemoveFileDescriptor(it->first); it = listeners.erase(it); diff --git a/libs/libeventhandler/src/event_runner.cpp b/libs/libeventhandler/src/event_runner.cpp index 1c635df8ca3e529745924f9c45c686c2c58cb7f1..10cb96c76a397a93f11675c2b8f799e92a6cb3df 100644 --- a/libs/libeventhandler/src/event_runner.cpp +++ b/libs/libeventhandler/src/event_runner.cpp @@ -248,8 +248,8 @@ private: static Avatar avatar_; }; -ThreadCollector::ThreadCollector() : - collectorLock_(), condition_(), reclaims_(), depositMap_(), threadLock_(), thread_(nullptr) +ThreadCollector::ThreadCollector() + : collectorLock_(), condition_(), reclaims_(), depositMap_(), threadLock_(), thread_(nullptr) { // Thread collector is created, so enable avatar. avatarEnabled_ = true; @@ -372,8 +372,8 @@ private: }; } // unnamed namespace -EventInnerRunner::EventInnerRunner(const std::shared_ptr &runner) : - queue_(nullptr), owner_(runner), logger_(nullptr), threadName_(""), threadId_() +EventInnerRunner::EventInnerRunner(const std::shared_ptr &runner) + : queue_(nullptr), owner_(runner), logger_(nullptr), threadName_(""), threadId_() {} std::shared_ptr EventInnerRunner::GetCurrentEventRunner() diff --git a/libs/libeventhandler/src/thread_local_data.h b/libs/libeventhandler/src/thread_local_data.h index 1fd69b8d1f16561c9e8cf4f3fe71ed61b9e239fd..1b2655fdcca0fb8cd33fed3329e7c88e0c1fc3eb 100644 --- a/libs/libeventhandler/src/thread_local_data.h +++ b/libs/libeventhandler/src/thread_local_data.h @@ -27,7 +27,7 @@ namespace AppExecFwk { /* * Tool class, used to save thread local data. */ -template +template class ThreadLocalData { public: ThreadLocalData() = default; diff --git a/libs/test/moduletest/common/event_handler/event_handler_press_module_test.cpp b/libs/test/moduletest/common/event_handler/event_handler_press_module_test.cpp index 49dd92d3000cebb07331776f2d645edc82b5c7c4..3d8f773fff1f9681dca3780ece567085535fe8aa 100644 --- a/libs/test/moduletest/common/event_handler/event_handler_press_module_test.cpp +++ b/libs/test/moduletest/common/event_handler/event_handler_press_module_test.cpp @@ -211,9 +211,9 @@ HWTEST_F(EventHandlerPressModuleTest, FdListenerPress001, TestSize.Level3) auto myRunner = EventRunner::Create(false); auto handler = std::make_shared(myRunner); auto inResult = handler->AddFileDescriptorListener(fds[0], FILE_DESCRIPTOR_INPUT_EVENT, listener); - ASSERT_EQ(inResult, ERR_OK); + EXPECT_EQ(inResult, ERR_OK); auto outResult = handler->AddFileDescriptorListener(fds[1], FILE_DESCRIPTOR_OUTPUT_EVENT, listener); - ASSERT_EQ(outResult, ERR_OK); + EXPECT_EQ(outResult, ERR_OK); int64_t delayTime = 20000; int64_t param = 0; diff --git a/services/appmgr/src/lmks/lmks_utils.cpp b/services/appmgr/src/lmks/lmks_utils.cpp index e64ff67a94b3ff28b39679d74058ac2cdb4dbedc..6c0ea2af75f395bc48d10392f801470c226951fb 100644 --- a/services/appmgr/src/lmks/lmks_utils.cpp +++ b/services/appmgr/src/lmks/lmks_utils.cpp @@ -108,7 +108,7 @@ std::string LmksUtils::GetProcName(pid_t pid) return name; } - if (strlen(line) < PROC_LINE_MAX && strlen(line) != 0) { + if (strlen(line) + 1 <= PROC_LINE_MAX && strlen(line) != 0) { name = line; } else { HiLog::Error(LABEL, "cmdline no data"); @@ -160,7 +160,7 @@ int LmksUtils::GetProcSize(pid_t pid) return -1; } - if ((strlen(line) < PROC_LINE_MAX && strlen(line) != 0) && (sscanf_s(line, "%d %d ", &total, &rss) > 0)) { + if ((strlen(line) + 1 <= PROC_LINE_MAX && strlen(line) != 0) && (sscanf_s(line, "%d %d ", &total, &rss) > 0)) { HiLog::Info(LABEL, "pid %{public}d total %{public}d rss %{public}d", pid, total, rss); } else { HiLog::Error(LABEL, "strlen or sscanf_s err %{public}s", strerror(errno)); diff --git a/services/appmgr/src/process_optimizer.cpp b/services/appmgr/src/process_optimizer.cpp index 92607f83779af36f13366e67ced0f192ee48c19e..bc5c3dca6d01747237606d7c77946e1967668e73 100644 --- a/services/appmgr/src/process_optimizer.cpp +++ b/services/appmgr/src/process_optimizer.cpp @@ -709,11 +709,6 @@ void ProcessOptimizer::SetAppFreezingTime(int time) suspendTimeout_ = time; // convert seconds to milliseconds suspendTimeout_ *= TIME_ADVANCE_RATE; - if (suspendTimeout_ > INT_MAX) { - suspendTimeout_ = APP_SUSPEND_TIMEOUT_DEFAULT; - APP_LOGE("data overflow"); - return; - } } void ProcessOptimizer::GetAppFreezingTime(int &time) diff --git a/services/bundlemgr/include/common_profile.h b/services/bundlemgr/include/common_profile.h index 98624b7cf375907f0f1627e9d891d23bd9b2caee..b061ba67a2e425b303e1af7e78f958f145b1ffda 100644 --- a/services/bundlemgr/include/common_profile.h +++ b/services/bundlemgr/include/common_profile.h @@ -119,6 +119,7 @@ const std::string BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_WHEN = "when"; const std::string BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_WHEN_INUSE = "inuse"; const std::string BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_WHEN_ALWAYS = "always"; const std::string BUNDLE_MODULE_PROFILE_KEY_CUSTOMIZE_DATA = "customizeData"; +const std::string BUNDLE_MODULE_PROFILE_KEY_MAIN_ABILITY = "mainAbility"; // sub BUNDLE_MODULE_PROFILE_KEY_DISTRO const std::string BUNDLE_MODULE_PROFILE_KEY_DELIVERY_WITH_INSTALL = "deliveryWithInstall"; const std::string BUNDLE_MODULE_PROFILE_KEY_MODULE_NAME = "moduleName"; diff --git a/services/bundlemgr/include/inner_bundle_info.h b/services/bundlemgr/include/inner_bundle_info.h index f1c6749a20a927712da1a28f886b4ce0cb86e70d..437c66faa7982ead1c3f287aae18c3ba21a6202c 100644 --- a/services/bundlemgr/include/inner_bundle_info.h +++ b/services/bundlemgr/include/inner_bundle_info.h @@ -71,6 +71,7 @@ struct InnerModuleInfo { int32_t labelId = 0; std::string description; int32_t descriptionId = 0; + std::string mainAbility; bool isEntry; bool installationFree; MetaData metaData; @@ -892,7 +893,7 @@ public: void SetProvisionId(const std::string &provisionId) { - baseBundleInfo_.appId = provisionId; + baseBundleInfo_.appId = baseBundleInfo_.name + Constants::FILE_UNDERLINE + provisionId; } std::string GetProvisionId() const diff --git a/services/bundlemgr/src/base_bundle_installer.cpp b/services/bundlemgr/src/base_bundle_installer.cpp index 023be8c65e14d3771b462f7b6b3c4d19fd261922..31d8536dd88347005dff63141025a77287aeef24 100755 --- a/services/bundlemgr/src/base_bundle_installer.cpp +++ b/services/bundlemgr/src/base_bundle_installer.cpp @@ -700,7 +700,7 @@ bool BaseBundleInstaller::ModifyInstallDirByHapType(InnerBundleInfo &info) bool BaseBundleInstaller::UpdateBundlePaths(InnerBundleInfo &info, const std::string baseDataPath) const { info.SetBaseDataDir(baseDataPath); - info.SetAppDataDir(baseDataPath + Constants::PATH_SEPARATOR + Constants::DATA_DIR); + info.SetAppDataDir(baseDataPath); info.SetAppDataBaseDir(baseDataPath + Constants::PATH_SEPARATOR + Constants::DATA_BASE_DIR); info.SetAppCacheDir(baseDataPath + Constants::PATH_SEPARATOR + Constants::CACHE_DIR); return true; diff --git a/services/bundlemgr/src/bundle_profile.cpp b/services/bundlemgr/src/bundle_profile.cpp index a5069a1594a7df9733aac35be17347223a6a45e7..4ef30a7e14a61265df5e4633a0b0ce5cbc4c57a4 100644 --- a/services/bundlemgr/src/bundle_profile.cpp +++ b/services/bundlemgr/src/bundle_profile.cpp @@ -273,6 +273,7 @@ struct Module { std::vector shortcuts; std::vector defPermissions; std::vector reqPermissions; + std::string mainAbility; }; // config.json @@ -1626,6 +1627,14 @@ void from_json(const nlohmann::json &jsonObject, Module &module) false, parseResult, ArrayType::OBJECT); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + BUNDLE_MODULE_PROFILE_KEY_MAIN_ABILITY, + module.mainAbility, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); } void from_json(const nlohmann::json &jsonObject, ConfigJson &configJson) @@ -1886,6 +1895,7 @@ bool TransformToInfo(const ProfileReader::ConfigJson &configJson, InnerModuleInf innerModuleInfo.reqCapabilities = configJson.module.reqCapabilities; innerModuleInfo.defPermissions = configJson.module.defPermissions; innerModuleInfo.reqPermissions = configJson.module.reqPermissions; + innerModuleInfo.mainAbility = configJson.module.mainAbility; return true; } diff --git a/services/bundlemgr/src/inner_bundle_info.cpp b/services/bundlemgr/src/inner_bundle_info.cpp index 5e6bd27c983e003a1b7329b67f26637f19e349e1..7d66d2a40292a093245f2dad1eadecf1d4d241ed 100644 --- a/services/bundlemgr/src/inner_bundle_info.cpp +++ b/services/bundlemgr/src/inner_bundle_info.cpp @@ -58,6 +58,7 @@ const std::string MODULE_ABILITY_KEYS = "abilityKeys"; const std::string MODULE_SKILL_KEYS = "skillKeys"; const std::string MODULE_FORMS = "formInfos"; const std::string MODULE_SHORTCUT = "shortcutInfos"; +const std::string MODULE_MAIN_ABILITY = "mainAbility"; } // namespace @@ -73,7 +74,7 @@ InnerBundleInfo::~InnerBundleInfo() void to_json(nlohmann::json &jsonObject, const Distro &distro) { - jsonObject = nlohmann::json{ + jsonObject = nlohmann::json { {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DELIVERY_WITH_INSTALL, distro.deliveryWithInstall}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_MODULE_NAME, distro.moduleName}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_MODULE_TYPE, distro.moduleType}, @@ -83,7 +84,7 @@ void to_json(nlohmann::json &jsonObject, const Distro &distro) void to_json(nlohmann::json &jsonObject, const UsedScene &usedScene) { - jsonObject = nlohmann::json{ + jsonObject = nlohmann::json { {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_ABILITY, usedScene.ability}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_WHEN, usedScene.when} }; @@ -91,7 +92,7 @@ void to_json(nlohmann::json &jsonObject, const UsedScene &usedScene) void to_json(nlohmann::json &jsonObject, const ReqPermission &reqPermission) { - jsonObject = nlohmann::json{ + jsonObject = nlohmann::json { {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_NAME, reqPermission.name}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_REASON, reqPermission.reason}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_USEDSCENE, reqPermission.usedScene} @@ -100,7 +101,7 @@ void to_json(nlohmann::json &jsonObject, const ReqPermission &reqPermission) void to_json(nlohmann::json &jsonObject, const DefPermission &defPermission) { - jsonObject = nlohmann::json{ + jsonObject = nlohmann::json { {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_NAME, defPermission.name}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_GRANTMODE, defPermission.grantMode}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_AVAILABLESCOPE, defPermission.availableScope}, @@ -113,7 +114,7 @@ void to_json(nlohmann::json &jsonObject, const DefPermission &defPermission) void to_json(nlohmann::json &jsonObject, const InnerModuleInfo &info) { - jsonObject = nlohmann::json{ + jsonObject = nlohmann::json { {MODULE_PACKAGE, info.modulePackage}, {MODULE_NAME, info.moduleName}, {MODULE_PATH, info.modulePath}, @@ -132,13 +133,14 @@ void to_json(nlohmann::json &jsonObject, const InnerModuleInfo &info) {MODULE_REQ_PERMS, info.reqPermissions}, {MODULE_DEF_PERMS, info.defPermissions}, {MODULE_ABILITY_KEYS, info.abilityKeys}, - {MODULE_SKILL_KEYS, info.skillKeys} + {MODULE_SKILL_KEYS, info.skillKeys}, + {MODULE_MAIN_ABILITY, info.mainAbility} }; } void to_json(nlohmann::json &jsonObject, const SkillUri &uri) { - jsonObject = nlohmann::json{ + jsonObject = nlohmann::json { {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_SCHEME, uri.scheme}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_HOST, uri.host}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_PORT, uri.port}, @@ -149,7 +151,7 @@ void to_json(nlohmann::json &jsonObject, const SkillUri &uri) void to_json(nlohmann::json &jsonObject, const Skill &skill) { - jsonObject = nlohmann::json{ + jsonObject = nlohmann::json { {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_ACTIONS, skill.actions}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_ENTITIES, skill.entities}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_URIS, skill.uris} @@ -174,7 +176,7 @@ void InnerBundleInfo::ToJson(nlohmann::json &jsonObject) const jsonObject[MAIN_ABILITY] = mainAbility_; jsonObject[APP_FEATURE] = appFeature_; jsonObject[HAS_ENTRY] = hasEntry_; - jsonObject[MODULE_FORMS] = formInfos_; + jsonObject[MODULE_FORMS] = formInfos_; jsonObject[MODULE_SHORTCUT] = shortcutInfos_; } @@ -286,6 +288,14 @@ void from_json(const nlohmann::json &jsonObject, InnerModuleInfo &info) false, ProfileReader::parseResult, ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + MODULE_MAIN_ABILITY, + info.mainAbility, + JsonType::STRING, + false, + ProfileReader::parseResult, + ArrayType::NOT_ARRAY); GetValueIfFindKey(jsonObject, jsonObjectEnd, MODULE_DESCRIPTION_INSTALLATION_FREE, @@ -685,7 +695,7 @@ int32_t InnerBundleInfo::FromJson(const nlohmann::json &jsonObject) true, ProfileReader::parseResult, ArrayType::NOT_ARRAY); - GetValueIfFindKey>>(jsonObject, + GetValueIfFindKey>>(jsonObject, jsonObjectEnd, MODULE_FORMS, formInfos_, @@ -742,6 +752,7 @@ std::optional InnerBundleInfo::FindHapModuleInfo(const std::strin hapInfo.supportedModes = baseApplicationInfo_.supportedModes; hapInfo.reqCapabilities = it->second.reqCapabilities; hapInfo.colorMode = it->second.colorMode; + hapInfo.mainAbility = it->second.mainAbility; bool first = false; for (auto &ability : baseAbilityInfos_) { if (ability.first.find(modulePackage) != std::string::npos) { @@ -848,7 +859,11 @@ void InnerBundleInfo::UpdateModuleInfo(const InnerBundleInfo &newInfo) } } for (auto it = shortcutInfos_.begin(); it != shortcutInfos_.end();) { - (it->first.find(newInfo.currentPackage_) != std::string::npos) ? shortcutInfos_.erase(it++) : (++it); + if (it->first.find(newInfo.currentPackage_) != std::string::npos) { + shortcutInfos_.erase(it++); + } else { + ++it; + } } if (!hasEntry_ && newInfo.HasEntry()) { hasEntry_ = true; @@ -873,19 +888,39 @@ void InnerBundleInfo::RemoveModuleInfo(const std::string &modulePackage) mainAbility_.clear(); } for (auto it = innerModuleInfos_.begin(); it != innerModuleInfos_.end();) { - (it->first == modulePackage) ? innerModuleInfos_.erase(it++) : (++it); + if (it->first == modulePackage) { + innerModuleInfos_.erase(it++); + } else { + ++it; + } } for (auto it = baseAbilityInfos_.begin(); it != baseAbilityInfos_.end();) { - (it->first.find(modulePackage) != std::string::npos) ? baseAbilityInfos_.erase(it++) : (++it); + if (it->first.find(modulePackage) != std::string::npos) { + baseAbilityInfos_.erase(it++); + } else { + ++it; + } } for (auto it = skillInfos_.begin(); it != skillInfos_.end();) { - (it->first.find(modulePackage) != std::string::npos) ? skillInfos_.erase(it++) : (++it); + if (it->first.find(modulePackage) != std::string::npos) { + skillInfos_.erase(it++); + } else { + ++it; + } } for (auto it = formInfos_.begin(); it != formInfos_.end();) { - (it->first.find(modulePackage) != std::string::npos) ? formInfos_.erase(it++) : (++it); + if (it->first.find(modulePackage) != std::string::npos) { + formInfos_.erase(it++); + } else { + ++it; + } } for (auto it = shortcutInfos_.begin(); it != shortcutInfos_.end();) { - (it->first.find(modulePackage) != std::string::npos) ? shortcutInfos_.erase(it++) : (++it); + if (it->first.find(modulePackage) != std::string::npos) { + shortcutInfos_.erase(it++); + } else { + ++it; + } } } @@ -948,10 +983,16 @@ void InnerBundleInfo::GetBundleInfo(const BundleFlag flag, BundleInfo &bundleInf std::back_inserter(bundleInfo.defPermissions), [](const auto &p) { return p.name; }); bundleInfo.hapModuleNames.emplace_back(info.second.modulePackage); - bundleInfo.moduleNames.emplace_back(info.second.moduleName); - bundleInfo.moduleDirs.emplace_back(info.second.modulePath); - bundleInfo.modulePublicDirs.emplace_back(info.second.moduleDataDir); - bundleInfo.moduleResPaths.emplace_back(info.second.moduleResPath); + auto hapmoduleinfo = FindHapModuleInfo(info.second.modulePackage); + if (hapmoduleinfo) { + bundleInfo.hapModuleInfos.emplace_back(*hapmoduleinfo); + bundleInfo.moduleNames.emplace_back(info.second.moduleName); + bundleInfo.moduleDirs.emplace_back(info.second.modulePath); + bundleInfo.modulePublicDirs.emplace_back(info.second.moduleDataDir); + bundleInfo.moduleResPaths.emplace_back(info.second.moduleResPath); + } else { + APP_LOGE("can not find hapmoduleinfo %{public}s", info.second.moduleName.c_str()); + } if (info.second.isEntry) { bundleInfo.mainEntry = info.second.modulePackage; bundleInfo.entryModuleName = info.second.moduleName; @@ -982,28 +1023,28 @@ bool InnerBundleInfo::CheckSpecialMetaData(const std::string &metaData) const void InnerBundleInfo::GetFormsInfoByModule(const std::string &moduleName, std::vector &formInfos) const { - for (const auto &data : formInfos_) { - for (auto &form : data.second) { - if (form.moduleName == moduleName) { - formInfos.emplace_back(form); - } - } + for (const auto &data : formInfos_) { + for (auto &form : data.second) { + if (form.moduleName == moduleName) { + formInfos.emplace_back(form); + } + } } } void InnerBundleInfo::GetFormsInfoByApp(std::vector &formInfos) const { - for (const auto &data : formInfos_) { - for (auto &form : data.second) { - formInfos.emplace_back(form); - } + for (const auto &data : formInfos_) { + for (auto &form : data.second) { + formInfos.emplace_back(form); + } } } void InnerBundleInfo::GetShortcutInfos(std::vector &shortcutInfos) const { for (const auto &shortcut : shortcutInfos_) { - shortcutInfos.emplace_back(shortcut.second); + shortcutInfos.emplace_back(shortcut.second); } } diff --git a/services/bundlemgr/src/kvstore_death_recipient_callback.cpp b/services/bundlemgr/src/kvstore_death_recipient_callback.cpp index 3b1eb834f4b88b23da6b25156fb37dd1cb254896..92d4f9de455a653d45ac54ae0f3a4c17da60c21e 100644 --- a/services/bundlemgr/src/kvstore_death_recipient_callback.cpp +++ b/services/bundlemgr/src/kvstore_death_recipient_callback.cpp @@ -27,9 +27,9 @@ namespace AppExecFwk { namespace { const int32_t CHECK_TIMES = 300; -const int32_t CHECK_INTERVAL = 100000; // 100ms +const int32_t CHECK_INTERVAL = 100000; // 100ms -} // namespace +} // namespace KvStoreDeathRecipientCallback::KvStoreDeathRecipientCallback() { @@ -63,13 +63,7 @@ void KvStoreDeathRecipientCallback::OnRemoteDied() // init kvStore. if (dataStorage && dataStorage->ResetKvStore()) { // register data change listener again. - //dataStorage->RegisterChangeListener(); APP_LOGI("current times is %{public}d", times); - // auto service = DelayedSingleton::GetInstance(); - // std::shared_ptr handler = service->GetEventHandler(); - // if (handler != nullptr) { - // handler->SendEvent(BMSEventHandler::BUNDLE_SCAN_START); - // } break; } usleep(CHECK_INTERVAL); @@ -79,5 +73,5 @@ void KvStoreDeathRecipientCallback::OnRemoteDied() APP_LOGI("OnRemoteDied, register data change listener end"); } -} // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/bundlemgr/src/module_usage_data_storage.cpp b/services/bundlemgr/src/module_usage_data_storage.cpp index 5044b12a8f23c9e0e55051b3471ddbddd2efdedf..40787115fe6ecd1125d79466766f369cbb750550 100644 --- a/services/bundlemgr/src/module_usage_data_storage.cpp +++ b/services/bundlemgr/src/module_usage_data_storage.cpp @@ -31,7 +31,6 @@ using namespace OHOS::DistributedKv; namespace OHOS { namespace AppExecFwk { namespace { - const int32_t MAX_TIMES = 6000; // tem min const int32_t SLEEP_INTERVAL = 100 * 1000; // 100ms const std::string POUND_KEY_SEPARATOR = "#"; @@ -96,8 +95,7 @@ void ModuleUsageRecordStorage::AbilityRecordToKey(const std::string &userId, con void ModuleUsageRecordStorage::UpdateUsageRecord(const std::string &jsonString, ModuleUsageRecord &data) { - nlohmann::json jsonObject; - jsonObject = nlohmann::json::parse(jsonString); + nlohmann::json jsonObject = nlohmann::json::parse(jsonString); if (jsonObject.is_discarded()) { APP_LOGE("failed to parse existing usage record: %{private}s.", jsonString.c_str()); return; diff --git a/services/formmgr/BUILD.gn b/services/formmgr/BUILD.gn index 9036ae87b33c76b545e193eaaee5fa0418013de1..1ea0f1282196c4a211a6ac9684ecf7344db72ddb 100644 --- a/services/formmgr/BUILD.gn +++ b/services/formmgr/BUILD.gn @@ -19,6 +19,8 @@ config("formmgr_config") { "include", "//third_party/json/include", "//utils/system/safwk/native/include", + + # "//base/miscservices/time/interfaces/innerkits/include", ] cflags_cc = [ "-fexceptions" ] } @@ -83,27 +85,31 @@ ohos_shared_library("libfms") { } deps = [ "${appexecfwk_path}/common:libappexecfwk_common", - "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", - "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${libs_path}/libeventhandler:libeventhandler_target", - "//base/powermgr/power_manager/interfaces/innerkits:powermgr_client", - "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", - "//foundation/aafwk/standard/interfaces/innerkits/base:base", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", - "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", - "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//base/miscservices/time/services:time_service", + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", "//utils/native/base:utils", # "//third_party/libuuid:libuuid_static", ] external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", "ces_standard:cesfwk_core", "ces_standard:cesfwk_innerkits", + "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "os_account_standard:libaccountkits", + "os_account_standard:libaccountkits", + "permission_standard:libpermissionsdk_standard", + "power_manager_native:powermgr_client", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", ] subsystem_name = "appexecfwk" diff --git a/services/formmgr/include/form_ability_connection.h b/services/formmgr/include/form_ability_connection.h index 8794c9ffa754e2a9b38d7c838e106fed6a531a71..0cf36c49c5d58b2888dcdffe1173cbcefc74fd0a 100644 --- a/services/formmgr/include/form_ability_connection.h +++ b/services/formmgr/include/form_ability_connection.h @@ -1,86 +1,97 @@ -/* - * 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_SERVICES_FORMMGR_INCLUDE_FORM_ABILITY_CONNECTION_H -#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ABILITY_CONNECTION_H - -#include "event_handler.h" -#include "form_item_info.h" -#include "provider_connect_stub.h" -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -using WantParams = OHOS::AAFwk::WantParams; - -/** - * @class FormAbilityConnection - * Form Ability Connection Stub. - */ -class FormAbilityConnection : public ProviderConnectStub { -public: - FormAbilityConnection() = default; - virtual ~FormAbilityConnection() = default; - - /** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * @param element service ability's ElementName. - * @param remoteObject the session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - */ - virtual void OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; - - /** - * @brief OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. - * @param element service ability's ElementName. - * @param resultCode ERR_OK on success, others on failure. - */ - virtual void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; - - /** - * @brief remote object died event. - * @param remoteObject the remote object of service ability. - */ - void OnConnectDied(const wptr &remoteObject); - - /** - * @brief Get connectId. - * @return The ability connection id. - */ - long GetConnectId(); - - /** - * @brief Set connectId. - * @param connectId The ability connection id. - */ - void SetConnectId(long connectId); - - // std::string GetProviderKey(); - -private: - int64_t formId_; - std::string deviceId_; - std::string bundleName_; - std::string abilityName_; - bool isFreeInstall_; - long connectId_ = 0; - - DISALLOW_COPY_AND_MOVE(FormAbilityConnection); -}; -} // namespace AppExecFwk -} // namespace OHOS - +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ABILITY_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ABILITY_CONNECTION_H + +#include "event_handler.h" +#include "form_item_info.h" +#include "provider_connect_stub.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using WantParams = OHOS::AAFwk::WantParams; + +/** + * @class FormAbilityConnection + * Form Ability Connection Stub. + */ +class FormAbilityConnection : public ProviderConnectStub { +public: + FormAbilityConnection() = default; + virtual ~FormAbilityConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + virtual void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + + /** + * @brief OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * @param element service ability's ElementName. + * @param resultCode ERR_OK on success, others on failure. + */ + virtual void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; + + /** + * @brief remote object died event. + * @param remoteObject the remote object of service ability. + */ + void OnConnectDied(const wptr &remoteObject); + + /** + * @brief Get connectId. + * @return The ability connection id. + */ + long GetConnectId(); + + /** + * @brief Set connectId. + * @param connectId The ability connection id. + */ + void SetConnectId(long connectId); + /** + * @brief Get the provider Key + * + * @return The provider Key + */ + std::string GetProviderKey(); + /** + * @brief Set the Provider Key + * + * @param bundleName bundleName + * @param abilityName abilityName + */ + void SetProviderKey(const std::string &bundleName, const std::string &abilityName); + +private: + int64_t formId_ = 0; + std::string deviceId_ = ""; + std::string bundleName_ = ""; + std::string abilityName_ = ""; + bool isFreeInstall_ = false; + long connectId_ = 0; + + DISALLOW_COPY_AND_MOVE(FormAbilityConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + #endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ABILITY_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_ams_helper.h b/services/formmgr/include/form_ams_helper.h index 1d554279be383ef37223b2c09dda5b37572b1003..effd42988ebcc115da1cadd16b48fc37a0bd55a8 100644 --- a/services/formmgr/include/form_ams_helper.h +++ b/services/formmgr/include/form_ams_helper.h @@ -20,13 +20,13 @@ #include #include "ability_connect_callback_interface.h" #include "ability_manager_interface.h" +#include "event_handler.h" #include "iremote_object.h" #include "uri.h" namespace OHOS { namespace AppExecFwk { using IAbilityConnection = OHOS::AAFwk::IAbilityConnection; -using IAbilityManager = OHOS::AAFwk::IAbilityManager; using Want = OHOS::AAFwk::Want; /** * @class FormAmsHelper @@ -36,12 +36,19 @@ class FormAmsHelper final : public DelayedRefSingleton { DECLARE_DELAYED_REF_SINGLETON(FormAmsHelper) public: DISALLOW_COPY_AND_MOVE(FormAmsHelper); - + /** + * @brief SetEventHandler. + * @param handler event handler + */ + inline void SetEventHandler(const std::shared_ptr &handler) + { + eventHandler_ = handler; + } /** * @brief acquire a form ability manager if it not existed, * @return returns the ability manager ipc object or nullptr for failed. */ - sptr GetAbilityManager(); + sptr GetAbilityManager(); /** * @brief Connect session with service ability. * @param want Special want for service type's ability. @@ -49,21 +56,36 @@ public: * @return Returns ERR_OK on success, others on failure. */ ErrCode ConnectServiceAbility( - const Want &want, const sptr &connect); + const Want &want, const sptr &connect); /** * @brief Disconnect session with service ability. * @param want Special want for service type's ability. * @param connect Callback used to notify caller the result of connecting or disconnecting. * @return Returns ERR_OK on success, others on failure. */ - ErrCode DisConnectServiceAbility(const sptr &connect); + ErrCode DisConnectServiceAbility(const sptr &connect); + /** + * @brief Disconnect ability delay, disconnect session with service ability. + * @param want Special want for service type's ability. + * @param connect Callback used to notify caller the result of connecting or disconnecting. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode DisConnectServiceAbilityDelay(const sptr &connect); /** * @brief Add the ability manager instance for debug. * @param abilityManager the ability manager ipc object. */ void SetAbilityManager(const sptr &abilityManager); +private: + /** + * @brief Disconnect ability task, disconnect session with service ability. + * @param want Special want for service type's ability. + * @param connect Callback used to notify caller the result of connecting or disconnecting. + */ + void DisConnectAbilityTask(const sptr &connect); private: sptr abilityManager_ = nullptr; + std::shared_ptr eventHandler_ = nullptr; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/services/formmgr/include/form_batch_delete_connection.h b/services/formmgr/include/form_batch_delete_connection.h index 93dcf7cda997dad7912c3c5db239a265dd16e568..2f0ca0bafb4bd3450affd2ac37dc2692de7e623d 100644 --- a/services/formmgr/include/form_batch_delete_connection.h +++ b/services/formmgr/include/form_batch_delete_connection.h @@ -32,7 +32,8 @@ using WantParams = OHOS::AAFwk::WantParams; */ class FormBatchDeleteConnection : public FormAbilityConnection { public: - FormBatchDeleteConnection(const std::set &formIds); + FormBatchDeleteConnection(const std::set &formIds, const std::string &bundleName, + const std::string &abilityName); virtual ~FormBatchDeleteConnection() = default; /** diff --git a/services/formmgr/include/form_bms_helper.h b/services/formmgr/include/form_bms_helper.h index 8d377a18261503489b0f98a534fabc9bfedaef8d..4e5523ba3bc681a495af091c8a76ca6f767a5ad7 100644 --- a/services/formmgr/include/form_bms_helper.h +++ b/services/formmgr/include/form_bms_helper.h @@ -24,8 +24,6 @@ namespace OHOS { namespace AppExecFwk { -using IAbilityConnection = OHOS::AAFwk::IAbilityConnection; -using IAbilityManager = OHOS::AAFwk::IAbilityManager; using Want = OHOS::AAFwk::Want; /** diff --git a/services/formmgr/include/form_cast_temp_connection.h b/services/formmgr/include/form_cast_temp_connection.h index d0892a79548e09afa115202a2e5185aed65493d9..6a930ceca8a75c31d3f4d27e5134804c114af1eb 100644 --- a/services/formmgr/include/form_cast_temp_connection.h +++ b/services/formmgr/include/form_cast_temp_connection.h @@ -1,49 +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. - */ - -#ifndef FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_CAST_TEMP_CONNECTION_H -#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_CAST_TEMP_CONNECTION_H - -#include "event_handler.h" -#include "form_ability_connection.h" - -namespace OHOS { -namespace AppExecFwk { -/** - * @class FormCastTempConnection - * Cast temp form Connection Stub. - */ -class FormCastTempConnection : public FormAbilityConnection { -public: - FormCastTempConnection(const int64_t formId); - virtual ~FormCastTempConnection() = default; - - /** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * @param element service ability's ElementName. - * @param remoteObject the session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - */ - void OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; - -private: - int64_t formId_; - DISALLOW_COPY_AND_MOVE(FormCastTempConnection); -}; -} // namespace AppExecFwk -} // namespace OHOS - +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_CAST_TEMP_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_CAST_TEMP_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormCastTempConnection + * Cast temp form Connection Stub. + */ +class FormCastTempConnection : public FormAbilityConnection { +public: + FormCastTempConnection(const int64_t formId, const std::string &bundleName, + const std::string &abilityName); + virtual ~FormCastTempConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + int64_t formId_; + DISALLOW_COPY_AND_MOVE(FormCastTempConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + #endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_CAST_TEMP_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_data_mgr.h b/services/formmgr/include/form_data_mgr.h index d4eb6d02cb72333e4e1afdd22a3686c2d74dcae3..b8114dc3aef1b031452e52c456c7caf66760a8a2 100644 --- a/services/formmgr/include/form_data_mgr.h +++ b/services/formmgr/include/form_data_mgr.h @@ -68,23 +68,6 @@ public: * @param removedFormIds The id list of the forms. */ void CleanHostRemovedForms(const std::vector &removedFormIds); - /** - * @brief Delete form js info by form record. - * @return Returns all form records map. - */ - std::map &GetAllFormRecord(); - - /** - * @brief Get all form client host record. - * @return Returns all form client host record. - */ - std::vector &GetClientRecords(); - - /** - * @brief Get all form host records. - * @return Returns all form host records vector. - */ - std::vector &GetAllFormHostRecord(); /** * @brief Allot form host record by caller token. * @param info The form item info. @@ -339,7 +322,14 @@ public: * @param foundFormsMap Form Id list. */ void GetNoHostTempForms(const int uid, std::map> &noHostTempFormsMap, - std::map &foundFormsMap); + std::map &foundFormsMap); + + /** + * @brief Update form for host clients. + * @param formId The Id of the form. + * @param formProviderInfo FormProviderInfo object + */ + void UpdateFormProviderInfo(const int64_t formId, const FormProviderInfo &formProviderInfo); private: /** * @brief Create form record. @@ -376,7 +366,7 @@ private: * @param record The form record. * @param info form item info. */ - void ParseAtTimerConfig(FormRecord record, const FormItemInfo &info) const; + void ParseAtTimerConfig(FormRecord &record, const FormItemInfo &info) const; /** * @brief Get the temp forms from host and delete temp form in cache. * @param record The form record. diff --git a/services/formmgr/include/form_delete_connection.h b/services/formmgr/include/form_delete_connection.h index 4da0e284061263ea6f9f370153e3ed5e5a01fd90..329b56d677377cb2d57893b95d779c1e4c934e2a 100644 --- a/services/formmgr/include/form_delete_connection.h +++ b/services/formmgr/include/form_delete_connection.h @@ -1,51 +1,51 @@ -/* - * 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_SERVICES_FORMMGR_INCLUDE_FORM_DELETE_CONNECTION_H -#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DELETE_CONNECTION_H - -#include "event_handler.h" -#include "form_ability_connection.h" - -namespace OHOS { -namespace AppExecFwk { - -/** - * @class FormDeleteConnection - * Form Delete Connection Stub. - */ -class FormDeleteConnection : public FormAbilityConnection { -public: - FormDeleteConnection(const int64_t formId); - virtual ~FormDeleteConnection() = default; - - /** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * @param element service ability's ElementName. - * @param remoteObject the session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - */ - void OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; - -private: - int64_t formId_; - DISALLOW_COPY_AND_MOVE(FormDeleteConnection); -}; - -} // namespace AppExecFwk -} // namespace OHOS - +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DELETE_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DELETE_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" + +namespace OHOS { +namespace AppExecFwk { + +/** + * @class FormDeleteConnection + * Form Delete Connection Stub. + */ +class FormDeleteConnection : public FormAbilityConnection { +public: + FormDeleteConnection(const int64_t formId, const std::string &bundleName, const std::string &abilityName); + virtual ~FormDeleteConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + int64_t formId_; + DISALLOW_COPY_AND_MOVE(FormDeleteConnection); +}; + +} // namespace AppExecFwk +} // namespace OHOS + #endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DELETE_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_event_notify_connection.h b/services/formmgr/include/form_event_notify_connection.h index f06043a118fb0d6e97daffa69791431037b09ba4..88a51f43da110e7047d7bd34bd68314edbd737bb 100644 --- a/services/formmgr/include/form_event_notify_connection.h +++ b/services/formmgr/include/form_event_notify_connection.h @@ -1,53 +1,54 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_EVENT_NOTIFY_CONNECTION_H -#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_EVENT_NOTIFY_CONNECTION_H - -#include "event_handler.h" -#include "form_ability_connection.h" -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -using Want = OHOS::AAFwk::Want; -/** - * @class FormEventNotifyConnection - * Form Event Notify Connection Stub. - */ -class FormEventNotifyConnection : public FormAbilityConnection { -public: - FormEventNotifyConnection(const std::vector formEvents, const int32_t formVisibleType); - virtual ~FormEventNotifyConnection() = default; - - /** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * - * @param element service ability's ElementName. - * @param remoteObject the session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - */ - void OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; - -private: - std::vector formEvents_; - int32_t formVisibleType_; - DISALLOW_COPY_AND_MOVE(FormEventNotifyConnection); -}; -} // namespace AppExecFwk -} // namespace OHOS - +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_EVENT_NOTIFY_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_EVENT_NOTIFY_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +/** + * @class FormEventNotifyConnection + * Form Event Notify Connection Stub. + */ +class FormEventNotifyConnection : public FormAbilityConnection { +public: + FormEventNotifyConnection(const std::vector formEvents, const int32_t formVisibleType, + const std::string &bundleName, const std::string &abilityName); + virtual ~FormEventNotifyConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + std::vector formEvents_; + int32_t formVisibleType_; + DISALLOW_COPY_AND_MOVE(FormEventNotifyConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + #endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_EVENT_NOTIFY_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_host_record.h b/services/formmgr/include/form_host_record.h index 79e0869f7ba97a426680d979d15f8a89b1fbd025..4d4b5ee895858af2cfedb97328f436ad1367429f 100644 --- a/services/formmgr/include/form_host_record.h +++ b/services/formmgr/include/form_host_record.h @@ -1,202 +1,202 @@ -/* - * 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_SERVICES_FORMMGR_INCLUDE_FORM_HOST_RECORD_H -#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_HOST_RECORD_H - -#include -#include -#include -#include "app_log_wrapper.h" -#include "form_host_callback.h" -#include "form_item_info.h" -#include "form_record.h" -#include "iremote_object.h" - -namespace OHOS { -namespace AppExecFwk { -/** - * @class FormHostRecord - * Form host data. - */ -class FormHostRecord { -public: - /** - * @brief Create form host record. - * @param callback remote object. - * @param callingUid Calling uid. - */ - static FormHostRecord CreateRecord(const FormItemInfo &info, const sptr &callback, int callingUid); - /** - * @brief Add form id. - * @param formId The Id of the form. - */ - void AddForm(int64_t formId); - /** - * @brief Delete form id. - * @param formId The Id of the form. - */ - void DelForm(int64_t formId); - /** - * @brief forms_ is empty or not. - * @return forms_ is empty or not. - */ - bool IsEmpty() const; - /** - * @brief formId is in forms_ or not. - * @param formId The Id of the form. - * @return formId is in forms_ or not. - */ - bool Contains(int64_t formId) const; - - /** - * @brief Set refresh enable flag. - * @param formId The Id of the form. - * @param flag True for enbale, false for disable. - */ - void SetEnableRefresh(int64_t formId, bool flag); - - /** - * @brief Refresh enable or not. - * @param formId The Id of the form. - * @return true on enbale, false on disable.. - */ - bool IsEnableRefresh(int64_t formId) const; - - /** - * @brief Set need refresh enable flag. - * @param formId The Id of the form. - * @param flag True for enbale, false for disable. - */ - void SetNeedRefresh(int64_t formId, bool flag); - /** - * @brief Need Refresh enable or not. - * @param formId The Id of the form. - * @return true on enbale, false on disable.. - */ - bool IsNeedRefresh(int64_t formId) const; - - /** - * @brief Send form data to form host. - * @param id The Id of the form. - * @param record Form record. - */ - void OnAcquire(int64_t id, const FormRecord &record); - - /** - * @brief Update form data to form host. - * @param id The Id of the form. - * @param record Form record. - */ - void OnUpdate(int64_t id, const FormRecord &record); - /** - * Send form uninstall message to form host. - * - * @param id The Id of the form. - * @param record Form record. - */ - void OnFormUninstalled(std::vector &formIds); - - /** - * @brief Release resource. - * @param id The Id of the form. - * @param record Form record. - */ - void CleanResource(); - /** - * @brief Get callerUid_. - * @return callerUid_. - */ - int GetCallerUid() const - { - return callerUid_; - } - /** - * @brief Get clientStub_. - * @return clientStub_. - */ - sptr GetClientStub() const; - /** - * @brief Get deathRecipient_. - * @return deathRecipient_. - */ - sptr GetDeathRecipient() const; - /** - * @brief Set value of callerUid_. - * @param callerUid Caller uid. - */ - void SetCallerUid(const int callerUid); - /** - * @brief Set value of clientStub_. - * @param clientStub remote object. - */ - void SetClientStub(const sptr &clientStub); - /** - * @brief Set value of clientImpl_. - * @param clientImpl Form host callback object. - */ - void SetClientImpl(const std::shared_ptr &clientImpl); - /** - * @brief Set value of deathRecipient_. - * @param clientImpl DeathRecipient object. - */ - void SetDeathRecipient(const sptr &deathRecipient); - /** - * @brief Add deathRecipient object to clientStub_. - * @param deathRecipient DeathRecipient object. - */ - void AddDeathRecipient(const sptr& deathRecipient); - /** - * @brief Get hostBundleName_. - * @return hostBundleName_. - */ - std::string GetHostBundleName() const; - /** - * @brief Set hostBundleName_. - * @param hostBandleName Host bundle name. - */ - void SetHostBundleName(const std::string &hostBundleName); - -private: - int callerUid_; - sptr clientStub_ = nullptr; - std::shared_ptr clientImpl_ = nullptr; - sptr deathRecipient_ = nullptr; - std::unordered_map forms_; - std::unordered_map needRefresh_; - std::string hostBundleName_; - - /** - * @class ClientDeathRecipient - * notices IRemoteBroker died. - */ - class ClientDeathRecipient : public IRemoteObject::DeathRecipient { - public: - /** - * @brief Constructor - */ - ClientDeathRecipient() = default; - ~ClientDeathRecipient() = default; - /** - * @brief handle remote object died event. - * @param remote remote object. - */ - void OnRemoteDied(const wptr &remote) override; - }; -}; -} // namespace AppExecFwk -} // namespace OHOS - +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License")_; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_HOST_RECORD_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_HOST_RECORD_H + +#include +#include +#include +#include "app_log_wrapper.h" +#include "form_host_callback.h" +#include "form_item_info.h" +#include "form_record.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormHostRecord + * Form host data. + */ +class FormHostRecord { +public: + /** + * @brief Create form host record. + * @param callback remote object. + * @param callingUid Calling uid. + */ + static FormHostRecord CreateRecord(const FormItemInfo &info, const sptr &callback, int callingUid); + /** + * @brief Add form id. + * @param formId The Id of the form. + */ + void AddForm(int64_t formId); + /** + * @brief Delete form id. + * @param formId The Id of the form. + */ + void DelForm(int64_t formId); + /** + * @brief forms_ is empty or not. + * @return forms_ is empty or not. + */ + bool IsEmpty() const; + /** + * @brief formId is in forms_ or not. + * @param formId The Id of the form. + * @return formId is in forms_ or not. + */ + bool Contains(int64_t formId) const; + + /** + * @brief Set refresh enable flag. + * @param formId The Id of the form. + * @param flag True for enbale, false for disable. + */ + void SetEnableRefresh(int64_t formId, bool flag); + + /** + * @brief Refresh enable or not. + * @param formId The Id of the form. + * @return true on enbale, false on disable.. + */ + bool IsEnableRefresh(int64_t formId) const; + + /** + * @brief Set need refresh enable flag. + * @param formId The Id of the form. + * @param flag True for enbale, false for disable. + */ + void SetNeedRefresh(int64_t formId, bool flag); + /** + * @brief Need Refresh enable or not. + * @param formId The Id of the form. + * @return true on enbale, false on disable.. + */ + bool IsNeedRefresh(int64_t formId) const; + + /** + * @brief Send form data to form host. + * @param id The Id of the form. + * @param record Form record. + */ + void OnAcquire(int64_t id, const FormRecord &record); + + /** + * @brief Update form data to form host. + * @param id The Id of the form. + * @param record Form record. + */ + void OnUpdate(int64_t id, const FormRecord &record); + /** + * Send form uninstall message to form host. + * + * @param id The Id of the form. + * @param record Form record. + */ + void OnFormUninstalled(std::vector &formIds); + + /** + * @brief Release resource. + * @param id The Id of the form. + * @param record Form record. + */ + void CleanResource(); + /** + * @brief Get callerUid_. + * @return callerUid_. + */ + int GetCallerUid() const + { + return callerUid_; + } + /** + * @brief Get clientStub_. + * @return clientStub_. + */ + sptr GetClientStub() const; + /** + * @brief Get deathRecipient_. + * @return deathRecipient_. + */ + sptr GetDeathRecipient() const; + /** + * @brief Set value of callerUid_. + * @param callerUid Caller uid. + */ + void SetCallerUid(const int callerUid); + /** + * @brief Set value of clientStub_. + * @param clientStub remote object. + */ + void SetClientStub(const sptr &clientStub); + /** + * @brief Set value of clientImpl_. + * @param clientImpl Form host callback object. + */ + void SetClientImpl(const std::shared_ptr &clientImpl); + /** + * @brief Set value of deathRecipient_. + * @param clientImpl DeathRecipient object. + */ + void SetDeathRecipient(const sptr &deathRecipient); + /** + * @brief Add deathRecipient object to clientStub_. + * @param deathRecipient DeathRecipient object. + */ + void AddDeathRecipient(const sptr& deathRecipient); + /** + * @brief Get hostBundleName_. + * @return hostBundleName_. + */ + std::string GetHostBundleName() const; + /** + * @brief Set hostBundleName_. + * @param hostBandleName Host bundle name. + */ + void SetHostBundleName(const std::string &hostBundleName); + +private: + int callerUid_ = 0; + sptr clientStub_ = nullptr; + std::shared_ptr clientImpl_ = nullptr; + sptr deathRecipient_ = nullptr; + std::unordered_map forms_; + std::unordered_map needRefresh_; + std::string hostBundleName_ = ""; + + /** + * @class ClientDeathRecipient + * notices IRemoteBroker died. + */ + class ClientDeathRecipient : public IRemoteObject::DeathRecipient { + public: + /** + * @brief Constructor + */ + ClientDeathRecipient() = default; + ~ClientDeathRecipient() = default; + /** + * @brief handle remote object died event. + * @param remote remote object. + */ + void OnRemoteDied(const wptr &remote) override; + }; +}; +} // namespace AppExecFwk +} // namespace OHOS + #endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_HOST_RECORD_H \ No newline at end of file diff --git a/services/formmgr/include/form_item_info.h b/services/formmgr/include/form_item_info.h index aa0a499ea0f80f6664da862396abb9a4a9e4738b..3106ed83c82e0e4c08ceac03e5cf6540028e7615 100644 --- a/services/formmgr/include/form_item_info.h +++ b/services/formmgr/include/form_item_info.h @@ -231,22 +231,22 @@ private: private: int64_t formId_ = -1; - std::string packageName_; - std::string providerBundleName_; - std::string hostBundleName_; - std::string moduleName_; - std::string abilityName_; - std::string formName_; - int32_t specificationId_; - bool updateFlag_; - int32_t updateDuration_; - std::string scheduledUpdateTime_; + std::string packageName_ = ""; + std::string providerBundleName_ = ""; + std::string hostBundleName_ = ""; + std::string moduleName_ = ""; + std::string abilityName_ = ""; + std::string formName_ = ""; + int32_t specificationId_ = 0; + bool updateFlag_ = false; + int32_t updateDuration_ = 0; + std::string scheduledUpdateTime_ = ""; std::vector hapSourceDirs_; - bool temporaryFlag_; - bool formVisibleNotify_; + bool temporaryFlag_ = false; + bool formVisibleNotify_ = false; - std::string jsComponentName_; - std::string abilityModuleName_; + std::string jsComponentName_ = ""; + std::string abilityModuleName_ = ""; std::unordered_map moduleInfoMap_; }; } // namespace AppExecFwk diff --git a/services/formmgr/include/form_mgr_adapter.h b/services/formmgr/include/form_mgr_adapter.h index b795fb900f38fe25f45a2090f04d2d7c9b0242a0..2ac902fc6f4ee5a37c9eebdc719c11fa5f649f9f 100644 --- a/services/formmgr/include/form_mgr_adapter.h +++ b/services/formmgr/include/form_mgr_adapter.h @@ -17,6 +17,7 @@ #define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MGR_ADAPTER_H #include +#include #include "bundle_info.h" #include "bundle_mgr_interface.h" @@ -38,10 +39,10 @@ using WantParams = OHOS::AAFwk::WantParams; * @class FormMgrAdapter * Form request handler from form host. */ -class FormMgrAdapter { +class FormMgrAdapter final : public DelayedRefSingleton { +DECLARE_DELAYED_REF_SINGLETON(FormMgrAdapter) public: - FormMgrAdapter(){}; - virtual ~FormMgrAdapter(){}; + DISALLOW_COPY_AND_MOVE(FormMgrAdapter); /** * @brief Add form with want, send want to form manager service. @@ -161,6 +162,22 @@ public: * @return Returns true if execute success, false otherwise. */ int MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken); + + /** + * @brief Acquire form data from form provider. + * @param formId The Id of the from. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ + void AcquireProviderFormInfo(const int64_t formId, const Want &want, const sptr &remoteObject); + /** + * @brief Notify form provider for delete form. + * @param formId The Id of the from. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ + void NotifyFormDelete(const int64_t formId, const Want &want, const sptr &remoteObject); private: /** * @brief Get form configure info. diff --git a/services/formmgr/include/form_mgr_service.h b/services/formmgr/include/form_mgr_service.h index a2cd4970a0f0153f0eabce755f0f9142331a11ea..ac10b21ae6a2a392f596c3e16d6dca6550335edc 100644 --- a/services/formmgr/include/form_mgr_service.h +++ b/services/formmgr/include/form_mgr_service.h @@ -24,7 +24,6 @@ #include #include "event_handler.h" -#include "form_mgr_adapter.h" #include "form_mgr_stub.h" #include "form_provider_data.h" #include "iremote_object.h" @@ -194,8 +193,6 @@ private: std::shared_ptr runner_ = nullptr; std::shared_ptr handler_ = nullptr; - - std::unique_ptr formMgrAdapter_ = nullptr; bool resetFlag = false; diff --git a/services/formmgr/include/form_msg_event_connection.h b/services/formmgr/include/form_msg_event_connection.h index 6fd0981744c3a5e90b1a3d4b4ee00582d907ca58..1aefe943954c21e19249aa3af8e601d00665f363 100644 --- a/services/formmgr/include/form_msg_event_connection.h +++ b/services/formmgr/include/form_msg_event_connection.h @@ -1,53 +1,54 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MSG_EVENT_CONNECTION_H -#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MSG_EVENT_CONNECTION_H - -#include "event_handler.h" -#include "form_ability_connection.h" -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -using Want = OHOS::AAFwk::Want; -/** - * @class FormMsgEventConnection - * Form Refresh Connection Stub. - */ -class FormMsgEventConnection : public FormAbilityConnection { -public: - FormMsgEventConnection(const int64_t formId, const Want &want); - virtual ~FormMsgEventConnection() = default; - - /** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * - * @param element service ability's ElementName. - * @param remoteObject the session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - */ - void OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; - -private: - int64_t formId_; - Want want_; - DISALLOW_COPY_AND_MOVE(FormMsgEventConnection); -}; -} // namespace AppExecFwk -} // namespace OHOS - +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MSG_EVENT_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MSG_EVENT_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +/** + * @class FormMsgEventConnection + * Form Refresh Connection Stub. + */ +class FormMsgEventConnection : public FormAbilityConnection { +public: + FormMsgEventConnection(const int64_t formId, const Want &want, + const std::string &bundleName, const std::string &abilityName); + virtual ~FormMsgEventConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + int64_t formId_; + Want want_; + DISALLOW_COPY_AND_MOVE(FormMsgEventConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + #endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MSG_EVENT_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_refresh_connection.h b/services/formmgr/include/form_refresh_connection.h index 142c06ae99db54408fc76667255359fdc7121cd3..a847be922893c1ba524949925668f9a7ebfdc6d4 100644 --- a/services/formmgr/include/form_refresh_connection.h +++ b/services/formmgr/include/form_refresh_connection.h @@ -1,53 +1,54 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_REFRESH_CONNECTION_H -#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_REFRESH_CONNECTION_H - -#include "event_handler.h" -#include "form_ability_connection.h" -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -using Want = OHOS::AAFwk::Want; -/** - * @class FormRefreshConnection - * Form Refresh Connection Stub. - */ -class FormRefreshConnection : public FormAbilityConnection { -public: - FormRefreshConnection(const int64_t formId, const Want &want); - virtual ~FormRefreshConnection() = default; - - /** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * - * @param element service ability's ElementName. - * @param remoteObject the session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - */ - void OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; - -private: - int64_t formId_; - Want want_; - DISALLOW_COPY_AND_MOVE(FormRefreshConnection); -}; -} // namespace AppExecFwk -} // namespace OHOS - +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_REFRESH_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_REFRESH_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +/** + * @class FormRefreshConnection + * Form Refresh Connection Stub. + */ +class FormRefreshConnection : public FormAbilityConnection { +public: + FormRefreshConnection(const int64_t formId, const Want &want, + const std::string &bundleName, const std::string &abilityName); + virtual ~FormRefreshConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + int64_t formId_; + Want want_; + DISALLOW_COPY_AND_MOVE(FormRefreshConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + #endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_REFRESH_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_supply_callback.h b/services/formmgr/include/form_supply_callback.h index 031ff49c12bf1e6b5a2c26f5c492c4a40ef1f602..38487b5fa1b967e23cae2f1adb405c636292695c 100644 --- a/services/formmgr/include/form_supply_callback.h +++ b/services/formmgr/include/form_supply_callback.h @@ -1,69 +1,76 @@ -/* - * 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_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H -#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H - -#include "form_ability_connection.h" -#include "form_supply_stub.h" - -namespace OHOS { -namespace AppExecFwk { -/** - * @class FormSupplyCallback - * form supply service stub. - */ -class FormSupplyCallback : public FormSupplyStub { -public: - FormSupplyCallback() = default; - virtual ~FormSupplyCallback() = default; - static sptr GetInstance(); - - /** - * @brief Accept form binding data from form provider. - * @param providerFormInfo Form binding data. - * @param want input data. - * @return Returns ERR_OK on success, others on failure. - */ - int OnAcquire(const FormProviderInfo &formInfo, const Want &want) override; - - /** - * @brief Accept other event. - * @param want input data. - * @return Returns ERR_OK on success, others on failure. - */ - int OnEventHandle(const Want &want) override; - - /** - * @brief Save ability Connection for the callback. - * @param connection ability connection. - */ - void AddConnection(sptr connection); - /** - * @brief Delete ability connection after the callback come. - * @param connectId The ability connection id generated when save. - */ - void RemoveConnection(long connectId); -private: - static std::mutex mutex_; - static sptr instance_; - - mutable std::mutex conMutex_; - std::map> connections_; - DISALLOW_COPY_AND_MOVE(FormSupplyCallback); -}; -} // namespace AppExecFwk -} // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H + +#include "form_ability_connection.h" +#include "form_supply_stub.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormSupplyCallback + * form supply service stub. + */ +class FormSupplyCallback : public FormSupplyStub { +public: + FormSupplyCallback() = default; + virtual ~FormSupplyCallback() = default; + static sptr GetInstance(); + + /** + * @brief Accept form binding data from form provider. + * @param providerFormInfo Form binding data. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ + int OnAcquire(const FormProviderInfo &formInfo, const Want &want) override; + + /** + * @brief Accept other event. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ + int OnEventHandle(const Want &want) override; + + /** + * @brief Save ability Connection for the callback. + * @param connection ability connection. + */ + void AddConnection(sptr connection); + /** + * @brief Delete ability connection after the callback come. + * @param connectId The ability connection id generated when save. + */ + void RemoveConnection(long connectId); + +private: + /** + * @brief check if disconnect ability or not. + * @param connection The ability connection. + */ + bool CanDisConnect(sptr &connection); +private: + static std::mutex mutex_; + static sptr instance_; + + mutable std::mutex conMutex_; + std::map> connections_; + DISALLOW_COPY_AND_MOVE(FormSupplyCallback); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H diff --git a/services/formmgr/include/form_timer.h b/services/formmgr/include/form_timer.h index 94cf7ffcff9b0f6f88bec011eb9cefd3fd16937e..cec511f4f4a7be46636ffd088eea2b8620ab268f 100644 --- a/services/formmgr/include/form_timer.h +++ b/services/formmgr/include/form_timer.h @@ -14,6 +14,7 @@ */ #ifndef FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_TASK_H #define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_TASK_H + namespace OHOS { namespace AppExecFwk { /** @@ -41,7 +42,7 @@ public: int64_t refreshTime; bool isEnable = true; bool isCountTimer = false; - UpdateType type; + UpdateType type = UpdateType::TYPE_INTERVAL_CHANGE; FormTimer() { @@ -51,6 +52,8 @@ public: min = -1; isUpdateAt = false; isCountTimer = false; + refreshTime = 0; + type = UpdateType::TYPE_INTERVAL_CHANGE; } FormTimer(int64_t id, bool countTimer) @@ -61,6 +64,8 @@ public: min = -1; isUpdateAt = false; isCountTimer = countTimer; + refreshTime = 0; + type = UpdateType::TYPE_INTERVAL_CHANGE; } FormTimer(int64_t id, long repeatTime) @@ -71,6 +76,8 @@ public: min = -1; isUpdateAt = false; isCountTimer = true; + refreshTime = 0; + type = UpdateType::TYPE_INTERVAL_CHANGE; } FormTimer(int64_t id, int hourTime, int minTime) @@ -81,6 +88,10 @@ public: period = -1; isUpdateAt = true; isCountTimer = false; + refreshTime = 0; + type = UpdateType::TYPE_INTERVAL_CHANGE; + } + ~FormTimer(void){ } }; /** @@ -108,6 +119,8 @@ public: formId = id; settedTime = time; } + ~DynamicRefreshItem(void){ + } }; /** * @struct LimitInfo @@ -130,57 +143,6 @@ struct FormTimerCfg { int updateAtMin = -1; }; -// class TimerInfo : public ITimerInfo { -// public: -// TimerInfo(); -// virtual ~TimerInfo(); -// virtual void OnTrigger() override; -// virtual void SetType(const int &type) override; -// virtual void SetRepeat(bool repeat) override; -// virtual void SetInterval(const uint64_t &interval) override; -// virtual void SetWantAgent(std::shared_ptr wantAgent) override; -// void SetCallbackInfo(std::function callBack); - -// private: -// std::function callBack_; -// }; - -// TimerInfo::TimerInfo() -// { -// } - -// TimerInfo::~TimerInfo() -// { -// } - -// void TimerInfo::OnTrigger() -// { -// callBack_(); -// } - -// void TimerInfo::SetCallbackInfo(std::function callBack) -// { -// callBack_ = callBack; -// } - -// void TimerInfo::SetType(const int &_type) -// { -// type = _type; -// } - -// void TimerInfo::SetRepeat(bool _repeat) -// { -// repeat = _repeat; -// } -// void TimerInfo::SetInterval(const uint64_t &_interval) -// { -// interval = _interval; -// } -// void TimerInfo::SetWantAgent(std::shared_ptr _wantAgent) -// { -// wantAgent = _wantAgent; -// } - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_TASK_H diff --git a/services/formmgr/include/form_timer_mgr.h b/services/formmgr/include/form_timer_mgr.h index b710a2a07995b760074c3c8422bdeeeb6b036a13..1ff69380079bdb562a21b9d0e7305aad3ef7901c 100644 --- a/services/formmgr/include/form_timer_mgr.h +++ b/services/formmgr/include/form_timer_mgr.h @@ -33,9 +33,8 @@ #include "common_event_subscribe_info.h" #include "form_refresh_limiter.h" #include "form_timer.h" - #include "thread_pool.h" -#include "timer.h" +// #include "timer.h" namespace OHOS { namespace AppExecFwk { @@ -115,22 +114,26 @@ public: /** * @brief Handle system time changed. + * @return Returns true on success, false on failure. */ - void HandleSystemTimeChanged(); + bool HandleSystemTimeChanged(); /** * @brief Reset form limiter. + * @return Returns true on success, false on failure. */ - void HandleResetLimiter(); + bool HandleResetLimiter(); /** * @brief Update attime trigger. * @param updateTime Update time. + * @return Returns true on success, false on failure. */ - void OnUpdateAtTrigger(long updateTime); + bool OnUpdateAtTrigger(long updateTime); /** * @brief Dynamic time trigger. * @param updateTime Update time. + * @return Returns true on success, false on failure. */ - void OnDynamicTimeTrigger(long updateTime); + bool OnDynamicTimeTrigger(long updateTime); private: /** @@ -154,6 +157,7 @@ private: * @brief interval timer task timeout. */ void OnIntervalTimeOut(); + /** * @brief Get remind tasks. * @param remindTasks Remind tasks. @@ -203,8 +207,9 @@ private: /** * @brief Delete update at timer. * @param formId The Id of the form. + * @return Returns true on success, false on failure. */ - void DeleteUpdateAtTimer(const int64_t formId); + bool DeleteUpdateAtTimer(const int64_t formId); /** * @brief Update at timer task alarm. * @return Returns true on success, false on failure. @@ -215,11 +220,16 @@ private: * @return Returns true on success, false on failure. */ bool UpdateLimiterAlarm(); + /** + * @brief Clear limiter timer resource. + */ + void ClearLimiterTimerResource(); /** * @brief Delete dynamic refresh item. * @param formId The Id of the form. + * @return Returns true on success, false on failure. */ - void DeleteDynamicItem(const int64_t formId); + bool DeleteDynamicItem(const int64_t formId); /** * @brief Update dynamic refresh task alarm. * @return Returns true on success, false on failure. @@ -303,14 +313,18 @@ private: std::list updateAtTimerTasks_; std::vector dynamicRefreshTasks_; - std::shared_ptr timerReceiver_; + std::shared_ptr timerReceiver_ = nullptr; + OHOS::ThreadPool* taskExecutor_ = nullptr; + + uint64_t intervalTimerId_ = 0L; + uint64_t updateAtTimerId_ = 0L; + uint64_t dynamicAlarmTimerId_ = 0L; + uint64_t limiterTimerId_= 0L; + - OHOS::ThreadPool* taskExecutor_; - Utils::Timer* intervalTimer_; - long dynamicWakeUpTime_ = LONG_MAX; - long atTimerWakeUpTime_ = LONG_MAX; }; + } // namespace AppExecFwk } // namespace OHOS diff --git a/services/formmgr/include/form_timer_option.h b/services/formmgr/include/form_timer_option.h new file mode 100644 index 0000000000000000000000000000000000000000..d026163ee46779b03b3e08f36f4e6b75e34d86aa --- /dev/null +++ b/services/formmgr/include/form_timer_option.h @@ -0,0 +1,81 @@ +/* + * 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_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_INFO_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_INFO_H + +#include "itimer_info.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormTimerOption + * form timer option. + */ +class FormTimerOption : public OHOS::MiscServices::ITimerInfo { +public: + FormTimerOption(); + virtual ~FormTimerOption(); + virtual void OnTrigger() override; + virtual void SetType(const int &type) override; + virtual void SetRepeat(bool repeat) override; + virtual void SetInterval(const uint64_t &interval) override; + virtual void SetWantAgent(std::shared_ptr wantAgent) override; + void SetCallbackInfo(std::function callBack); + + private: + std::function callBack; +}; + +FormTimerOption::FormTimerOption() +{ +} + +FormTimerOption::~FormTimerOption() +{ +} + +void FormTimerOption::OnTrigger() +{ + callBack(); +} + +void FormTimerOption::SetCallbackInfo(std::function callBack) +{ + this->callBack = callBack; +} + +void FormTimerOption::SetType(const int &type) +{ + this->type = type; +} + +void FormTimerOption::SetRepeat(bool repeat) +{ + this->repeat = repeat; +} +void FormTimerOption::SetInterval(const uint64_t &interval) +{ + this->interval = interval; +} +void FormTimerOption::SetWantAgent(std::shared_ptr _wantAgent) +{ + this->wantAgent = _wantAgent; +} + +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_INFO_H diff --git a/services/formmgr/include/form_util.h b/services/formmgr/include/form_util.h index d043693889bcbd385f65318a8998f27ed0b7e056..d31b79dda6d239a0cb485b977bd6cb3e7df1570e 100644 --- a/services/formmgr/include/form_util.h +++ b/services/formmgr/include/form_util.h @@ -1,101 +1,101 @@ -/* - * 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_SERVICES_FORMMGR_INCLUDE_FORM_UTIL_H -#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_UTIL_H - -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -using Want = OHOS::AAFwk::Want; -/** - * @class FormUtil - * form utils. - */ -class FormUtil { -public: - /** - * @brief create want for form. - * @param formName The name of the form. - * @param specificationId specification id. - * @param isTemporaryForm temporary form or not. - * @param want The want of the form. - */ - static void CreateFormWant(const std::string &formName, const int32_t specificationId, const bool isTemporaryForm, - Want &want); - /** - * @brief create default want for form. - * @param want The want of the form.. - * @param uri The uri. - * @param userId user id. - */ - static void CreateDefaultFormWant(Want &want, const std::string &uri, const int32_t userId); - - /** - * @brief create udid for form. - * @return udid. - */ - static std::string GenerateUdid(); - - /** - * @brief create form id for form. - * @param udidHash udid hash - * @return new form id. - */ - static int64_t GenerateFormId(int64_t udidHash); - - /** - * @brief padding form id. - * @param formId The id of the form. - * @param udidHash udid hash. - * @return new form id. - */ - static int64_t PaddingUDIDHash(int64_t formId, int64_t udidHash); - - /** - * @brief create udid hash. - * @param udidHash udid hash. - * @return Returns true on success, false on failure. - */ - static bool GenerateUdidHash(int64_t &udidHash); - /** - * @brief Get current system nanosecond. - * @return Current system nanosecond. - */ - static long GetCurrentNanosecond(); - /** - * @brief Get current system millisecond. - * @return Current system millisecond. - */ - static long GetCurrentMillisecond(); - /** - * @brief Get millisecond from tm. - * @param tmAtTime tm time. - * @return Millisecond. - */ - static long GetMillisecondFromTm(struct tm &tmAtTime); - - /** - * @brief split string. - * @param in string. - * @param delim delimiter. - * @return string list. - */ - static std::vector StringSplit(const std::string &in, const std::string &delim); -}; -} // namespace AppExecFwk -} // namespace OHOS +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License")_; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_UTIL_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_UTIL_H + +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +/** + * @class FormUtil + * form utils. + */ +class FormUtil { +public: + /** + * @brief create want for form. + * @param formName The name of the form. + * @param specificationId specification id. + * @param isTemporaryForm temporary form or not. + * @param want The want of the form. + */ + static void CreateFormWant(const std::string &formName, const int32_t specificationId, const bool isTemporaryForm, + Want &want); + /** + * @brief create default want for form. + * @param want The want of the form.. + * @param uri The uri. + * @param userId user id. + */ + static void CreateDefaultFormWant(Want &want, const std::string &uri, const int32_t userId); + + /** + * @brief create udid for form. + * @return udid. + */ + static std::string GenerateUdid(); + + /** + * @brief create form id for form. + * @param udidHash udid hash + * @return new form id. + */ + static int64_t GenerateFormId(int64_t udidHash); + + /** + * @brief padding form id. + * @param formId The id of the form. + * @param udidHash udid hash. + * @return new form id. + */ + static int64_t PaddingUDIDHash(uint64_t formId, uint64_t udidHash); + + /** + * @brief create udid hash. + * @param udidHash udid hash. + * @return Returns true on success, false on failure. + */ + static bool GenerateUdidHash(int64_t &udidHash); + /** + * @brief Get current system nanosecond. + * @return Current system nanosecond. + */ + static long GetCurrentNanosecond(); + /** + * @brief Get current system millisecond. + * @return Current system millisecond. + */ + static long GetCurrentMillisecond(); + /** + * @brief Get millisecond from tm. + * @param tmAtTime tm time. + * @return Millisecond. + */ + static long GetMillisecondFromTm(struct tm &tmAtTime); + + /** + * @brief split string. + * @param in string. + * @param delim delimiter. + * @return string list. + */ + static std::vector StringSplit(const std::string &in, const std::string &delim); +}; +} // namespace AppExecFwk +} // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_UTIL_H \ No newline at end of file diff --git a/services/formmgr/src/form_ability_connection.cpp b/services/formmgr/src/form_ability_connection.cpp index 2550f42fb4732daffacb005d1196812621de8bd7..35c58ca9ea98c75892555179ba81b52e76c49b22 100644 --- a/services/formmgr/src/form_ability_connection.cpp +++ b/services/formmgr/src/form_ability_connection.cpp @@ -37,13 +37,10 @@ void FormAbilityConnection::OnAbilityConnectDone( const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) { if (resultCode != ERR_OK) { - APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", - __func__, element.GetAbilityName().c_str(), formId_, resultCode); + APP_LOGE("%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", + __func__, formId_, resultCode); return; } - // deviceId_ = element.GetDeviceID(); - // bundleName_ = element.GetBundleName(); - // abilityName_ = element.GetAbilityName(); if (isFreeInstall_) { // Handle free install for form provider app @@ -93,12 +90,29 @@ long FormAbilityConnection::GetConnectId() { return connectId_; } -// std::string FormAbilityConnection::GetProviderKey() -// { -// if(deviceId_.empty() || bundleName_.empty() || abilityName_.empty()) { -// return ""; -// } -// return deviceId_ + "::" + bundleName_ + "::" + abilityName_; -// } +/** + * @brief Get the provider Key + * + * @return The provider Key + */ +std::string FormAbilityConnection::GetProviderKey() +{ + if(bundleName_.empty() || abilityName_.empty()) { + return ""; + } + return bundleName_ + "::" + abilityName_; +} + +/** + * @brief Set the Provider Key + * + * @param bundleName bundleName + * @param abilityName abilityName + */ +void FormAbilityConnection::SetProviderKey(const std::string &bundleName, const std::string &abilityName) +{ + bundleName_ = bundleName; + abilityName_ = abilityName; +} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_acquire_connection.cpp b/services/formmgr/src/form_acquire_connection.cpp index 282dd320de5659ea8404a4856c03fc7ee5955031..3cd1770f269ea7642e4e52e5850075f489534c8b 100644 --- a/services/formmgr/src/form_acquire_connection.cpp +++ b/services/formmgr/src/form_acquire_connection.cpp @@ -1,67 +1,71 @@ - -/* - * 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 "appexecfwk_errors.h" -#include "app_log_wrapper.h" -#include "form_acquire_connection.h" -#include "form_constants.h" -#include "form_supply_callback.h" -#include "form_task_mgr.h" -#include "form_util.h" -#include "ipc_types.h" -#include "message_parcel.h" -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -FormAcquireConnection::FormAcquireConnection(const int64_t formId, const FormItemInfo &info, -const WantParams &wantParams) - :formId_(formId), - info_(info), - wantParams_(wantParams) -{ -} -/** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * @param element service ability's ElementName. - * @param remoteObject the session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - */ -void FormAcquireConnection::OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) -{ - APP_LOGI("%{public}s called.", __func__); - if (resultCode != ERR_OK) { - APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", - __func__, element.GetAbilityName().c_str(), formId_, resultCode); - return; - } - FormSupplyCallback::GetInstance()->AddConnection(this); - Want want; - want.SetParams(wantParams_); - FormUtil::CreateFormWant(info_.GetFormName(), info_.GetSpecificationId(), info_.IsTemporaryForm(), want); - if (want.GetBoolParam(Constants::RECREATE_FORM_KEY, false)) { - want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_RECREATE_FORM); - } else { - want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); - } - want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); - FormTaskMgr::GetInstance().PostAcquireTask(formId_, want, remoteObject); -} -} // namespace AppExecFwk + +/* + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_acquire_connection.h" +#include "form_constants.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "form_util.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormAcquireConnection::FormAcquireConnection( + const int64_t formId, + const FormItemInfo &info, + const WantParams &wantParams) + :formId_(formId), + info_(info), + wantParams_(wantParams) +{ + SetProviderKey(info.GetProviderBundleName(), info.GetAbilityName()); +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ +void FormAcquireConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + Want want; + want.SetParams(wantParams_); + FormUtil::CreateFormWant(info_.GetFormName(), info_.GetSpecificationId(), info_.IsTemporaryForm(), want); + if (want.GetBoolParam(Constants::RECREATE_FORM_KEY, false)) { + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_RECREATE_FORM); + } else { + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + } + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostAcquireTask(formId_, want, remoteObject); +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_ams_helper.cpp b/services/formmgr/src/form_ams_helper.cpp index 7a393c4aa0e349f92c51a56f9bc7fd85f5a0719d..7588442f149637b44f0a691b6096a44980cc19b6 100644 --- a/services/formmgr/src/form_ams_helper.cpp +++ b/services/formmgr/src/form_ams_helper.cpp @@ -24,6 +24,7 @@ namespace OHOS { namespace AppExecFwk { +const int FORM_DISCONNECT_DELAY_TIME = 100; // ms FormAmsHelper::FormAmsHelper(){} FormAmsHelper::~FormAmsHelper(){} @@ -59,10 +60,10 @@ sptr FormAmsHelper::GetAbilityManager() * @return Returns ERR_OK on success, others on failure. */ ErrCode FormAmsHelper::ConnectServiceAbility( - const Want &want, const sptr &connect) + const Want &want, const sptr &connect) { APP_LOGI("%{public}s called.", __func__); - sptr ams = GetAbilityManager(); + sptr ams = GetAbilityManager(); if (ams == nullptr) { APP_LOGE("%{public}s:ability service not connect", __func__); return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; @@ -70,20 +71,42 @@ ErrCode FormAmsHelper::ConnectServiceAbility( return ams->ConnectAbility(want, connect, nullptr); } /** - * @brief DisConnectAbility, disconnect session with service ability. + * @brief Disconnect ability, disconnect session with service ability. * @param want Special want for service type's ability. * @param connect Callback used to notify caller the result of connecting or disconnecting. * @return Returns ERR_OK on success, others on failure. */ -ErrCode FormAmsHelper::DisConnectServiceAbility(const sptr &connect) -{ - sptr ams = GetAbilityManager(); +ErrCode FormAmsHelper::DisConnectServiceAbility(const sptr &connect) +{ APP_LOGI("%{public}s called.", __func__); + sptr ams = GetAbilityManager(); if (ams == nullptr) { APP_LOGE("%{public}s:ability service not connect", __func__); return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; } return ams->DisconnectAbility(connect); } +/** + * @brief Disconnect ability delay, disconnect session with service ability. + * @param want Special want for service type's ability. + * @param connect Callback used to notify caller the result of connecting or disconnecting. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormAmsHelper::DisConnectServiceAbilityDelay(const sptr &connect) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); + return ERR_INVALID_OPERATION; + } + std::function disConnectAbilityFunc = std::bind( + &FormAmsHelper::DisConnectAbilityTask, + this, + connect); + if(!eventHandler_->PostTask(disConnectAbilityFunc, FORM_DISCONNECT_DELAY_TIME)) { + APP_LOGE("%{public}s, failed to disconnect ability", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + return ERR_OK; +} /** * @brief Add the ability manager instance for debug. * @param abilityManager the ability manager ipc object. @@ -92,5 +115,20 @@ void FormAmsHelper::SetAbilityManager(const sptr &abilit { abilityManager_ = abilityManager; } + +/** + * @brief Disconnect ability task, disconnect session with service ability. + * @param want Special want for service type's ability. + * @param connect Callback used to notify caller the result of connecting or disconnecting. + */ +void FormAmsHelper::DisConnectAbilityTask(const sptr &connect) +{ + sptr ams = GetAbilityManager(); + if (ams == nullptr) { + APP_LOGE("%{public}s, ability service not connect", __func__); + return; + } + ams->DisconnectAbility(connect); +} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_batch_delete_connection.cpp b/services/formmgr/src/form_batch_delete_connection.cpp index 6da3a394eac36c6415e258d88a4a613fc7d020d0..72935c04c17edbea20160a1abf9646940be2b71f 100644 --- a/services/formmgr/src/form_batch_delete_connection.cpp +++ b/services/formmgr/src/form_batch_delete_connection.cpp @@ -27,9 +27,11 @@ namespace OHOS { namespace AppExecFwk { -FormBatchDeleteConnection::FormBatchDeleteConnection(const std::set &formIds) +FormBatchDeleteConnection::FormBatchDeleteConnection(const std::set &formIds, + const std::string &bundleName, const std::string &abilityName) :formIds_(formIds) { + SetProviderKey(bundleName, abilityName); } /** * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. diff --git a/services/formmgr/src/form_bms_helper.cpp b/services/formmgr/src/form_bms_helper.cpp index 22180d22631947ba5e665089e42185fe9b17df52..2f2a0d8e53a6e02350a4610dc2f9aad7d0e2a100 100644 --- a/services/formmgr/src/form_bms_helper.cpp +++ b/services/formmgr/src/form_bms_helper.cpp @@ -73,8 +73,8 @@ void FormBmsHelper::SetBundleManager(const sptr &bundleManager) */ void FormBmsHelper::NotifyModuleRemovable(const std::string &bundleName, const std::string &moduleName) { - APP_LOGI("%{public}s, bundleName:%{public}s, moduleName:%{public}s", __func__, bundleName.c_str(), - moduleName.c_str()); + APP_LOGI("%{public}s, bundleName:%{public}s, moduleName:%{public}s", + __func__, bundleName.c_str(), moduleName.c_str()); if (bundleName.empty() || moduleName.empty()) { return; } @@ -88,7 +88,6 @@ void FormBmsHelper::NotifyModuleRemovable(const std::string &bundleName, const s } std::string originId = IPCSkeleton::ResetCallingIdentity(); - // iBundleMgr->UpdateModuleRemovableFlag(bundleName, moduleName, FLAG_MODULE_NOT_USED_BY_FORM); IPCSkeleton::SetCallingIdentity(originId); } diff --git a/services/formmgr/src/form_cast_temp_connection.cpp b/services/formmgr/src/form_cast_temp_connection.cpp index 32b833d5304c06367518efc52f9718ce59675e53..e39ae1f08fe26152904d78e798e9d4d0e4e84a04 100644 --- a/services/formmgr/src/form_cast_temp_connection.cpp +++ b/services/formmgr/src/form_cast_temp_connection.cpp @@ -1,56 +1,58 @@ - -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include "appexecfwk_errors.h" -#include "app_log_wrapper.h" -#include "form_cast_temp_connection.h" -#include "form_constants.h" -#include "form_supply_callback.h" -#include "form_task_mgr.h" -#include "ipc_types.h" -#include "message_parcel.h" - -namespace OHOS { -namespace AppExecFwk { -FormCastTempConnection::FormCastTempConnection(const int64_t formId) - :formId_(formId) -{ -} -/** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * @param element service ability's ElementName. - * @param remoteObject the session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - */ -void FormCastTempConnection::OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) -{ - APP_LOGI("%{public}s called.", __func__); - if (resultCode != ERR_OK) { - APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", - __func__, element.GetAbilityName().c_str(), formId_, resultCode); - return; - } - FormSupplyCallback::GetInstance()->AddConnection(this); - - Want want; - want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); - FormTaskMgr::GetInstance().PostCastTempTask(formId_, want, remoteObject); -} -} // namespace AppExecFwk + +/* + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_cast_temp_connection.h" +#include "form_constants.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" + +namespace OHOS { +namespace AppExecFwk { +FormCastTempConnection::FormCastTempConnection(const int64_t formId, const std::string &bundleName, + const std::string &abilityName) + :formId_(formId) +{ + SetProviderKey(bundleName, abilityName); +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ +void FormCastTempConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + + Want want; + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostCastTempTask(formId_, want, remoteObject); +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_data_mgr.cpp b/services/formmgr/src/form_data_mgr.cpp index de464fcaddda7461120a49cb4c233d231caf64c0..d845fc5760b438fdd940c45c35e2b3be7e12b892 100644 --- a/services/formmgr/src/form_data_mgr.cpp +++ b/services/formmgr/src/form_data_mgr.cpp @@ -37,32 +37,6 @@ FormDataMgr::~FormDataMgr() APP_LOGI("destroy form data manager instance"); } -/** - * @brief Delete form js info by form record. - * @return Returns all form records map. - */ -std::map& FormDataMgr::GetAllFormRecord() -{ - return formRecords_; -} - -/** - * @brief Get all form client host record. - * @return Returns all form client host record. - */ -std::vector& FormDataMgr::GetClientRecords() -{ - return clientRecords_; -} - -/** - * @brief Get all form host records. - * @return Returns all form host records vector. - */ -std::vector& FormDataMgr::GetAllFormHostRecord() -{ - return clientRecords_; -} /** * @brief Allot form info by item info. * @param formId The Id of the form. @@ -103,7 +77,8 @@ FormRecord FormDataMgr::AllotFormRecord(const FormItemInfo &formInfo, const int * @param formId The Id of the form. * @return Returns true if this function is successfully called; returns false otherwise. */ -bool FormDataMgr::DeleteFormRecord(const int64_t formId) { +bool FormDataMgr::DeleteFormRecord(const int64_t formId) +{ APP_LOGI("%{public}s, delete form info", __func__); std::lock_guard lock(formRecordMutex_); auto iter = formRecords_.find(formId); @@ -155,7 +130,8 @@ bool FormDataMgr::AllotFormHostRecord(const FormItemInfo &info, const sptr &callerToken, - const int callingUid, FormHostRecord& record) { + const int callingUid, FormHostRecord& record) +{ if (callerToken == nullptr) { APP_LOGE("%{public}s, invalid param", __func__); return false; @@ -211,7 +187,6 @@ void FormDataMgr::CreateFormInfo(const int64_t formId, const FormRecord &record, formInfo.abilityName = record.abilityName; formInfo.formName = record.formName; formInfo.formTempFlg = record.formTempFlg; - // formInfo.setInstantProvider(record.instantProvider); } /** * @brief Check temp form count is max. @@ -221,8 +196,7 @@ int FormDataMgr::CheckTempEnoughForm() const { if (tempForms_.size() >= Constants::MAX_TEMP_FORMS) { APP_LOGW("%{public}s, already exist %{public}d temp forms in system", __func__, Constants::MAX_TEMP_FORMS); - // HiViewUtil.sendAddFormExceedLimitEvent(); - return ERR_MAX_SYSTEM_TEMP_FORMS; + return ERR_APPEXECFWK_FORM_MAX_SYSTEM_TEMP_FORMS; } return ERR_OK; } @@ -233,11 +207,11 @@ int FormDataMgr::CheckTempEnoughForm() const */ int FormDataMgr::CheckEnoughForm(const int callingUid) const { - APP_LOGI("%{public}s, callingUid: %{public}d", __func__, callingUid); + APP_LOGI("%{public}s, callingUid: %{public}d", __func__, callingUid); if (formRecords_.size() - tempForms_.size() >= Constants::MAX_FORMS) { APP_LOGW("%{public}s, already exist %{public}d forms in system", __func__, Constants::MAX_FORMS); - return ERR_MAX_SYSTEM_FORMS; + return ERR_APPEXECFWK_FORM_MAX_SYSTEM_FORMS; } int callingUidFormCounts = 0; @@ -246,10 +220,9 @@ int FormDataMgr::CheckEnoughForm(const int callingUid) const if (IsCallingUidValid(record.formUserUids) && !record.formTempFlg) { for (auto &userUid : record.formUserUids) { if (userUid == callingUid) { - if (++callingUidFormCounts >= Constants::MAX_RECORD_PER_APP) - { + if (++callingUidFormCounts >= Constants::MAX_RECORD_PER_APP) { APP_LOGW("%{public}s, already use %{public}d forms", __func__, Constants::MAX_RECORD_PER_APP); - return ERR_MAX_RECORDS_PER_APP; + return ERR_APPEXECFWK_FORM_MAX_FORMS_PER_CLIENT; } } } @@ -268,7 +241,7 @@ bool FormDataMgr::DeleteTempForm(const int64_t formId) auto iter = std::find(tempForms_.begin(), tempForms_.end(), formId); if (iter == tempForms_.end()) { APP_LOGE("%{public}s, temp form is not exist", __func__); - return true; + return false; } tempForms_.erase(iter); return true; @@ -346,8 +319,8 @@ bool FormDataMgr::DeleteFormUserUid(const int64_t formId, const int32_t uid) APP_LOGI("%{public}s, delete form user uid from form record", __func__); std::lock_guard lock(formRecordMutex_); if (ExistFormRecord(formId)) { - auto iter = std::find(formRecords_.at(formId).formUserUids.begin(), formRecords_.at(formId).formUserUids.end(), - uid); + auto iter = std::find(formRecords_.at(formId).formUserUids.begin(), + formRecords_.at(formId).formUserUids.end(), uid); if (iter != formRecords_.at(formId).formUserUids.end()) { formRecords_.at(formId).formUserUids.erase(iter); } @@ -405,7 +378,7 @@ bool FormDataMgr::GetFormRecord(const std::string &bundleName, std::vector lock(formRecordMutex_); std::map::iterator itFormRecord; - for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();itFormRecord++) { + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); itFormRecord++) { if (bundleName == itFormRecord->second.bundleName) { formInfos.emplace_back(itFormRecord->second); } @@ -495,7 +468,7 @@ void FormDataMgr::CleanHostRemovedForms(const std::vector &removedFormI std::vector matchedIds; std::lock_guard lock(formHostRecordMutex_); std::vector::iterator itHostRecord; - for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();itHostRecord++) { + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end(); itHostRecord++) { for (const int64_t& formId : removedFormIds) { if (itHostRecord->Contains(formId)) { matchedIds.emplace_back(formId); @@ -520,7 +493,7 @@ void FormDataMgr::HandleHostDied(const sptr &remoteHost) { std::lock_guard lock(formHostRecordMutex_); std::vector::iterator itHostRecord; - for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();) { + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end(); ) { if (remoteHost == itHostRecord->GetClientStub()) { HandleHostDiedForTempForms(*itHostRecord, recordTempForms); APP_LOGI("find died client, remove it"); @@ -535,7 +508,7 @@ void FormDataMgr::HandleHostDied(const sptr &remoteHost) { std::lock_guard lock(formRecordMutex_); std::map::iterator itFormRecord; - for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();) { + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); ) { int64_t formId = itFormRecord->first; // if temp form, remove it if (std::find(recordTempForms.begin(), recordTempForms.end(), formId) != recordTempForms.end()) { @@ -558,7 +531,7 @@ void FormDataMgr::HandleHostDiedForTempForms(const FormHostRecord &record, std:: { std::lock_guard lock(formTempMutex_); std::vector::iterator itForm; - for (itForm = tempForms_.begin(); itForm != tempForms_.end();) { + for (itForm = tempForms_.begin(); itForm != tempForms_.end(); ) { if (record.Contains(*itForm)) { recordTempForms.emplace_back(*itForm); itForm = tempForms_.erase(itForm); @@ -590,6 +563,11 @@ bool FormDataMgr::IsEnableRefresh(int64_t formId) */ int64_t FormDataMgr::GenerateFormId() { + // generate udidHash_ + if (udidHash_ < 0) { + APP_LOGE("%{public}s fail, generateFormId no invalid udidHash_", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } return FormUtil::GenerateFormId(udidHash_); } /** @@ -688,8 +666,10 @@ void FormDataMgr::SetCountTimerRefresh(const int64_t formId, const bool countTim * @param updatedForm Updated formnfo. * @return Returns true on success, false on failure. */ -bool FormDataMgr::GetUpdatedForm(const FormRecord &record, const std::vector &targetForms, -FormInfo &updatedForm) +bool FormDataMgr::GetUpdatedForm( + const FormRecord &record, + const std::vector &targetForms, + FormInfo &updatedForm) { if (targetForms.empty()) { APP_LOGE("%{public}s error, targetForms is empty.", __func__); @@ -728,8 +708,12 @@ void FormDataMgr::SetEnableUpdate(const int64_t formId, const bool enableUpdate) * @param updateAtHour Update at hour. * @param updateAtMin Update at minute. */ -void FormDataMgr::SetUpdateInfo(const int64_t formId, const bool enableUpdate, const long updateDuration, -const int updateAtHour, const int updateAtMin) +void FormDataMgr::SetUpdateInfo( + const int64_t formId, + const bool enableUpdate, + const long updateDuration, + const int updateAtHour, + const int updateAtMin) { std::lock_guard lock(formRecordMutex_); auto itFormRecord = formRecords_.find(formId); @@ -771,12 +755,11 @@ void FormDataMgr::CleanRemovedFormRecords(const std::string &bundleName, std::se APP_LOGI("%{public}s, clean removed form records", __func__); std::lock_guard lock(formRecordMutex_); std::map::iterator itFormRecord; - for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();) { + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); ) { auto itForm = std::find(removedForms.begin(), removedForms.end(), itFormRecord->first); if (itForm != removedForms.end()) { itFormRecord = formRecords_.erase(itFormRecord); - } - else { + } else { itFormRecord++; } } @@ -793,12 +776,11 @@ void FormDataMgr::CleanRemovedTempFormRecords(const std::string &bundleName, std { std::lock_guard lock(formRecordMutex_); std::map::iterator itFormRecord; - for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();) { + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); ) { if (itFormRecord->second.formTempFlg && bundleName == itFormRecord->second.bundleName) { removedTempForms.emplace(itFormRecord->second.formId); itFormRecord = formRecords_.erase(itFormRecord); - } - else { + } else { itFormRecord++; } } @@ -807,8 +789,8 @@ void FormDataMgr::CleanRemovedTempFormRecords(const std::string &bundleName, std if (removedTempForms.size() > 0) { std::lock_guard lock(formTempMutex_); std::vector::iterator itTemp; - for(itTemp = tempForms_.begin();itTemp != tempForms_.end();) { - if(removedTempForms.find(*itTemp) != removedTempForms.end()) { + for (itTemp = tempForms_.begin();itTemp != tempForms_.end(); ) { + if (removedTempForms.find(*itTemp) != removedTempForms.end()) { itTemp = tempForms_.erase(itTemp); } else { itTemp++; @@ -825,7 +807,7 @@ void FormDataMgr::GetReCreateFormRecordsByBundleName(const std::string &bundleNa { std::lock_guard lock(formRecordMutex_); std::map::iterator itFormRecord; - for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();itFormRecord++) { + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); itFormRecord++) { if (bundleName == itFormRecord->second.bundleName) { reCreateForms.emplace(itFormRecord->second.formId); } @@ -871,12 +853,28 @@ void FormDataMgr::UpdateHostNeedRefresh(const int64_t formId, const bool needRef { std::lock_guard lock(formHostRecordMutex_); std::vector::iterator itHostRecord; - for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();itHostRecord++) { + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end(); itHostRecord++) { if (itHostRecord->Contains(formId)) { itHostRecord->SetNeedRefresh(formId, needRefresh); } } } + +/** + * @brief Update form for host clients. + * @param formId The Id of the form. + * @param formProviderInfo FormProviderInfo object + */ +void FormDataMgr::UpdateFormProviderInfo(const int64_t formId, const FormProviderInfo &formProviderInfo) +{ + std::lock_guard lock(formRecordMutex_); + auto itFormRecord = formRecords_.find(formId); + if (itFormRecord == formRecords_.end()) { + APP_LOGE("%{public}s, form info not find", __func__); + return; + } + itFormRecord->second.formProviderInfo = formProviderInfo; +} /** * @brief Update form for host clients. * @param formId The Id of the form. @@ -888,7 +886,7 @@ bool FormDataMgr::UpdateHostForm(const int64_t formId, const FormRecord &formRec bool isUpdated = false; std::lock_guard lock(formHostRecordMutex_); std::vector::iterator itHostRecord; - for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();itHostRecord++) { + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end(); itHostRecord++) { if (itHostRecord->IsEnableRefresh(formId)) { // update form itHostRecord->OnUpdate(formId, formRecord); @@ -907,13 +905,16 @@ bool FormDataMgr::UpdateHostForm(const int64_t formId, const FormRecord &formRec * @param refreshForms Refresh forms * @return Returns ERR_OK on success, others on failure. */ -int32_t FormDataMgr::UpdateHostFormFlag(std::vector formIds, const sptr &callerToken, -const bool flag, std::vector &refreshForms) +int32_t FormDataMgr::UpdateHostFormFlag( + std::vector formIds, + const sptr &callerToken, + const bool flag, + std::vector &refreshForms) { APP_LOGI("%{public}s start, flag: %{public}d", __func__, flag); std::lock_guard lock(formHostRecordMutex_); std::vector::iterator itHostRecord; - for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();itHostRecord++) { + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end(); itHostRecord++) { if (callerToken == itHostRecord->GetClientStub()) { for (const int64_t formId : formIds) { if (formId <= 0) { @@ -967,7 +968,7 @@ const bool flag, std::vector &refreshForms) } } APP_LOGE("%{public}s, can't find target client", __func__); - return ERR_FORM_INVALID_PARAM; + return ERR_APPEXECFWK_FORM_INVALID_PARAM; } /** * @brief Find matched form id. @@ -976,13 +977,16 @@ const bool flag, std::vector &refreshForms) */ int64_t FormDataMgr::FindMatchedFormId(const int64_t formId) { - if ((formId & 0xffffffff00000000L) != 0) { + uint64_t unsignedFormId = static_cast(formId); + if ((unsignedFormId & 0xffffffff00000000L) != 0) { return formId; } std::lock_guard lock(formRecordMutex_); std::map::iterator itFormRecord; - for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();itFormRecord++) { - if ((itFormRecord->first & 0x00000000ffffffffL) == (formId & 0x00000000ffffffffL)) { + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); itFormRecord++) { + uint64_t unsignedFormId = static_cast(formId); + uint64_t unsignedItFormRecordFirst = static_cast(itFormRecord->first); + if ((unsignedItFormRecordFirst & 0x00000000ffffffffL) == (unsignedFormId & 0x00000000ffffffffL)) { return itFormRecord->first; } } @@ -997,7 +1001,7 @@ void FormDataMgr::ClearHostDataByUId(const int uId) { std::lock_guard lock(formHostRecordMutex_); std::vector::iterator itHostRecord; - for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();) { + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end(); ) { if (itHostRecord->GetCallerUid() == uId) { itHostRecord->CleanResource(); itHostRecord = clientRecords_.erase(itHostRecord); @@ -1012,21 +1016,27 @@ void FormDataMgr::ClearHostDataByUId(const int uId) * @param noHostTempFormsMap no host temp forms. * @param foundFormsMap Form Id list. */ -void FormDataMgr::GetNoHostTempForms(const int uid, std::map> &noHostTempFormsMap, -std::map &foundFormsMap) +void FormDataMgr::GetNoHostTempForms( + const int uid, std::map> &noHostTempFormsMap, + std::map &foundFormsMap) { std::lock_guard lock(formRecordMutex_); std::map::iterator itFormRecord; - for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();itFormRecord++) { + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); itFormRecord++) { if (itFormRecord->second.formTempFlg) { - auto itUid = std::find(itFormRecord->second.formUserUids.begin(), itFormRecord->second.formUserUids.end(), - uid); + auto itUid = std::find(itFormRecord->second.formUserUids.begin(), + itFormRecord->second.formUserUids.end(), uid); if (itUid != itFormRecord->second.formUserUids.end()) { itFormRecord->second.formUserUids.erase(itUid); if (itFormRecord->second.formUserUids.empty()) { FormIdKey formIdKey; formIdKey.bundleName = itFormRecord->second.bundleName; formIdKey.abilityName = itFormRecord->second.abilityName; + formIdKey.moduleName = ""; + formIdKey.formName = ""; + formIdKey.specificationId = 0; + formIdKey.orientation = 0; auto itIdsSet = noHostTempFormsMap.find(formIdKey); if (itIdsSet == noHostTempFormsMap.end()) { std::set formIdsSet; @@ -1079,7 +1089,8 @@ void FormDataMgr::ParseIntervalConfig(FormRecord &record, const int configDurati * @param record The form record. * @param info form item info. */ -void FormDataMgr::ParseAtTimerConfig(FormRecord record, const FormItemInfo &info) const { +void FormDataMgr::ParseAtTimerConfig(FormRecord &record, const FormItemInfo &info) const +{ record.isEnableUpdate = false; record.updateDuration = 0; std::string configAtTime = info.GetScheduledUpdateTime(); @@ -1103,7 +1114,7 @@ void FormDataMgr::ParseAtTimerConfig(FormRecord record, const FormItemInfo &info } if (hour < Constants::MIN_TIME || hour > Constants::MAX_HOUR || min < Constants::MIN_TIME || min > - Constants::MAX_MININUTE) { + Constants::MAX_MININUTE) { APP_LOGE("%{public}s, time is invalid", __func__); return; } diff --git a/services/formmgr/src/form_db_cache.cpp b/services/formmgr/src/form_db_cache.cpp index a866048f6fa5622dd828c73af757682414b17062..1625e676ecb3846927d9455dcf13606a3ee893f5 100644 --- a/services/formmgr/src/form_db_cache.cpp +++ b/services/formmgr/src/form_db_cache.cpp @@ -56,12 +56,6 @@ void FormDbCache::Start() } } -// void FormDbCache::Stop() -// { -// APP_LOGI("stop"); -// dataStorage_->Stop(); -// } - /** * @brief Save or update form data to DbCache and DB. * @param formDBInfo Form data. @@ -134,7 +128,7 @@ ErrCode FormDbCache::DeleteFormInfo(int64_t formId) if (dataStorage_->DeleteStorageFormInfo(std::to_string(formId)) == ERR_OK) { return ERR_OK; } else { - return ERR_APPEXECFWK_FORM_JSON_DELETE_FAIL; + return ERR_APPEXECFWK_FORM_COMMON_CODE; } } /** @@ -147,7 +141,7 @@ ErrCode FormDbCache::DeleteFormInfoByBundleName(const std::string &bundleName, s { std::lock_guard lock(formDBInfosMutex_); std::vector::iterator itRecord; - for (itRecord = formDBInfos_.begin(); itRecord != formDBInfos_.end();) { + for (itRecord = formDBInfos_.begin(); itRecord != formDBInfos_.end(); ) { if (bundleName == itRecord->bundleName) { int64_t formId = itRecord->formId; if (dataStorage_->DeleteStorageFormInfo(std::to_string(formId)) == ERR_OK) { @@ -162,19 +156,6 @@ ErrCode FormDbCache::DeleteFormInfoByBundleName(const std::string &bundleName, s } return ERR_OK; } -// bool FormDbCache::BatchDeleteForms(std::vector formIds) -// { -// std::lock_guard lock(formDBInfosMutex_); -// for (const auto& formId : formIds) { -// FormDBInfo tmpForm; -// tmpForm.formId_ = formId; -// auto iter = find(formDBInfos_.begin(), formDBInfos_.end(), tmpForm); -// if (iter != formDBInfos_.end()) { -// formDBInfos_.erase(iter); -// } -// } -// return dataStorage_->BatchDeleteForms(formIds); -// } /** * @brief Get all form data from DbCache. @@ -208,7 +189,7 @@ ErrCode FormDbCache::GetDBRecord(const int64_t formId, FormRecord &record) const } } APP_LOGE("%{public}s, not find formId[%{public}" PRId64 "]", __func__, formId); - return ERR_APPEXECFWK_FORM_DBCACHE_FIND_FAIL; + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; } /** * @brief Get record from DB cache with formId @@ -226,7 +207,7 @@ ErrCode FormDbCache::GetDBRecord(const int64_t formId, FormDBInfo &record) const } } APP_LOGE("%{public}s, not find formId[%{public}" PRId64 "]", __func__, formId); - return ERR_APPEXECFWK_FORM_DBCACHE_FIND_FAIL; + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; } /** * @brief Use record save or update DB data and DB cache with formId @@ -238,7 +219,6 @@ ErrCode FormDbCache::UpdateDBRecord(const int64_t formId, const FormRecord &reco { FormDBInfo formDBInfo(formId, record); return FormDbCache::GetInstance().SaveFormInfo(formDBInfo); - // FormBmsHelper::GetInstance().NotifyModuleNotRemovable(formDBInfo.bundleName, formDBInfo.moduleName); } /** * @brief Get no host db record. @@ -247,8 +227,8 @@ ErrCode FormDbCache::UpdateDBRecord(const int64_t formId, const FormRecord &reco * @param foundFormsMap Form Id list. * @return Returns ERR_OK on success, others on failure. */ -ErrCode FormDbCache::GetNoHostDBForms(const int uid, std::map> &noHostFormDBList, -std::map &foundFormsMap) +ErrCode FormDbCache::GetNoHostDBForms(const int uid, std::map> &noHostFormDBList, std::map &foundFormsMap) { std::lock_guard lock(formDBInfosMutex_); for (FormDBInfo& dbInfo : formDBInfos_) { @@ -258,6 +238,10 @@ std::map &foundFormsMap) FormIdKey formIdKey; formIdKey.bundleName = dbInfo.bundleName; formIdKey.abilityName = dbInfo.abilityName; + formIdKey.moduleName = ""; + formIdKey.formName = ""; + formIdKey.specificationId = 0; + formIdKey.orientation = 0; auto itIdsSet = noHostFormDBList.find(formIdKey); if (itIdsSet == noHostFormDBList.end()) { std::set formIdsSet; diff --git a/services/formmgr/src/form_db_info.cpp b/services/formmgr/src/form_db_info.cpp index 4846b9bf795b361060a1411c929149d0d1a08cc0..f47f45c4f75f789c13fe28dee49f1ad376f98ba4 100644 --- a/services/formmgr/src/form_db_info.cpp +++ b/services/formmgr/src/form_db_info.cpp @@ -1,135 +1,79 @@ -/* - * 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 "app_log_wrapper.h" -#include "form_db_info.h" -namespace OHOS { -namespace AppExecFwk { -namespace { -const std::string FORM_ID = "formId"; -const std::string FORM_NAME = "formName"; -const std::string BUNDLE_NAME = "bundleName"; -const std::string MODULE_NAME = "moduleName"; -const std::string ABILITY_NAME = "abilityName"; -const std::string FORM_USER_UIDS = "formUserUids"; -} - -// void to_json(nlohmann::json &jsonObject, const FormDBInfo &info) -// { -// jsonObject = nlohmann::json{ -// {FORM_ID, info.formId}, -// {USER_ID, info.userId}, -// {BUNDLE_NAME, info.bundleName}, -// {MODULE_NAME, info.moduleName}, -// {ABILITY_NAME, info.abilityName}, -// {FORM_USER_UIDS, info.formUserUids} -// }; -// } - -/** - * @brief Transform the InnerFormInfo object to json. - * @param jsonObject Indicates the obtained json object. - * @return - */ -void InnerFormInfo::ToJson(nlohmann::json &jsonObject) const -{ - jsonObject[FORM_ID] = formDBInfo_.formId; - jsonObject[FORM_NAME] = formDBInfo_.formName; - jsonObject[BUNDLE_NAME] = formDBInfo_.bundleName; - jsonObject[MODULE_NAME] = formDBInfo_.moduleName; - jsonObject[ABILITY_NAME] = formDBInfo_.abilityName; - jsonObject[FORM_USER_UIDS] = formDBInfo_.formUserUids; -} - -// void from_json(const nlohmann::json &jsonObject, FormDBInfo &info) -// { -// const auto &jsonObjectEnd = jsonObject.end(); -// if (jsonObject.find(FORM_ID) != jsonObjectEnd) { -// info.formId = jsonObject.at(FORM_ID).get(); -// } - -// if (jsonObject.find(USER_ID) != jsonObjectEnd) { -// info.userId = jsonObject.at(USER_ID).get(); -// } - -// if (jsonObject.find(BUNDLE_NAME) != jsonObjectEnd) { -// info.bundleName = jsonObject.at(BUNDLE_NAME).get(); -// } - -// if (jsonObject.find(MODULE_NAME) != jsonObjectEnd) { -// info.moduleName = jsonObject.at(MODULE_NAME).get(); -// } - -// if (jsonObject.find(ABILITY_NAME) != jsonObjectEnd) { -// info.abilityName = jsonObject.at(ABILITY_NAME).get(); -// } - -// if (jsonObject.find(FORM_USER_UIDS) != jsonObjectEnd) { -// info.formUserUids = jsonObject.at(FORM_USER_UIDS).get>(); -// } -// } - -/** - * @brief Transform the json object to InnerFormInfo object. - * @param jsonObject Indicates the obtained json object. - * @return - */ -bool InnerFormInfo::FromJson(const nlohmann::json &jsonObject) -{ - // try { - formDBInfo_.formId = jsonObject.at(FORM_ID).get(); - formDBInfo_.formName = jsonObject.at(FORM_NAME).get(); - formDBInfo_.bundleName = jsonObject.at(BUNDLE_NAME).get(); - formDBInfo_.moduleName = jsonObject.at(MODULE_NAME).get(); - formDBInfo_.abilityName = jsonObject.at(ABILITY_NAME).get(); - formDBInfo_.formUserUids = jsonObject.at(FORM_USER_UIDS).get>(); - - // } catch (nlohmann::detail::parse_error &exception) { - // APP_LOGE("%{public}s, has a parse_error:%{public}s", __func__, exception.what()); - // return false; - // } catch (nlohmann::detail::type_error &exception) { - // APP_LOGE("%{public}s, has a type_error:%{public}s.", __func__, exception.what()); - // return false; - // } catch (nlohmann::detail::out_of_range &exception) { - // APP_LOGE("%{public}s, has an out_of_range exception:%{public}s.", __func__, exception.what()); - // return false; - // } catch(...) { - // APP_LOGE("%{public}s, other exception", __func__); - // return false; - // } - return true; -} - -void InnerFormInfo::AddUserUid(const int callingUid) -{ - // std::lock_guard lock(mutex_); - auto iter = std::find(formDBInfo_.formUserUids.begin(), formDBInfo_.formUserUids.end(), callingUid); - if (iter == formDBInfo_.formUserUids.end()) { - formDBInfo_.formUserUids.push_back(callingUid); - } -} - -bool InnerFormInfo::DeleteUserUid(const int callingUid) -{ - // std::lock_guard lock(mutex_); - auto iter = std::find(formDBInfo_.formUserUids.begin(), formDBInfo_.formUserUids.end(), callingUid); - if (iter == formDBInfo_.formUserUids.end()) { - return false; - } - formDBInfo_.formUserUids.erase(iter); - return true; -} -} // namespace AppExecFwk +/* + * 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 "app_log_wrapper.h" +#include "form_db_info.h" +namespace OHOS { +namespace AppExecFwk { +namespace { +const std::string FORM_ID = "formId"; +const std::string FORM_NAME = "formName"; +const std::string BUNDLE_NAME = "bundleName"; +const std::string MODULE_NAME = "moduleName"; +const std::string ABILITY_NAME = "abilityName"; +const std::string FORM_USER_UIDS = "formUserUids"; +} + +/** + * @brief Transform the InnerFormInfo object to json. + * @param jsonObject Indicates the obtained json object. + * @return + */ +void InnerFormInfo::ToJson(nlohmann::json &jsonObject) const +{ + jsonObject[FORM_ID] = formDBInfo_.formId; + jsonObject[FORM_NAME] = formDBInfo_.formName; + jsonObject[BUNDLE_NAME] = formDBInfo_.bundleName; + jsonObject[MODULE_NAME] = formDBInfo_.moduleName; + jsonObject[ABILITY_NAME] = formDBInfo_.abilityName; + jsonObject[FORM_USER_UIDS] = formDBInfo_.formUserUids; +} + +/** + * @brief Transform the json object to InnerFormInfo object. + * @param jsonObject Indicates the obtained json object. + * @return + */ +bool InnerFormInfo::FromJson(const nlohmann::json &jsonObject) +{ + formDBInfo_.formId = jsonObject.at(FORM_ID).get(); + formDBInfo_.formName = jsonObject.at(FORM_NAME).get(); + formDBInfo_.bundleName = jsonObject.at(BUNDLE_NAME).get(); + formDBInfo_.moduleName = jsonObject.at(MODULE_NAME).get(); + formDBInfo_.abilityName = jsonObject.at(ABILITY_NAME).get(); + formDBInfo_.formUserUids = jsonObject.at(FORM_USER_UIDS).get>(); + + return true; +} + +void InnerFormInfo::AddUserUid(const int callingUid) +{ + auto iter = std::find(formDBInfo_.formUserUids.begin(), formDBInfo_.formUserUids.end(), callingUid); + if (iter == formDBInfo_.formUserUids.end()) { + formDBInfo_.formUserUids.push_back(callingUid); + } +} + +bool InnerFormInfo::DeleteUserUid(const int callingUid) +{ + auto iter = std::find(formDBInfo_.formUserUids.begin(), formDBInfo_.formUserUids.end(), callingUid); + if (iter == formDBInfo_.formUserUids.end()) { + return false; + } + formDBInfo_.formUserUids.erase(iter); + return true; +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_delete_connection.cpp b/services/formmgr/src/form_delete_connection.cpp index 40312f1beeccb37689204681b6486c3280ebfb38..77e3ea378936cb8c57ec61c6259a9f698c48427c 100755 --- a/services/formmgr/src/form_delete_connection.cpp +++ b/services/formmgr/src/form_delete_connection.cpp @@ -1,58 +1,60 @@ - -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include "appexecfwk_errors.h" -#include "app_log_wrapper.h" -#include "form_constants.h" -#include "form_delete_connection.h" -#include "form_supply_callback.h" -#include "form_task_mgr.h" -#include "ipc_types.h" -#include "message_parcel.h" -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -FormDeleteConnection::FormDeleteConnection(const int64_t formId) - :formId_(formId) -{ -} -/** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * @param element service ability's ElementName. - * @param remoteObject the session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - */ -void FormDeleteConnection::OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) -{ - APP_LOGI("%{public}s called.", __func__); - if (resultCode != ERR_OK) { - APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", - __func__, element.GetAbilityName().c_str(), formId_, resultCode); - return; - } - FormSupplyCallback::GetInstance()->AddConnection(this); - - Want want; - want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); - APP_LOGD("%{public}s, connectId :%{public}ld", __func__, this->GetConnectId()); - FormTaskMgr::GetInstance().PostDeleteTask(formId_, want, remoteObject); -} -} // namespace AppExecFwk + +/* + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_delete_connection.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormDeleteConnection::FormDeleteConnection(const int64_t formId, const std::string &bundleName, + const std::string &abilityName) + :formId_(formId) +{ + SetProviderKey(bundleName, abilityName); +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ +void FormDeleteConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + + Want want; + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + APP_LOGD("%{public}s, connectId :%{public}ld", __func__, this->GetConnectId()); + FormTaskMgr::GetInstance().PostDeleteTask(formId_, want, remoteObject); +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_dump_mgr.cpp b/services/formmgr/src/form_dump_mgr.cpp index 0f89ca359dc4b799450e191d1f5a8a6e5648ef29..1961cc2ff567e81ad602ff5d431a8607d19c1320 100644 --- a/services/formmgr/src/form_dump_mgr.cpp +++ b/services/formmgr/src/form_dump_mgr.cpp @@ -146,7 +146,7 @@ void FormDumpMgr::DumpFormInfo(const FormRecord &formRecordInfo, std::string &fo if (formRecordInfo.formUserUids.size() > 0) { formInfo += " formUserUids ["; for (auto &uId : formRecordInfo.formUserUids) { - formInfo +=" Uid [" + std::to_string(uId) + "]"; + formInfo += " Uid [" + std::to_string(uId) + "]"; } formInfo += "]"; } diff --git a/services/formmgr/src/form_event_notify_connection.cpp b/services/formmgr/src/form_event_notify_connection.cpp index cea26ab8e3ff06a79d7343523a70ae7476862f77..6933e3887e49ab5066893b3adc6719ad917ca930 100644 --- a/services/formmgr/src/form_event_notify_connection.cpp +++ b/services/formmgr/src/form_event_notify_connection.cpp @@ -1,60 +1,60 @@ - -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "appexecfwk_errors.h" -#include "app_log_wrapper.h" -#include "form_constants.h" -#include "form_event_notify_connection.h" -#include "form_supply_callback.h" -#include "form_task_mgr.h" -#include "ipc_types.h" -#include "message_parcel.h" -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -FormEventNotifyConnection::FormEventNotifyConnection(const std::vector formEvents, -const int32_t formVisibleType) - :formEvents_(formEvents), - formVisibleType_(formVisibleType) -{ -} -/** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * - * @param element Service ability's ElementName. - * @param remoteObject The session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - * @return none. - */ -void FormEventNotifyConnection::OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) -{ - APP_LOGI("%{public}s called.", __func__); - - if (resultCode != ERR_OK) { - APP_LOGE("%{public}s, abilityName:%{public}s, resultCode:%{public}d", - __func__, element.GetAbilityName().c_str(), resultCode); - return; - } - FormSupplyCallback::GetInstance()->AddConnection(this); - - Want want; - want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); - FormTaskMgr::GetInstance().PostEventNotifyTask(formEvents_, formVisibleType_, want, remoteObject); -} -} // namespace AppExecFwk + +/* + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_event_notify_connection.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormEventNotifyConnection::FormEventNotifyConnection(const std::vector formEvents, + const int32_t formVisibleType, const std::string &bundleName, const std::string &abilityName) + :formEvents_(formEvents), + formVisibleType_(formVisibleType) +{ + SetProviderKey(bundleName, abilityName); +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element Service ability's ElementName. + * @param remoteObject The session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + * @return none. + */ +void FormEventNotifyConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + + Want want; + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostEventNotifyTask(formEvents_, formVisibleType_, want, remoteObject); +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_host_callback.cpp b/services/formmgr/src/form_host_callback.cpp index 2bcae1eb5906fb2f89a8a1581891982cc390d6fa..6348112c8112b8d0a394314fd785b88985619862 100644 --- a/services/formmgr/src/form_host_callback.cpp +++ b/services/formmgr/src/form_host_callback.cpp @@ -32,7 +32,7 @@ namespace AppExecFwk { * @return Returns ERR_OK on success, others on failure. */ void FormHostCallback::OnAcquired(const int64_t formId, const FormRecord& record, -const sptr &callerToken) + const sptr &callerToken) { APP_LOGD("FormHostCallback OnAcquired, formId:%{public}" PRId64 "", formId); FormTaskMgr::GetInstance().PostAcquireTaskToHost(formId, record, callerToken); diff --git a/services/formmgr/src/form_host_record.cpp b/services/formmgr/src/form_host_record.cpp index 7b276a1c8b7bface38ece447b3a13c09c3f949ec..2644d0273c280c46033eaaccd1db0547d996dbe2 100644 --- a/services/formmgr/src/form_host_record.cpp +++ b/services/formmgr/src/form_host_record.cpp @@ -1,270 +1,270 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "form_host_record.h" -#include "form_task_mgr.h" - -namespace OHOS { -namespace AppExecFwk { -/** - * @brief Add form id. - * @param formId The Id of the form. - */ -void FormHostRecord::AddForm(int64_t formId) -{ - if (forms_.find(formId) != forms_.end()) { - return; - } - forms_[formId] = true; -} -/** - * @brief Delete form id. - * @param formId The Id of the form. - */ -void FormHostRecord::DelForm(int64_t formId) -{ - forms_.erase(formId); -} -/** - * @brief forms_ is empty or not. - * @return forms_ is empty or not. - */ -bool FormHostRecord::IsEmpty() const -{ - return forms_.empty(); -} -/** - * @brief formId is in forms_ or not. - * @param formId The Id of the form. - * @return formId is in forms_ or not. - */ -bool FormHostRecord::Contains(int64_t formId) const -{ - return forms_.find(formId) != forms_.end(); -} - -/** - * @brief Set refresh enable flag. - * @param formId The Id of the form. - * @param flag True for enbale, false for disable. - */ -void FormHostRecord::SetEnableRefresh(int64_t formId, bool flag) -{ - if (forms_.find(formId) == forms_.end()) { - return; - } - forms_[formId] = flag; -} -/** - * @brief Refresh enable or not. - * @param formId The Id of the form. - * @return true on enbale, false on disable.. - */ -bool FormHostRecord::IsEnableRefresh(int64_t formId) const -{ - auto result = forms_.find(formId); - if (result != forms_.end()) { - return result->second; - } - return false; -} -/** - * @brief Set need refresh enable flag. - * @param formId The Id of the form. - * @param flag True for enbale, false for disable. - */ -void FormHostRecord::SetNeedRefresh(int64_t formId, bool flag) -{ - needRefresh_[formId] = flag; -} -/** - * @brief Need Refresh enable or not. - * @param formId The Id of the form. - * @return true on enbale, false on disable.. - */ -bool FormHostRecord::IsNeedRefresh(int64_t formId) const -{ - auto result = needRefresh_.find(formId); - if (result != needRefresh_.end()) { - return result->second; - } - return false; -} -/** - * @brief Get clientStub_. - * @return clientStub_. - */ -sptr FormHostRecord::GetClientStub() const -{ - return clientStub_; -} - -/** - * @brief Send form data to form host. - * @param id The Id of the form. - * @param record Form record. - */ -void FormHostRecord::OnAcquire(int64_t id, const FormRecord &record) -{ - APP_LOGD("FormHostRecord OnAcquire"); - if (clientImpl_ == nullptr) { - APP_LOGE("%{public}s: clientImpl_ can not be NULL", __func__); - return; - } - - clientImpl_->OnAcquired(id, record, clientStub_); -} - -/** - * @brief Update form data to form host. - * @param id The Id of the form. - * @param record Form record. - */ -void FormHostRecord::OnUpdate(int64_t id, const FormRecord &record) -{ - APP_LOGI("%{public}s start.", __func__); - - if (clientImpl_ == nullptr) { - APP_LOGE("%{public}s: clientImpl_ can not be null.", __func__); - return; - } - - clientImpl_->OnUpdate(id, record, clientStub_); -} - -/** - * @brief Send form uninstall message to form host. - * @param id The Id of the form. - * @param record Form record. - */ -void FormHostRecord::OnFormUninstalled(std::vector &formIds) -{ - APP_LOGI("%{public}s start.", __func__); - - if (clientImpl_ == nullptr) { - APP_LOGE("%{public}s: clientImpl_ can not be null.", __func__); - return; - } - clientImpl_->OnUninstall(formIds, clientStub_); -} -/** - * @brief Release resource. - * @param id The Id of the form. - * @param record Form record. - */ -void FormHostRecord::CleanResource() -{ - if (clientStub_ != nullptr && deathRecipient_ != nullptr) { - clientStub_->RemoveDeathRecipient(deathRecipient_); - clientStub_ = nullptr; - deathRecipient_ = nullptr; - } -} -/** - * @brief Set value of callerUid_. - * @param callerUid Caller uid. - */ -void FormHostRecord::SetCallerUid(const int callerUid) -{ - callerUid_ = callerUid; -} -/** - * @brief Set value of clientStub_. - * @param clientStub remote object. - */ -void FormHostRecord::SetClientStub(const sptr &clientStub) -{ - clientStub_ = clientStub; -} -/** - * @brief Set value of clientImpl_. - * @param clientImpl Form host callback object. - */ -void FormHostRecord::SetClientImpl(const std::shared_ptr &clientImpl) -{ - clientImpl_ = clientImpl; -} -/** - * @brief Get deathRecipient_. - * @return deathRecipient_. - */ -sptr FormHostRecord::GetDeathRecipient() const -{ - return deathRecipient_; -} -/** - * @brief Set value of deathRecipient_. - * @param clientImpl DeathRecipient object. - */ -void FormHostRecord::SetDeathRecipient(const sptr &deathRecipient) -{ - deathRecipient_ = deathRecipient; -} -/** - * @brief Add deathRecipient object to clientStub_. - * @param deathRecipient DeathRecipient object. - */ -void FormHostRecord::AddDeathRecipient(const sptr &deathRecipient) -{ - clientStub_->AddDeathRecipient(deathRecipient); -} - -/** - * @brief Create form host record. - * @param info The form item info. - * @param callback remote object. - * @param callingUid Calling uid. - */ -FormHostRecord FormHostRecord::CreateRecord(const FormItemInfo &info, const sptr &callback, -int callingUid) -{ - FormHostRecord record; - record.SetHostBundleName(info.GetHostBundleName()); - record.SetCallerUid(callingUid); - record.SetClientStub(callback); - record.SetClientImpl(std::make_shared()); - record.SetDeathRecipient(new FormHostRecord::ClientDeathRecipient()); - record.AddDeathRecipient(record.GetDeathRecipient()); - - return record; -} - -/** - * @brief handle remote object died event. - * @param remote remote object. - */ -void FormHostRecord::ClientDeathRecipient::OnRemoteDied(const wptr &remote) -{ - APP_LOGD("Form remote died"); - FormTaskMgr::GetInstance().PostHostDiedTask(remote.promote()); -} - -/** - * @brief Get hostBundleName_. - * @return hostBundleName_. - */ -std::string FormHostRecord::GetHostBundleName() const -{ - return hostBundleName_; -} -/** - * @brief Set hostBundleName_. - * @param hostBandleName Host bundle name. - */ -void FormHostRecord::SetHostBundleName(const std::string &hostBundleName) -{ - hostBundleName_ = hostBundleName; -} -} // namespace AppExecFwk -} // namespace OHOS +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "form_host_record.h" +#include "form_task_mgr.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Add form id. + * @param formId The Id of the form. + */ +void FormHostRecord::AddForm(int64_t formId) +{ + if (forms_.find(formId) != forms_.end()) { + return; + } + forms_[formId] = true; +} +/** + * @brief Delete form id. + * @param formId The Id of the form. + */ +void FormHostRecord::DelForm(int64_t formId) +{ + forms_.erase(formId); +} +/** + * @brief forms_ is empty or not. + * @return forms_ is empty or not. + */ +bool FormHostRecord::IsEmpty() const +{ + return forms_.empty(); +} +/** + * @brief formId is in forms_ or not. + * @param formId The Id of the form. + * @return formId is in forms_ or not. + */ +bool FormHostRecord::Contains(int64_t formId) const +{ + return forms_.find(formId) != forms_.end(); +} + +/** + * @brief Set refresh enable flag. + * @param formId The Id of the form. + * @param flag True for enbale, false for disable. + */ +void FormHostRecord::SetEnableRefresh(int64_t formId, bool flag) +{ + if (forms_.find(formId) == forms_.end()) { + return; + } + forms_[formId] = flag; +} +/** + * @brief Refresh enable or not. + * @param formId The Id of the form. + * @return true on enbale, false on disable.. + */ +bool FormHostRecord::IsEnableRefresh(int64_t formId) const +{ + auto result = forms_.find(formId); + if (result != forms_.end()) { + return result->second; + } + return false; +} +/** + * @brief Set need refresh enable flag. + * @param formId The Id of the form. + * @param flag True for enbale, false for disable. + */ +void FormHostRecord::SetNeedRefresh(int64_t formId, bool flag) +{ + needRefresh_[formId] = flag; +} +/** + * @brief Need Refresh enable or not. + * @param formId The Id of the form. + * @return true on enbale, false on disable.. + */ +bool FormHostRecord::IsNeedRefresh(int64_t formId) const +{ + auto result = needRefresh_.find(formId); + if (result != needRefresh_.end()) { + return result->second; + } + return false; +} +/** + * @brief Get clientStub_. + * @return clientStub_. + */ +sptr FormHostRecord::GetClientStub() const +{ + return clientStub_; +} + +/** + * @brief Send form data to form host. + * @param id The Id of the form. + * @param record Form record. + */ +void FormHostRecord::OnAcquire(int64_t id, const FormRecord &record) +{ + APP_LOGD("FormHostRecord OnAcquire"); + if (clientImpl_ == nullptr) { + APP_LOGE("%{public}s: clientImpl_ can not be NULL", __func__); + return; + } + + clientImpl_->OnAcquired(id, record, clientStub_); +} + +/** + * @brief Update form data to form host. + * @param id The Id of the form. + * @param record Form record. + */ +void FormHostRecord::OnUpdate(int64_t id, const FormRecord &record) +{ + APP_LOGI("%{public}s start.", __func__); + + if (clientImpl_ == nullptr) { + APP_LOGE("%{public}s: clientImpl_ can not be null.", __func__); + return; + } + + clientImpl_->OnUpdate(id, record, clientStub_); +} + +/** + * @brief Send form uninstall message to form host. + * @param id The Id of the form. + * @param record Form record. + */ +void FormHostRecord::OnFormUninstalled(std::vector &formIds) +{ + APP_LOGI("%{public}s start.", __func__); + + if (clientImpl_ == nullptr) { + APP_LOGE("%{public}s: clientImpl_ can not be null.", __func__); + return; + } + clientImpl_->OnUninstall(formIds, clientStub_); +} +/** + * @brief Release resource. + * @param id The Id of the form. + * @param record Form record. + */ +void FormHostRecord::CleanResource() +{ + if (clientStub_ != nullptr && deathRecipient_ != nullptr) { + clientStub_->RemoveDeathRecipient(deathRecipient_); + clientStub_ = nullptr; + deathRecipient_ = nullptr; + } +} +/** + * @brief Set value of callerUid_. + * @param callerUid Caller uid. + */ +void FormHostRecord::SetCallerUid(const int callerUid) +{ + callerUid_ = callerUid; +} +/** + * @brief Set value of clientStub_. + * @param clientStub remote object. + */ +void FormHostRecord::SetClientStub(const sptr &clientStub) +{ + clientStub_ = clientStub; +} +/** + * @brief Set value of clientImpl_. + * @param clientImpl Form host callback object. + */ +void FormHostRecord::SetClientImpl(const std::shared_ptr &clientImpl) +{ + clientImpl_ = clientImpl; +} +/** + * @brief Get deathRecipient_. + * @return deathRecipient_. + */ +sptr FormHostRecord::GetDeathRecipient() const +{ + return deathRecipient_; +} +/** + * @brief Set value of deathRecipient_. + * @param clientImpl DeathRecipient object. + */ +void FormHostRecord::SetDeathRecipient(const sptr &deathRecipient) +{ + deathRecipient_ = deathRecipient; +} +/** + * @brief Add deathRecipient object to clientStub_. + * @param deathRecipient DeathRecipient object. + */ +void FormHostRecord::AddDeathRecipient(const sptr &deathRecipient) +{ + clientStub_->AddDeathRecipient(deathRecipient); +} + +/** + * @brief Create form host record. + * @param info The form item info. + * @param callback remote object. + * @param callingUid Calling uid. + */ +FormHostRecord FormHostRecord::CreateRecord(const FormItemInfo &info, + const sptr &callback, int callingUid) +{ + FormHostRecord record; + record.SetHostBundleName(info.GetHostBundleName()); + record.SetCallerUid(callingUid); + record.SetClientStub(callback); + record.SetClientImpl(std::make_shared()); + record.SetDeathRecipient(new FormHostRecord::ClientDeathRecipient()); + record.AddDeathRecipient(record.GetDeathRecipient()); + + return record; +} + +/** + * @brief handle remote object died event. + * @param remote remote object. + */ +void FormHostRecord::ClientDeathRecipient::OnRemoteDied(const wptr &remote) +{ + APP_LOGD("Form remote died"); + FormTaskMgr::GetInstance().PostHostDiedTask(remote.promote()); +} + +/** + * @brief Get hostBundleName_. + * @return hostBundleName_. + */ +std::string FormHostRecord::GetHostBundleName() const +{ + return hostBundleName_; +} +/** + * @brief Set hostBundleName_. + * @param hostBandleName Host bundle name. + */ +void FormHostRecord::SetHostBundleName(const std::string &hostBundleName) +{ + hostBundleName_ = hostBundleName; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_mgr_adapter.cpp b/services/formmgr/src/form_mgr_adapter.cpp index e04e546bc9e971812fb40ee733f0ac8197ea600a..fbb58c77909314b6c952a733bce87ce9c54240a8 100644 --- a/services/formmgr/src/form_mgr_adapter.cpp +++ b/services/formmgr/src/form_mgr_adapter.cpp @@ -31,7 +31,9 @@ #include "form_event_notify_connection.h" #include "form_mgr_adapter.h" #include "form_provider_info.h" +#include "form_provider_interface.h" #include "form_provider_mgr.h" +#include "form_supply_callback.h" #include "form_refresh_connection.h" #include "form_timer_mgr.h" #include "if_system_ability_manager.h" @@ -43,23 +45,12 @@ namespace OHOS { namespace AppExecFwk { -// /** -// * @brief Get moduleName from packageName and abilityName. -// * @param packageName Package name. -// * @param abilityName Ability name. -// * @return ModuleName. -// */ -// std::string GetFullClassName(const std::string& packageName, const std::string& abilityName) -// { -// std::string fullName; -// if (!abilityName.empty() && abilityName[0] == '.') { -// fullName = packageName + abilityName; -// } else { -// fullName = abilityName; -// } -// return fullName; -// } - +FormMgrAdapter::FormMgrAdapter() +{ +}; +FormMgrAdapter::~FormMgrAdapter() +{ +}; /** * @brief Add form with want, send want to form manager service. * @param formId The Id of the forms to add. @@ -68,8 +59,8 @@ namespace AppExecFwk { * @param formInfo Form info. * @return Returns ERR_OK on success, others on failure. */ -int FormMgrAdapter::AddForm(const int64_t formId, const Want &want, const sptr &callerToken, -FormJsInfo &formInfo) +int FormMgrAdapter::AddForm(const int64_t formId, const Want &want, + const sptr &callerToken, FormJsInfo &formInfo) { if (formId < 0 || callerToken == nullptr) { APP_LOGE("%{public}s fail, callerToken can not be NULL", __func__); @@ -129,9 +120,8 @@ int FormMgrAdapter::DeleteForm(const int64_t formId, const sptr & { if (formId <= 0 || callerToken == nullptr) { APP_LOGE("%{public}s, deleteForm invalid param", __func__); - return ERR_FORM_INVALID_PARAM; + return ERR_APPEXECFWK_FORM_INVALID_PARAM; } - int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); if (FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) { // delete temp form if receive delete form call @@ -153,9 +143,8 @@ int FormMgrAdapter::ReleaseForm(const int64_t formId, const sptr if (formId <= 0 || callerToken == nullptr) { APP_LOGE("%{public}s, releaseForm invalid param", __func__); - return ERR_FORM_INVALID_PARAM; + return ERR_APPEXECFWK_FORM_INVALID_PARAM; } - int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); if (FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) { // delete temp form if receive release form call @@ -175,7 +164,7 @@ int FormMgrAdapter::ReleaseForm(const int64_t formId, const sptr } if (!FormTimerMgr::GetInstance().RemoveFormTimer(matchedFormId)) { APP_LOGE("%{public}s, remove timer error", __func__); - return ERR_DELETE_FORM_TIMER; + return ERR_APPEXECFWK_FORM_COMMON_CODE; } return ERR_OK; } @@ -191,7 +180,7 @@ ErrCode FormMgrAdapter::HandleReleaseForm(const int64_t formId, const sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); if (iBundleMgr == nullptr) { APP_LOGE("%{public}s error, failed to get IBundleMgr.", __func__); - return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; + return ERR_APPEXECFWK_FORM_GET_BMS_FAILED; } // check bundle uid for permission @@ -391,7 +379,7 @@ const FormProviderData &formProviderData) int32_t bundleUid = iBundleMgr->GetUidByBundleName(bundleName, userId); if (bundleUid != callingUid) { APP_LOGE("%{public}s error, permission denied, the updated form is not your own.", __func__); - return ERR_FORM_INVALID_PARAM; + return ERR_APPEXECFWK_FORM_INVALID_PARAM; } // find matched formId @@ -401,19 +389,19 @@ const FormProviderData &formProviderData) FormRecord formRecord; if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) { APP_LOGE("%{public}s error, not exist such form:%{public}" PRId64 ".", __func__, matchedFormId); - return ERR_NOT_EXIST_ID; + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; } // check then form under current user if (!FormDataMgr::GetInstance().IsCallingUidValid(formRecord.formUserUids)) { APP_LOGE("%{public}s error, not under current user, formId:%{public}" PRId64 ".", __func__, matchedFormId); - return ERR_NOT_EXIST_ID; + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; } // check bundleName match if (formRecord.bundleName.compare(bundleName) != 0) { APP_LOGE("%{public}s error, not match bundleName:%{public}s.", __func__, bundleName.c_str()); - return ERR_FORM_INVALID_PARAM; + return ERR_APPEXECFWK_FORM_INVALID_PARAM; } // update Form @@ -431,7 +419,7 @@ int FormMgrAdapter::RequestForm(const int64_t formId, const sptr { APP_LOGI("%{public}s called.", __func__); - if (callerToken == nullptr) { + if (formId <= 0 || callerToken == nullptr) { APP_LOGE("%{public}s fail, callerToken can not be NULL.", __func__); return ERR_APPEXECFWK_FORM_INVALID_PARAM; } @@ -440,19 +428,19 @@ int FormMgrAdapter::RequestForm(const int64_t formId, const sptr if (!FormDataMgr::GetInstance().ExistFormRecord(matchedFormId)) { APP_LOGE("%{public}s fail, not exist such formId:%{public}" PRId64 ".", __func__, matchedFormId); - return ERR_NOT_EXIST_ID; + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; } FormHostRecord formHostRecord; bool isHostExist = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, formHostRecord); if (!isHostExist) { APP_LOGE("%{public}s fail, cannot find target client.", __func__); - return ERR_FORM_INVALID_PARAM; + return ERR_APPEXECFWK_FORM_INVALID_PARAM; } if (!formHostRecord.Contains(matchedFormId)) { APP_LOGE("%{public}s fail, form is not self-owned.", __func__); - return ERR_OPERATION_FORM_NOT_SELF; + return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; } APP_LOGI("%{public}s, find target client.", __func__); @@ -468,8 +456,7 @@ int FormMgrAdapter::RequestForm(const int64_t formId, const sptr * @return Returns ERR_OK on success, others on failure. */ ErrCode FormMgrAdapter::NotifyWhetherVisibleForms(const std::vector &formIds, -const sptr &callerToken, - const int32_t formVisibleType) + const sptr &callerToken, const int32_t formVisibleType) { APP_LOGI("%{public}s called.", __func__); @@ -481,7 +468,7 @@ const sptr &callerToken, sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); if (iBundleMgr == nullptr) { APP_LOGE("%{public}s fail, failed to get IBundleMgr.", __func__); - return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; + return ERR_APPEXECFWK_FORM_GET_BMS_FAILED; } int64_t matchedFormId; @@ -528,7 +515,8 @@ const sptr &callerToken, if (iBundleMgr->GetBundleInfo(formRecord.bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo)) { APP_LOGD("%{public}s, get bundle uid success", __func__); if (!iBundleMgr->CheckIsSystemAppByUid(bundleInfo.uid)) { - APP_LOGW("%{public}s fail, form provider is not system app, formId:%{public}" PRId64 ".", __func__, matchedFormId); + APP_LOGW("%{public}s fail, form provider is not system app, formId:%{public}" PRId64 ".", + __func__, matchedFormId); continue; } } else { @@ -569,21 +557,21 @@ int FormMgrAdapter::CastTempForm(const int64_t formId, const sptr { if (formId <= 0 || callerToken == nullptr) { APP_LOGE("%{public}s, invalid param", __func__); - return ERR_FORM_INVALID_PARAM; + return ERR_APPEXECFWK_FORM_INVALID_PARAM; } int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); if (!FormDataMgr::GetInstance().ExistFormRecord(matchedFormId) || !FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) { APP_LOGE("%{public}s, not exist such temp form:%{public}" PRId64 "", __func__, matchedFormId); - return ERR_NOT_EXIST_ID; + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; } FormHostRecord record; bool hasHostRec = FormDataMgr::GetInstance().GetFormHostRecord(matchedFormId, record); if (!hasHostRec || !record.Contains(matchedFormId)) { APP_LOGE("%{public}s, not self form:%{public}" PRId64 "", __func__, matchedFormId); - return ERR_OPERATION_FORM_NOT_SELF; + return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; } int callingUid = IPCSkeleton::GetCallingUid(); @@ -596,7 +584,7 @@ int FormMgrAdapter::CastTempForm(const int64_t formId, const sptr FormRecord formRecord; if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) { APP_LOGE("%{public}s fail, not exist such form:%{public}" PRId64 ".", __func__, matchedFormId); - return ERR_NOT_EXIST_ID; + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; } int bindSupplierCheckCode = HandleCastTempForm(matchedFormId, formRecord); if (bindSupplierCheckCode != 0) { @@ -606,15 +594,15 @@ int FormMgrAdapter::CastTempForm(const int64_t formId, const sptr if (!FormDataMgr::GetInstance().DeleteTempForm(matchedFormId)) { APP_LOGE("%{public}s fail, delete temp form error, formId:%{public}" PRId64 ".", __func__, matchedFormId); - return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; } if (!FormDataMgr::GetInstance().ModifyFormTempFlg(matchedFormId, false)) { APP_LOGE("%{public}s fail, modify form temp flag error, formId:%{public}" PRId64 ".", __func__, matchedFormId); - return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; } if (!FormDataMgr::GetInstance().AddFormUserUid(matchedFormId, callingUid)) { APP_LOGE("%{public}s fail, add form user uid error, formId:%{public}" PRId64 ".", __func__, matchedFormId); - return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; } if (std::find(formRecord.formUserUids.begin(), formRecord.formUserUids.end(), callingUid) == formRecord.formUserUids.end()) { @@ -638,12 +626,18 @@ ErrCode FormMgrAdapter::HandleCastTempForm(const int64_t formId, const FormRecor { APP_LOGD("%{public}s, cast temp form to normal form, notify supplier, package:%{public}s, class:%{public}s", __func__, record.bundleName.c_str(), record.abilityName.c_str()); - sptr castTempConnection = new FormCastTempConnection(formId); + sptr castTempConnection = new FormCastTempConnection(formId, + record.bundleName, record.abilityName); Want want; want.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); want.SetElementName(record.bundleName, record.abilityName); - return FormAmsHelper::GetInstance().ConnectServiceAbility(want, castTempConnection); + ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, castTempConnection); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s fail, ConnectServiceAbility failed.", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + return ERR_OK; } /** * @brief Dump all of form storage infos. @@ -654,14 +648,15 @@ int FormMgrAdapter::DumpStorageFormInfos(std::string &formInfos) const { std::vector formDBInfos; FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); - if(formDBInfos.size() > 0) { - std::sort(formDBInfos.begin(), formDBInfos.end(), [] (FormDBInfo &formDBInfoA, FormDBInfo &formDBInfoB) -> bool { + if (formDBInfos.size() > 0) { + std::sort(formDBInfos.begin(), formDBInfos.end(), + [] (FormDBInfo &formDBInfoA, FormDBInfo &formDBInfoB) -> bool { return formDBInfoA.formId < formDBInfoB.formId; }); FormDumpMgr::GetInstance().DumpStorageFormInfos(formDBInfos, formInfos); return ERR_OK; } else { - return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; } } /** @@ -678,7 +673,7 @@ int FormMgrAdapter::DumpFormInfoByBundleName(const std::string &bundleName, std: FormDumpMgr::GetInstance().DumpFormInfos(formRecordInfos, formInfos); return ERR_OK; } else { - return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; } } /** @@ -690,7 +685,7 @@ int FormMgrAdapter::DumpFormInfoByBundleName(const std::string &bundleName, std: int FormMgrAdapter::DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) const { APP_LOGI("%{public}s called.", __func__); - int reply = ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + int reply = ERR_APPEXECFWK_FORM_NOT_EXIST_ID; FormRecord formRecord; if (FormDataMgr::GetInstance().GetFormRecord(formId, formRecord)) { @@ -749,8 +744,8 @@ ErrCode FormMgrAdapter::GetFormConfigInfo(const Want &want, FormItemInfo &formCo * @param formInfo Form info for form host. * @return Returns ERR_OK on success, others on failure. */ -ErrCode FormMgrAdapter::AllotFormById(const FormItemInfo &info, const sptr &callerToken, -const WantParams &wantParams, FormJsInfo &formInfo) +ErrCode FormMgrAdapter::AllotFormById(const FormItemInfo &info, + const sptr &callerToken, const WantParams &wantParams, FormJsInfo &formInfo) { int64_t formId = PaddingUDIDHash(info.GetFormId()); FormRecord record; @@ -763,7 +758,7 @@ const WantParams &wantParams, FormJsInfo &formInfo) if (hasRecord && FormDataMgr::GetInstance().IsCallingUidValid(record.formUserUids)) { if (!info.IsMatch(record)) { APP_LOGE("%{public}s, formId and item info not match:%{public}" PRId64 "", __func__, formId); - return ERR_CFG_NOT_MATCH_ID; + return ERR_APPEXECFWK_FORM_CFG_NOT_MATCH_ID; } return AddExistFormRecord(info, callerToken, record, formId, wantParams); } @@ -783,12 +778,13 @@ const WantParams &wantParams, FormJsInfo &formInfo) delRecord.abilityName = info.GetAbilityName(); FormProviderMgr::GetInstance().NotifyProviderFormDelete(formId, delRecord); - return ERR_NOT_EXIST_ID; + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; } int64_t FormMgrAdapter::PaddingUDIDHash(const int64_t formId) const { // Compatible with int form id. - if ((formId & 0xffffffff00000000L) == 0) { + uint64_t unsignedFormId = static_cast(formId); + if ((unsignedFormId & 0xffffffff00000000L) == 0) { return FormDataMgr::GetInstance().GetUdidHash() | formId; } return formId; @@ -806,6 +802,7 @@ ErrCode FormMgrAdapter::AddExistFormRecord(const FormItemInfo &info, const sptr< } FormRecord newRecord(record); + if (newRecord.needRefresh) { newRecord.isInited = false; FormDataMgr::GetInstance().SetFormCacheInited(formId, false); @@ -842,8 +839,8 @@ ErrCode FormMgrAdapter::AddExistFormRecord(const FormItemInfo &info, const sptr< * @param formInfo Form info for form host. * @return Returns ERR_OK on success, others on failure. */ -ErrCode FormMgrAdapter::AllotFormByInfo(const FormItemInfo &info, const sptr &callerToken, -const WantParams &wantParams, FormJsInfo &formInfo) +ErrCode FormMgrAdapter::AllotFormByInfo(const FormItemInfo &info, + const sptr &callerToken, const WantParams &wantParams, FormJsInfo &formInfo) { // generate formId int64_t newFormId = FormDataMgr::GetInstance().GenerateFormId(); @@ -915,7 +912,7 @@ ErrCode FormMgrAdapter::AddFormTimer(const FormRecord &formRecord) timerRet = FormTimerMgr::GetInstance().AddFormTimer(formRecord.formId, formRecord.updateDuration); } else { timerRet = FormTimerMgr::GetInstance().AddFormTimer(formRecord.formId, formRecord.updateAtHour, - formRecord.updateAtMin); + formRecord.updateAtMin); } if (!timerRet) { APP_LOGE("%{public}s fail, add form timer failed", __func__); @@ -938,19 +935,20 @@ ErrCode FormMgrAdapter::HandleEventNotify(const std::string &providerKey, const const int32_t formVisibleType) { APP_LOGI("%{public}s called.", __func__); - + size_t position = providerKey.find(Constants::NAME_DELIMITER); + std::string bundleName = providerKey.substr(0, position); + std::string abilityName = providerKey.substr(position + Constants::NAME_DELIMITER.size()); sptr formEventNotifyConnection = new FormEventNotifyConnection(formIdsByProvider, - formVisibleType); + formVisibleType, bundleName, abilityName); Want connectWant; connectWant.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); - size_t position = providerKey.find(Constants::NAME_DELIMITER); - connectWant.SetElementName(providerKey.substr(0, position), - providerKey.substr(position + Constants::NAME_DELIMITER.size())); + + connectWant.SetElementName(bundleName, abilityName); ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(connectWant, formEventNotifyConnection); if (errorCode != ERR_OK) { APP_LOGE("%{public}s fail, ConnectServiceAbility failed.", __func__); - return errorCode; + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; } return ERR_OK; @@ -963,8 +961,8 @@ ErrCode FormMgrAdapter::HandleEventNotify(const std::string &providerKey, const * @param wantParams WantParams of the request. * @return Returns ERR_OK on success, others on failure. */ -ErrCode FormMgrAdapter::AcquireProviderFormInfoAsync(const int64_t formId, const FormItemInfo &info, -const WantParams &wantParams) +ErrCode FormMgrAdapter::AcquireProviderFormInfoAsync(const int64_t formId, + const FormItemInfo &info, const WantParams &wantParams) { if (formId <= 0) { APP_LOGE("%{public}s fail, formId should be greater than 0", __func__); @@ -976,7 +974,12 @@ const WantParams &wantParams) Want want; want.SetElementName(info.GetProviderBundleName(), info.GetAbilityName()); want.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); - return FormAmsHelper::GetInstance().ConnectServiceAbility(want, formAcquireConnection); + ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, formAcquireConnection); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s fail, ConnectServiceAbility failed.", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + return ERR_OK; } /** @@ -1001,7 +1004,7 @@ ErrCode FormMgrAdapter::GetBundleInfo(const AAFwk::Want &want, BundleInfo &bundl sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); if (iBundleMgr == nullptr) { APP_LOGE("GetBundleMgr, failed to get IBundleMgr."); - return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; + return ERR_APPEXECFWK_FORM_GET_BMS_FAILED; } if (iBundleMgr->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo) != true) { @@ -1023,16 +1026,12 @@ ErrCode FormMgrAdapter::GetBundleInfo(const AAFwk::Want &want, BundleInfo &bundl } for (const auto &abilityInfo : bundleInfo.abilityInfos) { - // if (abilityInfo.moduleName.compare(GetFullClassName(abilityInfo.package, abilityName)) == 0) { - // packageName = abilityInfo.package; - // break; - // } - if (abilityInfo.deviceId == deviceId) { - packageName = abilityInfo.package; + if (abilityInfo.bundleName == bundleName && abilityInfo.moduleName == moduleName ) { + packageName = bundleName + moduleName; break; } } - + if (packageName.empty()) { APP_LOGE("GetBundleInfo can not find target ability %{public}s", abilityName.c_str()); return ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY; @@ -1060,7 +1059,7 @@ ErrCode FormMgrAdapter::GetFormInfo(const AAFwk::Want &want, FormInfo &formInfo) sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); if (iBundleMgr == nullptr) { APP_LOGE("GetFormInfo, failed to get IBundleMgr."); - return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; + return ERR_APPEXECFWK_FORM_GET_BMS_FAILED; } std::vector formInfos; @@ -1110,16 +1109,9 @@ ErrCode FormMgrAdapter::GetFormItemInfo(const AAFwk::Want &want, const BundleInf return ERR_APPEXECFWK_FORM_NO_SUCH_DIMENSION; } - // int32_t orientation = want.GetIntParam(Constants::PARAM_FORM_ORIENTATION_KEY, Constants::ORIENTATION_PORTRAIT); - // if (orientation != Constants::ORIENTATION_PORTRAIT && orientation != Constants::ORIENTATION_LANDSCAPE) { - // orientation = Constants::ORIENTATION_PORTRAIT; - // } - if (ErrCode ret = CreateFormItemInfo(bundleInfo, formInfo, formItemInfo); ret != ERR_OK) { return ret; } - // formItemInfo.SetFormId(formId); - // formItemInfo.orientation_ = orientation; formItemInfo.SetSpecificationId(dimensionId); formItemInfo.SetTemporaryFlag(want.GetBoolParam(Constants::PARAM_FORM_TEMPORARY_KEY, false)); @@ -1155,14 +1147,14 @@ bool FormMgrAdapter::IsDimensionValid(const FormInfo &formInfo, int dimensionId) * @param formInfo Form info. * @param itemInfo Form configure info. */ -ErrCode FormMgrAdapter::CreateFormItemInfo(const BundleInfo &bundleInfo, const FormInfo &formInfo, -FormItemInfo &itemInfo) +ErrCode FormMgrAdapter::CreateFormItemInfo(const BundleInfo &bundleInfo, + const FormInfo &formInfo, FormItemInfo &itemInfo) { itemInfo.SetProviderBundleName(bundleInfo.name); sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); if (iBundleMgr == nullptr) { APP_LOGE("GetFormInfo, failed to get IBundleMgr."); - return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; + return ERR_APPEXECFWK_FORM_GET_BMS_FAILED; } std::string hostBundleName {}; if (!iBundleMgr->GetBundleNameForUid(IPCSkeleton::GetCallingUid(), hostBundleName)) { @@ -1184,9 +1176,11 @@ FormItemInfo &itemInfo) itemInfo.SetAbilityModuleName(abilityInfo.moduleName); } } + APP_LOGI("%{public}s moduleInfos size: %{public}zu", __func__, bundleInfo.applicationInfo.moduleInfos.size()); for (const auto &item : bundleInfo.applicationInfo.moduleInfos) { - APP_LOGI("%{public}s moduleInfos, moduleName: %{public}s, moduleSourceDir: %{public}s", __func__, item.moduleName.c_str(), item.moduleSourceDir.c_str()); + APP_LOGI("%{public}s moduleInfos, moduleName: %{public}s, moduleSourceDir: %{public}s", __func__, + item.moduleName.c_str(), item.moduleSourceDir.c_str()); if (formInfo.moduleName == item.moduleName) { itemInfo.AddHapSourceDirs(item.moduleSourceDir); } @@ -1206,24 +1200,24 @@ int FormMgrAdapter::SetNextRefreshTime(const int64_t formId, const int64_t nextT APP_LOGI("%{public}s begin here, formId:%{public}" PRId64 ",nextTime:%{public}" PRId64 "", __func__, formId, nextTime); if (formId <= 0) { APP_LOGE("%{public}s form formId or bundleName is invalid", __func__); - return ERR_FORM_INVALID_PARAM; + return ERR_APPEXECFWK_FORM_INVALID_PARAM; } int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); std::string bundleName; if (!GetBundleName(bundleName)) { - return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; } FormRecord formRecord; if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) { APP_LOGE("%{public}s, not found in formrecord.", __func__); - return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; } // check bundleName if (bundleName != formRecord.bundleName) { APP_LOGE("%{public}s, not match bundleName:%{public}s", __func__, bundleName.c_str()); - return ERR_OPERATION_FORM_NOT_SELF; + return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; } return SetNextRefreshtTimeLocked(matchedFormId, nextTime); @@ -1269,12 +1263,12 @@ int FormMgrAdapter::SetNextRefreshtTimeLocked(const int64_t formId, const int64_ if (timerRefreshedCount >= Constants::LIMIT_COUNT) { APP_LOGE("%{public}s, already refresh times:%{public}d", __func__, timerRefreshedCount); FormTimerMgr::GetInstance().MarkRemind(formId); - return ERR_MAX_REFRESH; + return ERR_APPEXECFWK_FORM_MAX_REFRESH; } if (!FormTimerMgr::GetInstance().SetNextRefreshTime(formId, nextTime)) { APP_LOGE("%{public}s failed", __func__); - return ERR_CODE_COMMON; + return ERR_APPEXECFWK_FORM_COMMON_CODE; } return ERR_OK; @@ -1348,32 +1342,32 @@ int FormMgrAdapter::MessageEvent(const int64_t formId, const Want &want, const s bool bGetRecord = FormDataMgr::GetInstance().GetFormRecord(matchedFormId, record); if (!bGetRecord) { APP_LOGE("%{public}s fail, not exist such form:%{public}" PRId64 "", __func__, matchedFormId); - return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; } FormHostRecord formHostRecord; bool isHostExist = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, formHostRecord); if (!isHostExist) { APP_LOGE("%{public}s failed, cannot find target client.", __func__); - return ERR_APPEXECFWK_FORM_HOST_INFO_NOT_EXIST; + return ERR_APPEXECFWK_FORM_COMMON_CODE; } if (!formHostRecord.Contains(matchedFormId)) { APP_LOGE("%{public}s failed, form is not self-owned.", __func__); - return ERR_OPERATION_FORM_NOT_SELF; + return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; } APP_LOGI("%{public}s, find target client.", __func__); return FormProviderMgr::GetInstance().MessageEvent(matchedFormId, record, want); } -int FormMgrAdapter::HandleUpdateFormFlag(std::vector formIds, const sptr &callerToken, -bool flag) +int FormMgrAdapter::HandleUpdateFormFlag(std::vector formIds, + const sptr &callerToken, bool flag) { APP_LOGI("%{public}s called.", __func__); if (formIds.empty() || callerToken == nullptr) { APP_LOGE("%{public}s, invalid param", __func__); - return ERR_FORM_INVALID_PARAM; + return ERR_APPEXECFWK_FORM_INVALID_PARAM; } std::vector refreshForms; int errCode = FormDataMgr::GetInstance().UpdateHostFormFlag(formIds, callerToken, flag, refreshForms); @@ -1392,13 +1386,66 @@ bool flag) * @param formIDs The id of the forms. * @param callerToken Caller ability token. * @param flag form flag. - * @return Returns ERR_OK on success, others on failure. + * @return Returns true on success, false on failure. */ -bool FormMgrAdapter::IsFormCached(const FormRecord record) { +bool FormMgrAdapter::IsFormCached(const FormRecord record) +{ if (record.versionUpgrade) { return false; } return true; } + +/** + * @brief Acquire form data from form provider. + * @param formId The Id of the from. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ +void FormMgrAdapter::AcquireProviderFormInfo(const int64_t formId, const Want &want, +const sptr &remoteObject) +{ + APP_LOGI("%{public}s called.", __func__); + + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + sptr formProviderProxy = iface_cast(remoteObject); + if (formProviderProxy == nullptr) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to get formProviderProxy", __func__); + return; + } + + int error = formProviderProxy->AcquireProviderFormInfo(formId, want, FormSupplyCallback::GetInstance()); + if (error != ERR_OK) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to get acquire provider form info", __func__); + } +} + +/** + * @brief Notify form provider for delete form. + * + * @param formId The Id of the from. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ +void FormMgrAdapter::NotifyFormDelete(const int64_t formId, const Want &want, const sptr &remoteObject) +{ + APP_LOGI("%{public}s called.", __func__); + + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + sptr formProviderProxy = iface_cast(remoteObject); + if (formProviderProxy == nullptr) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to get formProviderProxy", __func__); + return; + } + int error = formProviderProxy->NotifyFormDelete(formId, want, FormSupplyCallback::GetInstance()); + if (error != ERR_OK) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to get acquire provider form info", __func__); + } +} } // namespace AppExecFwk } // namespace OHOS diff --git a/services/formmgr/src/form_mgr_service.cpp b/services/formmgr/src/form_mgr_service.cpp index 8eb194ba678001d6fb32a7fb9bba2e716bad3a77..7fb4a8e61fdbcb7b6968a1a1dcd7b841625f5f07 100644 --- a/services/formmgr/src/form_mgr_service.cpp +++ b/services/formmgr/src/form_mgr_service.cpp @@ -19,11 +19,13 @@ #include "appexecfwk_errors.h" #include "app_log_wrapper.h" +#include "form_ams_helper.h" #include "form_bms_helper.h" #include "form_constants.h" #include "form_data_mgr.h" #include "form_db_cache.h" #include "form_mgr_service.h" +#include "form_mgr_adapter.h" #include "form_task_mgr.h" #include "form_timer_mgr.h" #include "ipc_skeleton.h" @@ -48,8 +50,7 @@ FormMgrService::FormMgrService() : SystemAbility(FORM_MGR_SERVICE_ID, true), state_(ServiceRunningState::STATE_NOT_START), runner_(nullptr), - handler_(nullptr), - formMgrAdapter_(std::make_unique()) + handler_(nullptr) { } @@ -77,14 +78,14 @@ bool FormMgrService::IsReady() const * @param formInfo Form info. * @return Returns ERR_OK on success, others on failure. */ -int FormMgrService::AddForm(const int64_t formId, const Want &want, const sptr &callerToken, -FormJsInfo &formInfo) +int FormMgrService::AddForm(const int64_t formId, const Want &want, + const sptr &callerToken, FormJsInfo &formInfo) { if (!CheckFormPermission()) { APP_LOGE("%{public}s fail, add form permission denied", __func__); return ERR_APPEXECFWK_FORM_PERMISSION_DENY; } - return formMgrAdapter_->AddForm(formId, want, callerToken, formInfo); + return FormMgrAdapter::GetInstance().AddForm(formId, want, callerToken, formInfo); } /** @@ -100,7 +101,7 @@ int FormMgrService::DeleteForm(const int64_t formId, const sptr & return ERR_APPEXECFWK_FORM_PERMISSION_DENY; } - return formMgrAdapter_->DeleteForm(formId, callerToken); + return FormMgrAdapter::GetInstance().DeleteForm(formId, callerToken); } /** @@ -117,7 +118,7 @@ int FormMgrService::ReleaseForm(const int64_t formId, const sptr return ERR_APPEXECFWK_FORM_PERMISSION_DENY; } - return formMgrAdapter_->ReleaseForm(formId, callerToken, delCache); + return FormMgrAdapter::GetInstance().ReleaseForm(formId, callerToken, delCache); } /** @@ -127,14 +128,14 @@ int FormMgrService::ReleaseForm(const int64_t formId, const sptr * @param formBindingData Form binding data. * @return Returns ERR_OK on success, others on failure. */ -int FormMgrService::UpdateForm(const int64_t formId, const std::string &bundleName, -const FormProviderData &formBindingData) +int FormMgrService::UpdateForm(const int64_t formId, + const std::string &bundleName, const FormProviderData &formBindingData) { if (!CheckFormPermission()) { APP_LOGE("%{public}s fail, update form permission denied", __func__); return ERR_APPEXECFWK_FORM_PERMISSION_DENY; } - return formMgrAdapter_->UpdateForm(formId, bundleName, formBindingData); + return FormMgrAdapter::GetInstance().UpdateForm(formId, bundleName, formBindingData); } /** @@ -153,7 +154,7 @@ int FormMgrService::RequestForm(const int64_t formId, const sptr return ERR_APPEXECFWK_FORM_PERMISSION_DENY; } - return formMgrAdapter_->RequestForm(formId, callerToken, want); + return FormMgrAdapter::GetInstance().RequestForm(formId, callerToken, want); } /** @@ -167,7 +168,7 @@ int FormMgrService::SetNextRefreshTime(const int64_t formId, const int64_t nextT { APP_LOGI("%{public}s called.", __func__); - return formMgrAdapter_->SetNextRefreshTime(formId, nextTime); + return FormMgrAdapter::GetInstance().SetNextRefreshTime(formId, nextTime); } @@ -179,14 +180,14 @@ int FormMgrService::SetNextRefreshTime(const int64_t formId, const int64_t nextT * @return Returns ERR_OK on success, others on failure. */ int FormMgrService::NotifyWhetherVisibleForms(const std::vector &formIds, -const sptr &callerToken, const int32_t formVisibleType) + const sptr &callerToken, const int32_t formVisibleType) { if (!CheckFormPermission()) { APP_LOGE("%{public}s fail, event notify visible permission denied", __func__); return ERR_APPEXECFWK_FORM_PERMISSION_DENY; } - return formMgrAdapter_->NotifyWhetherVisibleForms(formIds, callerToken, formVisibleType); + return FormMgrAdapter::GetInstance().NotifyWhetherVisibleForms(formIds, callerToken, formVisibleType); } /** @@ -202,7 +203,7 @@ int FormMgrService::CastTempForm(const int64_t formId, const sptr return ERR_APPEXECFWK_FORM_PERMISSION_DENY; } - return formMgrAdapter_->CastTempForm(formId, callerToken); + return FormMgrAdapter::GetInstance().CastTempForm(formId, callerToken); } /** @@ -212,8 +213,8 @@ int FormMgrService::CastTempForm(const int64_t formId, const sptr * @param updateType update type,enable or disable. * @return Returns true on success, false on failure. */ -int FormMgrService::LifecycleUpdate(const std::vector &formIds, const sptr &callerToken, -const int32_t updateType) +int FormMgrService::LifecycleUpdate(const std::vector &formIds, + const sptr &callerToken, const int32_t updateType) { APP_LOGI("lifecycleUpdate."); @@ -223,9 +224,9 @@ const int32_t updateType) } if (updateType == ENABLE_FORM_UPDATE) { - return formMgrAdapter_->EnableUpdateForm(formIds, callerToken); + return FormMgrAdapter::GetInstance().EnableUpdateForm(formIds, callerToken); } else { - return formMgrAdapter_->DisableUpdateForm(formIds, callerToken); + return FormMgrAdapter::GetInstance().DisableUpdateForm(formIds, callerToken); } } /** @@ -235,7 +236,7 @@ const int32_t updateType) */ int FormMgrService::DumpStorageFormInfos(std::string &formInfos) { - return formMgrAdapter_->DumpStorageFormInfos(formInfos); + return FormMgrAdapter::GetInstance().DumpStorageFormInfos(formInfos); } /** * @brief Dump form info by a bundle name. @@ -245,7 +246,7 @@ int FormMgrService::DumpStorageFormInfos(std::string &formInfos) */ int FormMgrService::DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos) { - return formMgrAdapter_->DumpFormInfoByBundleName(bundleName, formInfos); + return FormMgrAdapter::GetInstance().DumpFormInfoByBundleName(bundleName, formInfos); } /** * @brief Dump form info by a bundle name. @@ -255,7 +256,7 @@ int FormMgrService::DumpFormInfoByBundleName(const std::string &bundleName, std: */ int FormMgrService::DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) { - return formMgrAdapter_->DumpFormInfoByFormId(formId, formInfo); + return FormMgrAdapter::GetInstance().DumpFormInfoByFormId(formId, formInfo); } /** * @brief Process js message event. @@ -273,7 +274,7 @@ int FormMgrService::MessageEvent(const int64_t formId, const Want &want, const s return ERR_APPEXECFWK_FORM_PERMISSION_DENY; } - return formMgrAdapter_->MessageEvent(formId, want, callerToken); + return FormMgrAdapter::GetInstance().MessageEvent(formId, want, callerToken); } /** * @brief Start envent for the form manager service. @@ -329,6 +330,7 @@ ErrCode FormMgrService::Init() return ERR_INVALID_OPERATION; } FormTaskMgr::GetInstance().SetEventHandler(handler_); + FormAmsHelper::GetInstance().SetEventHandler(handler_); /* Publish service maybe failed, so we need call this function at the last, * so it can't affect the TDD test program */ bool ret = Publish(DelayedSingleton::GetInstance().get()); @@ -380,7 +382,7 @@ bool FormMgrService::CheckFormPermission(const std::string &bundleName) const int result = PermissionKit::VerifyPermission(bundleName, Constants::PERMISSION_REQUIRE_FORM, 0); if (result != PermissionState::PERMISSION_GRANTED) { APP_LOGW("permission = %{public}s, bundleName = %{public}s, result = %{public}d", - Constants::PERMISSION_REQUIRE_FORM.c_str(), bundleName.c_str(), result); + Constants::PERMISSION_REQUIRE_FORM.c_str(), bundleName.c_str(), result); } return result == PermissionState::PERMISSION_GRANTED; } diff --git a/services/formmgr/src/form_msg_event_connection.cpp b/services/formmgr/src/form_msg_event_connection.cpp index 3b3c13dc414f01470aba64628974623e24f13044..570e77e9794c5ffdb3ca19a3e18f5c1816ecde58 100644 --- a/services/formmgr/src/form_msg_event_connection.cpp +++ b/services/formmgr/src/form_msg_event_connection.cpp @@ -1,66 +1,67 @@ - -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include "appexecfwk_errors.h" -#include "app_log_wrapper.h" -#include "form_constants.h" -#include "form_msg_event_connection.h" -#include "form_supply_callback.h" -#include "form_task_mgr.h" -#include "ipc_types.h" -#include "message_parcel.h" -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -FormMsgEventConnection::FormMsgEventConnection(const int64_t formId, const Want& want) - :formId_(formId), - want_(want) -{ -} -/** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * - * @param element Service ability's ElementName. - * @param remoteObject The session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - * @return none. - */ -void FormMsgEventConnection::OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) -{ - APP_LOGI("%{public}s called.", __func__); - - if (resultCode != ERR_OK) { - APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", - __func__, element.GetAbilityName().c_str(), formId_, resultCode); - return; - } - FormSupplyCallback::GetInstance()->AddConnection(this); - - if (want_.HasParameter(Constants::PARAM_MESSAGE_KEY)) { - std::string message = want_.GetStringParam(Constants::PARAM_MESSAGE_KEY); - Want eventWant = Want(want_); - eventWant.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); - FormTaskMgr::GetInstance().PostFormEventTask(formId_, message, eventWant, remoteObject); - } else { - APP_LOGE("%{public}s error, message info is not exist", __func__); - } -} -} // namespace AppExecFwk + +/* + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_msg_event_connection.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormMsgEventConnection::FormMsgEventConnection(const int64_t formId, const Want& want, + const std::string &bundleName, const std::string &abilityName) + :formId_(formId), + want_(want) +{ + SetProviderKey(bundleName, abilityName); +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element Service ability's ElementName. + * @param remoteObject The session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + * @return none. + */ +void FormMsgEventConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + + if (want_.HasParameter(Constants::PARAM_MESSAGE_KEY)) { + std::string message = want_.GetStringParam(Constants::PARAM_MESSAGE_KEY); + Want eventWant = Want(want_); + eventWant.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostFormEventTask(formId_, message, eventWant, remoteObject); + } else { + APP_LOGE("%{public}s error, message info is not exist", __func__); + } +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_provider_mgr.cpp b/services/formmgr/src/form_provider_mgr.cpp index 129597ad6da801c242cf0604b40765109d43e871..3712752d68c9a9de0f26899d66461897b5eea5a2 100644 --- a/services/formmgr/src/form_provider_mgr.cpp +++ b/services/formmgr/src/form_provider_mgr.cpp @@ -46,21 +46,21 @@ ErrCode FormProviderMgr::AcquireForm(const int64_t formId, const FormProviderInf if (formId <= 0) { APP_LOGE("%{public}s fail, formId should be greater than 0", __func__); - return ERR_FORM_INVALID_PARAM; + return ERR_APPEXECFWK_FORM_INVALID_PARAM; } FormRecord formRecord; bool isGetFormRecord = FormDataMgr::GetInstance().GetFormRecord(formId, formRecord); if (!isGetFormRecord) { APP_LOGE("%{public}s fail, not exist such form, formId:%{public}" PRId64 "", __func__, formId); - return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; } FormHostRecord clientHost; bool isGetFormHostRecord = FormDataMgr::GetInstance().GetFormHostRecord(formId, clientHost); if (!isGetFormHostRecord) { APP_LOGE("%{public}s fail, clientHost is null", __func__); - return ERR_APPEXECFWK_FORM_HOST_INFO_NOT_EXIST; + return ERR_APPEXECFWK_FORM_COMMON_CODE; } if (formRecord.isInited) { @@ -108,7 +108,7 @@ ErrCode FormProviderMgr::RefreshForm(const int64_t formId, const Want &want) bool bGetRecord = FormDataMgr::GetInstance().GetFormRecord(formId, record); if (!bGetRecord) { APP_LOGE("%{public}s fail, not exist such form:%{public}" PRId64 "", __func__, formId); - return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; } bool isTimerRefresh = want.GetBoolParam(Constants::KEY_IS_TIMER, false); @@ -149,13 +149,14 @@ ErrCode FormProviderMgr::RefreshForm(const int64_t formId, const Want &want) * @param isTimerRefresh The flag of timer refresh. * @return Returns ERR_OK on success, others on failure. */ -ErrCode FormProviderMgr::ConnectAmsForRefresh(const int64_t formId, const FormRecord &record, const Want &want, -const bool isTimerRefresh) +ErrCode FormProviderMgr::ConnectAmsForRefresh(const int64_t formId, + const FormRecord &record, const Want &want, const bool isTimerRefresh) { APP_LOGD("%{public}s called, bundleName:%{public}s, abilityName:%{public}s.", __func__, record.bundleName.c_str(), record.abilityName.c_str()); - sptr formRefreshConnection = new FormRefreshConnection(formId, want); + sptr formRefreshConnection = new FormRefreshConnection(formId, want, + record.bundleName, record.abilityName); Want connectWant; connectWant.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); connectWant.SetElementName(record.bundleName, record.abilityName); @@ -163,14 +164,14 @@ const bool isTimerRefresh) if (isTimerRefresh) { if (!FormTimerMgr::GetInstance().IsLimiterEnableRefresh(formId)) { APP_LOGE("%{public}s, timer refresh, already limit.", __func__); - return ERR_APPEXECFWK_FORM_SUPPLIER_DEL_FAIL; + return ERR_APPEXECFWK_FORM_PROVIDER_DEL_FAIL; } } ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(connectWant, formRefreshConnection); if (errorCode != ERR_OK) { APP_LOGE("%{public}s, ConnectServiceAbility failed.", __func__); - return errorCode; + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; } if (record.isCountTimerRefresh) { @@ -190,21 +191,28 @@ ErrCode FormProviderMgr::NotifyProviderFormDelete(const int64_t formId, const Fo { if (formRecord.abilityName.empty()) { APP_LOGE("%{public}s, formRecord.abilityName is empty.", __func__); - return ERR_CODE_COMMON; + return ERR_APPEXECFWK_FORM_INVALID_PARAM; } if (formRecord.bundleName.empty()) { APP_LOGE("%{public}s, formRecord.bundleName is empty.", __func__); - return ERR_CODE_COMMON; + return ERR_APPEXECFWK_FORM_INVALID_PARAM; } APP_LOGD("%{public}s, connectAbility,bundleName:%{public}s, abilityName:%{public}s", __func__, formRecord.bundleName.c_str(), formRecord.abilityName.c_str()); - sptr formDeleteConnection = new FormDeleteConnection(formId); + sptr formDeleteConnection = new FormDeleteConnection(formId, + formRecord.bundleName, formRecord.abilityName); Want want; want.SetElementName(formRecord.bundleName, formRecord.abilityName); want.SetFlags(Want::FLAG_ABILITY_FORM_ENABLED); - return FormAmsHelper::GetInstance().ConnectServiceAbility(want, formDeleteConnection); + + ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, formDeleteConnection); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s, ConnectServiceAbility failed.", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + return ERR_OK; } /** @@ -214,8 +222,8 @@ ErrCode FormProviderMgr::NotifyProviderFormDelete(const int64_t formId, const Fo * @param formIds form id list. * @return Returns ERR_OK on success, others on failure. */ -ErrCode FormProviderMgr::NotifyProviderFormsBatchDelete(const std::string &bundleName, const std::string &abilityName, -const std::set &formIds) +ErrCode FormProviderMgr::NotifyProviderFormsBatchDelete(const std::string &bundleName, + const std::string &abilityName, const std::set &formIds) { if (abilityName.empty()) { APP_LOGE("%{public}s error, abilityName is empty.", __func__); @@ -227,9 +235,9 @@ const std::set &formIds) return ERR_APPEXECFWK_FORM_INVALID_PARAM; } - APP_LOGD("%{public}s, bundleName:%{public}s, abilityName:%{public}s", __func__, bundleName.c_str(), - abilityName.c_str()); - sptr batchDeleteConnection = new FormBatchDeleteConnection(formIds); + APP_LOGD("%{public}s, bundleName:%{public}s, abilityName:%{public}s", + __func__, bundleName.c_str(), abilityName.c_str()); + sptr batchDeleteConnection = new FormBatchDeleteConnection(formIds, bundleName, abilityName); Want want; want.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); want.SetElementName(bundleName, abilityName); @@ -237,7 +245,7 @@ const std::set &formIds) ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, batchDeleteConnection); if (errorCode != ERR_OK) { APP_LOGE("%{public}s, ConnectServiceAbility failed.", __func__); - return errorCode; + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; } return ERR_OK; } @@ -254,7 +262,7 @@ ErrCode FormProviderMgr::UpdateForm(const int64_t formId, const FormProviderInfo FormRecord formRecord; if (!FormDataMgr::GetInstance().GetFormRecord(formId, formRecord)) { APP_LOGE("%{public}s error, not exist such form:%{public}" PRId64 ".", __func__, formId); - return ERR_NOT_EXIST_ID; + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; } return UpdateForm(formId, formRecord, formProviderInfo.GetFormData()); } @@ -266,13 +274,14 @@ ErrCode FormProviderMgr::UpdateForm(const int64_t formId, const FormProviderInfo * @param formProviderData provider form info. * @return Returns ERR_OK on success, others on failure. */ -ErrCode FormProviderMgr::UpdateForm(const int64_t formId, FormRecord &formRecord, -const FormProviderData &formProviderData) +ErrCode FormProviderMgr::UpdateForm(const int64_t formId, + FormRecord &formRecord, const FormProviderData &formProviderData) { APP_LOGI("%{public}s start", __func__); if (formRecord.versionUpgrade) { formRecord.formProviderInfo.SetFormData(formProviderData); + formRecord.formProviderInfo.SetUpgradeFlg(true); } else { nlohmann::json addJsonData = formProviderData.GetData(); formRecord.formProviderInfo.MergeData(addJsonData); @@ -290,8 +299,11 @@ const FormProviderData &formProviderData) if (screenOnFlag) { if (FormDataMgr::GetInstance().UpdateHostForm(formId, formRecord)) { FormDataMgr::GetInstance().SetVersionUpgrade(formId, false); + formRecord.formProviderInfo.SetUpgradeFlg(false); } } + // update formProviderInfo to formRecord + FormDataMgr::GetInstance().UpdateFormProviderInfo(formId, formRecord.formProviderInfo); // check if cache data size is less than 1k or not std::string jsonData = formRecord.formProviderInfo.GetFormDataString(); // get json data APP_LOGD("%{public}s , jsonData is %{public}s.", __func__, jsonData.c_str()); @@ -320,7 +332,8 @@ int FormProviderMgr::MessageEvent(const int64_t formId, const FormRecord &record return ERR_APPEXECFWK_FORM_COMMON_CODE; } - sptr formMsgEventConnection = new FormMsgEventConnection(formId, want); + sptr formMsgEventConnection = new FormMsgEventConnection(formId, want, + record.bundleName, record.abilityName); Want connectWant; connectWant.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); connectWant.SetElementName(record.bundleName, record.abilityName); @@ -328,7 +341,7 @@ int FormProviderMgr::MessageEvent(const int64_t formId, const FormRecord &record ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(connectWant, formMsgEventConnection); if (errorCode != ERR_OK) { APP_LOGE("%{public}s, ConnectServiceAbility failed.", __func__); - return errorCode; + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; } return ERR_OK; diff --git a/services/formmgr/src/form_refresh_connection.cpp b/services/formmgr/src/form_refresh_connection.cpp index 8c676b204bc6cb09e40ae2811c31e6c5e02ec3f6..7fd2ecf6141335a17711001b4b5bbb1cb2101712 100644 --- a/services/formmgr/src/form_refresh_connection.cpp +++ b/services/formmgr/src/form_refresh_connection.cpp @@ -1,72 +1,72 @@ - -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include "appexecfwk_errors.h" -#include "app_log_wrapper.h" -#include "form_constants.h" -#include "form_refresh_connection.h" -#include "form_supply_callback.h" -#include "form_task_mgr.h" -#include "ipc_types.h" -#include "message_parcel.h" -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -FormRefreshConnection::FormRefreshConnection(const int64_t formId, const Want& want) - :formId_(formId), - want_(want) -{ -} -/** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * - * @param element Service ability's ElementName. - * @param remoteObject The session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - * @return none. - */ -void FormRefreshConnection::OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) -{ - APP_LOGI("%{public}s called.", __func__); - - if (resultCode != ERR_OK) { - APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", - __func__, element.GetAbilityName().c_str(), formId_, resultCode); - return; - } - FormSupplyCallback::GetInstance()->AddConnection(this); - - if (want_.HasParameter(Constants::PARAM_MESSAGE_KEY)) { - std::string message = want_.GetStringParam(Constants::PARAM_MESSAGE_KEY); - // FormTaskMgr::GetInstance()->FireFormEvent(formId, message, BuildDefaultWant(null, this), remoteObject); - } else if (want_.HasParameter(Constants::RECREATE_FORM_KEY)) { - Want cloneWant = Want(want_); - cloneWant.RemoveParam(Constants::RECREATE_FORM_KEY); - cloneWant.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_RECREATE_FORM); - cloneWant.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); - FormTaskMgr::GetInstance().PostAcquireTask(formId_, cloneWant, remoteObject); - } else { - Want want; - want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); - FormTaskMgr::GetInstance().PostRefreshTask(formId_, want, remoteObject); - } -} -} // namespace AppExecFwk + +/* + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_refresh_connection.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormRefreshConnection::FormRefreshConnection(const int64_t formId, const Want& want, + const std::string &bundleName, const std::string &abilityName) + :formId_(formId), + want_(want) +{ + SetProviderKey(bundleName, abilityName); +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element Service ability's ElementName. + * @param remoteObject The session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + * @return none. + */ +void FormRefreshConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + + if (want_.HasParameter(Constants::PARAM_MESSAGE_KEY)) { + std::string message = want_.GetStringParam(Constants::PARAM_MESSAGE_KEY); + } else if (want_.HasParameter(Constants::RECREATE_FORM_KEY)) { + Want cloneWant = Want(want_); + cloneWant.RemoveParam(Constants::RECREATE_FORM_KEY); + cloneWant.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_RECREATE_FORM); + cloneWant.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostAcquireTask(formId_, cloneWant, remoteObject); + } else { + Want want; + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostRefreshTask(formId_, want, remoteObject); + } +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_storage_mgr.cpp b/services/formmgr/src/form_storage_mgr.cpp index 6f329ff712a0c3dca9ae071b5cf774530d7185be..7c3745ba00bc310b1f6a8cfbbae27615b797be1e 100644 --- a/services/formmgr/src/form_storage_mgr.cpp +++ b/services/formmgr/src/form_storage_mgr.cpp @@ -1,315 +1,255 @@ -/* - * 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 -#include -#include -#include - -#include "app_log_wrapper.h" -#include "form_storage_mgr.h" -#include "string_ex.h" - -namespace OHOS { -namespace AppExecFwk { -namespace { -const char* FORM_DB_DATA_BASE_FILE_DIR = "/data/formmgr"; -const int32_t FORM_DB_DATA_BASE_FILE_PATH_LEN = 255; -} - -// bool FormStorageMgr::KeyToDeviceAndName(const std::string &key, std::string &deviceId, std::string &bundleName) const -// { -// bool ret = false; -// std::vector splitStrs; -// const std::string::size_type EXPECT_SPLIT_SIZE = 2; -// OHOS::SplitStr(key, Constants::FILE_UNDERLINE, splitStrs); -// // the expect split size should be 2. -// // key rule is _ -// if (splitStrs.size() == EXPECT_SPLIT_SIZE) { -// deviceId = splitStrs[0]; -// bundleName = splitStrs[1]; -// ret = true; -// } -// APP_LOGD("key = %{private}s, bundleName = %{public}s", key.c_str(), bundleName.c_str()); -// return ret; -// } - -// void FormStorageMgr::DeviceAndNameToKey( -// const std::string &deviceId, const std::string &bundleName, std::string &key) const -// { -// key.append(deviceId); -// key.append(Constants::FILE_UNDERLINE); -// key.append(bundleName); -// APP_LOGD("key = %{private}s, bundleName = %{public}s", key.c_str(), bundleName.c_str()); -// } - -// bool FormStorageMgr::bool LoadAllData(std::map> &infos) const -// { -// bool ret = false; -// APP_LOGI("load all installed bundle data to map"); - -// std::fstream i(Constants::BUNDLE_DATA_BASE_FILE); -// nlohmann::json jParse; -// if (!i.is_open()) { -// APP_LOGE("failed to open bundle database file"); -// // if file not exist, should create file here -// std::ofstream o(Constants::BUNDLE_DATA_BASE_FILE); -// o.close(); -// return false; -// } -// APP_LOGI("open bundle database file success"); -// i.seekg(0, std::ios::end); -// int len = static_cast(i.tellg()); -// if (len > 0) { -// i.seekg(0, std::ios::beg); -// i >> jParse; -// for (auto &app : jParse.items()) { -// std::map deviceMap; -// for (auto &device : app.value().items()) { -// InnerBundleInfo innerBundleInfo; -// ret = innerBundleInfo.FromJson(device.value()); -// deviceMap.emplace(device.key(), innerBundleInfo); -// } -// auto pair = infos.emplace(app.key(), deviceMap); -// ret = pair.second; -// } -// } -// i.close(); -// return ret; -// } - -/** - * @brief Load form data from fileNamePath to innerFormInfos. - * @param fileNamePath load file path. - * @param innerFormInfos Save form data. - * @return Returns true if the data is successfully loaded; returns false otherwise. - */ -static bool LoadFormDataFile(const char* fileNamePath, std::vector &innerFormInfos) -{ - bool ret = false; - std::ifstream i(fileNamePath); - if (!i.is_open()) { - APP_LOGE("%{public}s, failed to open file[%{public}s]", __func__, fileNamePath); - return false; - } - - nlohmann::json jParse; - i.seekg(0, std::ios::end); - int len = static_cast(i.tellg()); - if (len != 0) { - i.seekg(0, std::ios::beg); - i >> jParse; - for (auto &it : jParse.items()) { - InnerFormInfo innerFormInfo; - if (innerFormInfo.FromJson(it.value())) { - innerFormInfos.emplace_back(innerFormInfo); - } else { - APP_LOGE("%{public}s, failed to parse json, formId[%{public}s]", __func__, it.key().c_str()); - } - } - ret = true; - } else { - APP_LOGE("%{public}s, file[%{public}s] is empty", __func__, fileNamePath); - ret = false; - } - i.close(); - return ret; -} - -/** - * @brief Load all form data from DB to innerFormInfos. - * @param innerFormInfos Storage all form data. - * @return Returns ERR_OK on success, others on failure. - */ -ErrCode FormStorageMgr::LoadFormData(std::vector &innerFormInfos) const -{ - APP_LOGI("%{public}s called.", __func__); - DIR *dirptr = opendir(FORM_DB_DATA_BASE_FILE_DIR); - if (dirptr == NULL) { - APP_LOGE("%{public}s, opendir failed, should no formmgr dir", __func__); - return ERR_APPEXECFWK_FORM_JSON_NO_DIR; - } - - struct dirent *ptr; - while ((ptr = readdir(dirptr)) != NULL) { - APP_LOGI("%{public}s, readdir fileName[%{public}s]", __func__, ptr->d_name); - if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0)) { - continue; - } - char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; - sprintf(fileNamePath, "%s/%s", FORM_DB_DATA_BASE_FILE_DIR, ptr->d_name); - if (!LoadFormDataFile(fileNamePath, innerFormInfos)) { - APP_LOGE("%{public}s, LoadFormDataFile failed, file[%{public}s]", __func__, ptr->d_name); - } - } - APP_LOGI("%{public}s, readdir over", __func__); - closedir(dirptr); - return ERR_OK; -} - -/** - * @brief Get form data from DB to innerFormInfo with formId. - * @param innerFormInfo Storage form data. - * @return Returns ERR_OK on success, others on failure. - */ -ErrCode FormStorageMgr::GetStorageFormInfoById(const std::string &formId, InnerFormInfo &innerFormInfo) const -{ - ErrCode ret = ERR_OK; - APP_LOGD("%{public}s called, formId[%{public}s]", __func__, formId.c_str()); - char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; - sprintf(fileNamePath, "%s/%s.json", FORM_DB_DATA_BASE_FILE_DIR, formId.c_str()); - std::ifstream i(fileNamePath); - nlohmann::json jParse; - if (!i.is_open()) { - APP_LOGE("%{public}s, open failed, should no this file[%{public}s.json]", __func__, formId.c_str()); - return ERR_APPEXECFWK_FORM_JSON_OPEN_FAIL; - } - APP_LOGD("%{public}s, open success file[%{public}s.json]", __func__, formId.c_str()); - i.seekg(0, std::ios::end); - int len = static_cast(i.tellg()); - if (len != 0) { - i.seekg(0, std::ios::beg); - i >> jParse; - auto it = jParse.find(formId); - if (it != jParse.end()) { - if (innerFormInfo.FromJson(it.value()) == false) { - APP_LOGE("%{public}s, fromJson parse failed formId[%{public}s]", __func__, it.key().c_str()); - ret = ERR_APPEXECFWK_FORM_JSON_PARSE_FAIL; - } else { - ret = ERR_OK; - } - } else { - APP_LOGE("%{public}s, not find formId[%{public}s]", __func__, formId.c_str()); - ret = ERR_APPEXECFWK_FORM_JSON_FIND_FAIL; - } - } else { - APP_LOGE("%{public}s, file is empty formId[%{public}s]", __func__, formId.c_str()); - ret = ERR_APPEXECFWK_FORM_JSON_FILE_EMPTY; - } - i.close(); - - return ret; -} - -/** - * @brief Save or update the form data in DB. - * @param innerFormInfo Indicates the InnerFormInfo object to be save. - * @return Returns ERR_OK on success, others on failure. - */ -ErrCode FormStorageMgr::SaveStorageFormInfo(const InnerFormInfo &innerFormInfo) const -{ - APP_LOGI("%{public}s called, formId[%{public}" PRId64 "]", __func__, innerFormInfo.GetFormId()); - ErrCode ret = ERR_OK; - std::string formId = std::to_string(innerFormInfo.GetFormId()); - - DIR *dirptr = opendir(FORM_DB_DATA_BASE_FILE_DIR); - if (dirptr == NULL) { - APP_LOGW("%{public}s, failed to open dir", __func__); - if (-1 == mkdir(FORM_DB_DATA_BASE_FILE_DIR, S_IRWXU)) { - APP_LOGE("%{public}s, failed to create dir", __func__); - return ERR_APPEXECFWK_FORM_JSON_CREATE_DIR_FAIL; - } - } else { - closedir(dirptr); - } - char tmpFilePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; - sprintf(tmpFilePath, "%s/%s.json", FORM_DB_DATA_BASE_FILE_DIR, formId.c_str()); - - std::fstream f(tmpFilePath); - nlohmann::json jParse; - if (!f.is_open()) { - std::ofstream o(tmpFilePath); // if file not exist, should create file here - if (!o.is_open()) { - APP_LOGE("%{public}s, touch new file[%{public}s] failed", __func__, tmpFilePath); - return ERR_APPEXECFWK_FORM_JSON_NEW_FILE_FAIL; - } - o.close(); - APP_LOGI("%{public}s, touch new file[%{public}s.json]", __func__, formId.c_str()); - f.open(tmpFilePath); - } - bool isExist = f.good(); - if (isExist) { - nlohmann::json innerInfo; - innerFormInfo.ToJson(innerInfo); - f.seekg(0, std::ios::end); - int len = static_cast(f.tellg()); - if (len == 0) { - nlohmann::json formRoot; - formRoot[formId] = innerInfo; - f << formRoot << std::endl; - } else { - APP_LOGE("%{public}s, file[%{public}s.json] is not empty", __func__, formId.c_str()); - } - } else { - APP_LOGE("%{public}s, touch new file[%{public}s] failed", __func__, formId.c_str()); - ret = ERR_APPEXECFWK_FORM_JSON_OPEN_FAIL; - } - f.close(); - return ret; -} - -/** - * @brief Modify the form data in DB. - * @param innerFormInfo Indicates the InnerFormInfo object to be Modify. - * @return Returns ERR_OK on success, others on failure. - */ -ErrCode FormStorageMgr::ModifyStorageFormInfo(const InnerFormInfo &innerFormInfo) const -{ - APP_LOGI("%{public}s called, formId[%{public}" PRId64 "]", __func__, innerFormInfo.GetFormId()); - char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; - sprintf(fileNamePath, "%s/%" PRId64 ".json", FORM_DB_DATA_BASE_FILE_DIR, innerFormInfo.GetFormId()); - - std::ofstream o(fileNamePath, std::ios_base::trunc | std::ios_base::out); - if (!o.is_open()) { - APP_LOGE("%{public}s, open failed file[%{public}s]", __func__, fileNamePath); - return ERR_APPEXECFWK_FORM_JSON_OPEN_FAIL; - } - - nlohmann::json innerInfo; - innerFormInfo.ToJson(innerInfo); - nlohmann::json formRoot; - std::string formId = std::to_string(innerFormInfo.GetFormId()); - - formRoot[formId] = innerInfo; - o << formRoot << std::endl; - - o.close(); - return ERR_OK; -} - -/** - * @brief Delete the form data in DB. - * @param formId The form data Id. - * @return Returns ERR_OK on success, others on failure. - */ -ErrCode FormStorageMgr::DeleteStorageFormInfo(const std::string &formId) const -{ - APP_LOGI("%{public}s called, formId[%{public}s]", __func__, formId.c_str()); - char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; - sprintf(fileNamePath, "%s/%s.json", FORM_DB_DATA_BASE_FILE_DIR, formId.c_str()); - - if (std::remove(fileNamePath) != 0) { - APP_LOGE("%{public}s, delete failed file[%{public}s]", __func__, fileNamePath); - return ERR_APPEXECFWK_FORM_JSON_DELETE_FAIL; - } - - return ERR_OK; -} -} // namespace AppExecFwk -} // namespace OHOS +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "securec.h" +#include "app_log_wrapper.h" +#include "form_storage_mgr.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const char* FORM_DB_DATA_BASE_FILE_DIR = "/data/formmgr"; +const int32_t FORM_DB_DATA_BASE_FILE_PATH_LEN = 255; +} + +/** + * @brief Load form data from fileNamePath to innerFormInfos. + * @param fileNamePath load file path. + * @param innerFormInfos Save form data. + * @return Returns true if the data is successfully loaded; returns false otherwise. + */ +static bool LoadFormDataFile(const char* fileNamePath, std::vector &innerFormInfos) +{ + bool ret = false; + std::ifstream i(fileNamePath); + if (!i.is_open()) { + APP_LOGE("%{public}s, failed to open file[%{public}s]", __func__, fileNamePath); + return false; + } + + nlohmann::json jParse; + i.seekg(0, std::ios::end); + int len = static_cast(i.tellg()); + if (len != 0) { + i.seekg(0, std::ios::beg); + i >> jParse; + for (auto &it : jParse.items()) { + InnerFormInfo innerFormInfo; + if (innerFormInfo.FromJson(it.value())) { + innerFormInfos.emplace_back(innerFormInfo); + } else { + APP_LOGE("%{public}s, failed to parse json, formId[%{public}s]", __func__, it.key().c_str()); + } + } + ret = true; + } else { + APP_LOGE("%{public}s, file[%{public}s] is empty", __func__, fileNamePath); + ret = false; + } + i.close(); + return ret; +} + +/** + * @brief Load all form data from DB to innerFormInfos. + * @param innerFormInfos Storage all form data. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormStorageMgr::LoadFormData(std::vector &innerFormInfos) const +{ + APP_LOGI("%{public}s called.", __func__); + DIR *dirptr = opendir(FORM_DB_DATA_BASE_FILE_DIR); + if (dirptr == NULL) { + APP_LOGE("%{public}s, opendir failed, should no formmgr dir", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + struct dirent *ptr; + while ((ptr = readdir(dirptr)) != NULL) { + APP_LOGI("%{public}s, readdir fileName[%{public}s]", __func__, ptr->d_name); + if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0)) { + continue; + } + char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; + sprintf_s(fileNamePath, FORM_DB_DATA_BASE_FILE_PATH_LEN, "%s/%s", FORM_DB_DATA_BASE_FILE_DIR, ptr->d_name); + if (!LoadFormDataFile(fileNamePath, innerFormInfos)) { + APP_LOGE("%{public}s, LoadFormDataFile failed, file[%{public}s]", __func__, ptr->d_name); + } + } + APP_LOGI("%{public}s, readdir over", __func__); + closedir(dirptr); + return ERR_OK; +} + +/** + * @brief Get form data from DB to innerFormInfo with formId. + * @param innerFormInfo Storage form data. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormStorageMgr::GetStorageFormInfoById(const std::string &formId, InnerFormInfo &innerFormInfo) const +{ + ErrCode ret = ERR_OK; + APP_LOGD("%{public}s called, formId[%{public}s]", __func__, formId.c_str()); + char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; + sprintf_s(fileNamePath, FORM_DB_DATA_BASE_FILE_PATH_LEN, "%s/%s.json", FORM_DB_DATA_BASE_FILE_DIR, formId.c_str()); + std::ifstream i(fileNamePath); + nlohmann::json jParse; + if (!i.is_open()) { + APP_LOGE("%{public}s, open failed, should no this file[%{public}s.json]", __func__, formId.c_str()); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + APP_LOGD("%{public}s, open success file[%{public}s.json]", __func__, formId.c_str()); + i.seekg(0, std::ios::end); + int len = static_cast(i.tellg()); + if (len != 0) { + i.seekg(0, std::ios::beg); + i >> jParse; + auto it = jParse.find(formId); + if (it != jParse.end()) { + if (innerFormInfo.FromJson(it.value()) == false) { + APP_LOGE("%{public}s, fromJson parse failed formId[%{public}s]", __func__, it.key().c_str()); + ret = ERR_APPEXECFWK_FORM_COMMON_CODE; + } else { + ret = ERR_OK; + } + } else { + APP_LOGE("%{public}s, not find formId[%{public}s]", __func__, formId.c_str()); + ret = ERR_APPEXECFWK_FORM_COMMON_CODE; + } + } else { + APP_LOGE("%{public}s, file is empty formId[%{public}s]", __func__, formId.c_str()); + ret = ERR_APPEXECFWK_FORM_COMMON_CODE; + } + i.close(); + + return ret; +} + +/** + * @brief Save or update the form data in DB. + * @param innerFormInfo Indicates the InnerFormInfo object to be save. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormStorageMgr::SaveStorageFormInfo(const InnerFormInfo &innerFormInfo) const +{ + APP_LOGI("%{public}s called, formId[%{public}" PRId64 "]", __func__, innerFormInfo.GetFormId()); + ErrCode ret = ERR_OK; + std::string formId = std::to_string(innerFormInfo.GetFormId()); + + DIR *dirptr = opendir(FORM_DB_DATA_BASE_FILE_DIR); + if (dirptr == NULL) { + APP_LOGW("%{public}s, failed to open dir", __func__); + if (-1 == mkdir(FORM_DB_DATA_BASE_FILE_DIR, S_IRWXU)) { + APP_LOGE("%{public}s, failed to create dir", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + } else { + closedir(dirptr); + } + char tmpFilePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; + sprintf_s(tmpFilePath, FORM_DB_DATA_BASE_FILE_PATH_LEN, "%s/%s.json", FORM_DB_DATA_BASE_FILE_DIR, formId.c_str()); + std::fstream f(tmpFilePath); + nlohmann::json jParse; + if (!f.is_open()) { + std::ofstream o(tmpFilePath); // if file not exist, should create file here + if (!o.is_open()) { + APP_LOGE("%{public}s, touch new file[%{public}s] failed", __func__, tmpFilePath); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + o.close(); + APP_LOGI("%{public}s, touch new file[%{public}s.json]", __func__, formId.c_str()); + f.open(tmpFilePath); + } + bool isExist = f.good(); + if (isExist) { + nlohmann::json innerInfo; + innerFormInfo.ToJson(innerInfo); + f.seekg(0, std::ios::end); + int len = static_cast(f.tellg()); + if (len == 0) { + nlohmann::json formRoot; + formRoot[formId] = innerInfo; + f << formRoot << std::endl; + } else { + APP_LOGE("%{public}s, file[%{public}s.json] is not empty", __func__, formId.c_str()); + } + } else { + APP_LOGE("%{public}s, touch new file[%{public}s] failed", __func__, formId.c_str()); + ret = ERR_APPEXECFWK_FORM_COMMON_CODE; + } + f.close(); + return ret; +} + +/** + * @brief Modify the form data in DB. + * @param innerFormInfo Indicates the InnerFormInfo object to be Modify. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormStorageMgr::ModifyStorageFormInfo(const InnerFormInfo &innerFormInfo) const +{ + APP_LOGI("%{public}s called, formId[%{public}" PRId64 "]", __func__, innerFormInfo.GetFormId()); + char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; + sprintf_s(fileNamePath, FORM_DB_DATA_BASE_FILE_PATH_LEN, "%s/%" PRId64 ".json", FORM_DB_DATA_BASE_FILE_DIR, innerFormInfo.GetFormId()); + + std::ofstream o(fileNamePath, std::ios_base::trunc | std::ios_base::out); + if (!o.is_open()) { + APP_LOGE("%{public}s, open failed file[%{public}s]", __func__, fileNamePath); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + nlohmann::json innerInfo; + innerFormInfo.ToJson(innerInfo); + nlohmann::json formRoot; + std::string formId = std::to_string(innerFormInfo.GetFormId()); + + formRoot[formId] = innerInfo; + o << formRoot << std::endl; + + o.close(); + return ERR_OK; +} + +/** + * @brief Delete the form data in DB. + * @param formId The form data Id. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormStorageMgr::DeleteStorageFormInfo(const std::string &formId) const +{ + APP_LOGI("%{public}s called, formId[%{public}s]", __func__, formId.c_str()); + char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; + sprintf_s(fileNamePath, FORM_DB_DATA_BASE_FILE_PATH_LEN, "%s/%s.json", FORM_DB_DATA_BASE_FILE_DIR, formId.c_str()); + + if (std::remove(fileNamePath) != 0) { + APP_LOGE("%{public}s, delete failed file[%{public}s]", __func__, fileNamePath); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + return ERR_OK; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_supply_callback.cpp b/services/formmgr/src/form_supply_callback.cpp index 9a240bf1d57918b3e9d80d6c2d4f4fd981a88dcf..3fef6de0c6574e725202e0f71cd41817f45d641e 100644 --- a/services/formmgr/src/form_supply_callback.cpp +++ b/services/formmgr/src/form_supply_callback.cpp @@ -1,120 +1,156 @@ -/* - * 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 "appexecfwk_errors.h" -#include "app_log_wrapper.h" -#include "form_ams_helper.h" -#include "form_constants.h" -#include "form_provider_mgr.h" -#include "form_supply_callback.h" -#include "form_util.h" -#include "string_ex.h" - -namespace OHOS { -namespace AppExecFwk { -sptr FormSupplyCallback::instance_ = nullptr; -std::mutex FormSupplyCallback::mutex_; - -sptr FormSupplyCallback::GetInstance() -{ - if (instance_ == nullptr) { - std::lock_guard lock_l(mutex_); - if (instance_ == nullptr) { - instance_ = new FormSupplyCallback(); - } - } - return instance_; -} - -/** - * @brief Accept form binding data from form provider. - * @param providerFormInfo Form binding data. - * @param want input data. - * @return Returns ERR_OK on success, others on failure. - */ -int FormSupplyCallback::OnAcquire(const FormProviderInfo &formProviderInfo, const Want &want) -{ - long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); - int errCode = want.GetIntParam(Constants::PROVIDER_FLAG, ERR_OK); - if (errCode != ERR_OK) { - RemoveConnection(connectId); - return errCode; - } - - int64_t formId = formProviderInfo.GetFormId(); - int type = want.GetIntParam(Constants::ACQUIRE_TYPE, 0); - APP_LOGD("%{public}s come: %{public}" PRId64 ", %{public}ld, %{public}d", __func__, - formId, connectId, type); - RemoveConnection(connectId); - - switch (type) { - case Constants::ACQUIRE_TYPE_CREATE_FORM: - return FormProviderMgr::GetInstance().AcquireForm(formId, formProviderInfo); - case Constants::ACQUIRE_TYPE_RECREATE_FORM: - return FormProviderMgr::GetInstance().UpdateForm(formId, formProviderInfo); - default: - APP_LOGW("%{public}s warning, onAcquired type: %{public}d", __func__, type); - } - return ERR_APPEXECFWK_FORM_INVALID_PARAM; -} - -/** - * @brief Accept other event. - * @param want input data. - * @return Returns ERR_OK on success, others on failure. - */ -int FormSupplyCallback::OnEventHandle(const Want &want) -{ - long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); - std::string supplyInfo = want.GetStringParam(Constants::FORM_SUPPLY_INFO); - APP_LOGD("%{public}s come: %{public}ld, %{public}s", __func__, connectId, supplyInfo.c_str()); - RemoveConnection(connectId); - return ERR_OK; -} -/** - * @brief Save ability Connection for the callback. - * @param connection ability connection. - */ -void FormSupplyCallback::AddConnection(sptr connection) -{ - std::lock_guard lock_l(conMutex_); - long connectKey = FormUtil::GetCurrentMillisecond(); - while (connections_.find(connectKey) != connections_.end()) { - connectKey++; - } - connection->SetConnectId(connectKey); - connections_.emplace(connectKey, connection); -} - -/** - * @brief Delete ability connection after the callback come. - * @param connectId The ability connection id generated when save. - */ -void FormSupplyCallback::RemoveConnection(long connectId) -{ - std::lock_guard lock_l(conMutex_); - auto conIterator = connections_.find(connectId); - if (conIterator != connections_.end()) { - sptr connection = conIterator->second; - if (connection != nullptr) { - FormAmsHelper::GetInstance().DisConnectServiceAbility(connection); - } - connections_.erase(connectId); - } -} -} // namespace AppExecFwk -} // namespace OHOS +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_ams_helper.h" +#include "form_constants.h" +#include "form_provider_mgr.h" +#include "form_supply_callback.h" +#include "form_util.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +sptr FormSupplyCallback::instance_ = nullptr; +std::mutex FormSupplyCallback::mutex_; + +sptr FormSupplyCallback::GetInstance() +{ + if (instance_ == nullptr) { + std::lock_guard lock_l(mutex_); + if (instance_ == nullptr) { + instance_ = new FormSupplyCallback(); + } + } + return instance_; +} + +/** + * @brief Accept form binding data from form provider. + * @param providerFormInfo Form binding data. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyCallback::OnAcquire(const FormProviderInfo &formProviderInfo, const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + int errCode = want.GetIntParam(Constants::PROVIDER_FLAG, ERR_OK); + if (errCode != ERR_OK) { + RemoveConnection(connectId); + return errCode; + } + + std::string strFormId = want.GetStringParam(Constants::PARAM_FORM_IDENTITY_KEY); + int64_t formId = std::stoll(strFormId); + int type = want.GetIntParam(Constants::ACQUIRE_TYPE, 0); + APP_LOGD("%{public}s come: %{public}" PRId64 ", %{public}ld, %{public}d", __func__, + formId, connectId, type); + RemoveConnection(connectId); + + switch (type) { + case Constants::ACQUIRE_TYPE_CREATE_FORM: + return FormProviderMgr::GetInstance().AcquireForm(formId, formProviderInfo); + case Constants::ACQUIRE_TYPE_RECREATE_FORM: + return FormProviderMgr::GetInstance().UpdateForm(formId, formProviderInfo); + default: + APP_LOGW("%{public}s warning, onAcquired type: %{public}d", __func__, type); + } + APP_LOGI("%{public}s end.", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; +} + +/** + * @brief Accept other event. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyCallback::OnEventHandle(const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + std::string supplyInfo = want.GetStringParam(Constants::FORM_SUPPLY_INFO); + APP_LOGD("%{public}s come: %{public}ld, %{public}s", __func__, connectId, supplyInfo.c_str()); + RemoveConnection(connectId); + APP_LOGI("%{public}s end.", __func__); + return ERR_OK; +} +/** + * @brief Save ability Connection for the callback. + * @param connection ability connection. + */ +void FormSupplyCallback::AddConnection(sptr connection) +{ + APP_LOGI("%{public}s called.", __func__); + std::lock_guard lock_l(conMutex_); + long connectKey = FormUtil::GetCurrentMillisecond(); + while (connections_.find(connectKey) != connections_.end()) { + connectKey++; + } + connection->SetConnectId(connectKey); + connections_.emplace(connectKey, connection); + APP_LOGI("%{public}s end.", __func__); +} + +/** + * @brief Delete ability connection after the callback come. + * @param connectId The ability connection id generated when save. + */ +void FormSupplyCallback::RemoveConnection(long connectId) +{ + APP_LOGI("%{public}s called.", __func__); + std::lock_guard lock_l(conMutex_); + auto conIterator = connections_.find(connectId); + if (conIterator != connections_.end()) { + sptr connection = conIterator->second; + if (connection != nullptr) { + if(CanDisConnect(connection)) { + FormAmsHelper::GetInstance().DisConnectServiceAbility(connection); + APP_LOGI("%{public}s end, disconnect service ability", __func__); + } else { + FormAmsHelper::GetInstance().DisConnectServiceAbilityDelay(connection); + APP_LOGI("%{public}s end, disconnect service ability delay", __func__); + } + } + connections_.erase(connectId); + } + APP_LOGI("%{public}s end.", __func__); +} +/** + * @brief check if disconnect ability or not. + * @param connection The ability connection. + */ +bool FormSupplyCallback::CanDisConnect(sptr &connection) +{ + APP_LOGI("%{public}s called.", __func__); + int count = 0; + for(auto &conn : connections_) { + if(connection->GetProviderKey() == conn.second->GetProviderKey()) { + APP_LOGI("%{public}s, key: %{public}s", __func__, conn.second->GetProviderKey().c_str()); + count++; + if(count > 1) { + APP_LOGI("%{public}s end, true.", __func__); + return true; + } + } + } + APP_LOGI("%{public}s end, false.", __func__); + return false; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_sys_event_receiver.cpp b/services/formmgr/src/form_sys_event_receiver.cpp index 33f940538007f2984671cb412e6d4af89329fe11..0fd6edcd7af5f3a947fd82dc5911b18e221b5c57 100644 --- a/services/formmgr/src/form_sys_event_receiver.cpp +++ b/services/formmgr/src/form_sys_event_receiver.cpp @@ -52,10 +52,9 @@ void FormSysEventReceiver::OnReceiveEvent(const EventFwk::CommonEventData &event AAFwk::Want want = eventData.GetWant(); std::string action = want.GetAction(); std::string bundleName = want.GetStringParam(KEY_BUNDLE_NAME); - if (action.empty() || bundleName.empty()) { - APP_LOGE("%{public}s failed, invalid param, action: %{public}s, bundleName: %{public}s", __func__, - action.c_str(), bundleName.c_str()); + APP_LOGE("%{public}s failed, invalid param, action: %{public}s, bundleName: %{public}s", + __func__, action.c_str(), bundleName.c_str()); return; } APP_LOGI("%{public}s, action:%{public}s.", __func__, action.c_str()); @@ -172,8 +171,8 @@ void FormSysEventReceiver::HandleProviderRemoved(const std::string &bundleName) } } -bool FormSysEventReceiver::ProviderFormUpdated(const int64_t formId, const FormRecord &formRecord, -const std::vector &targetForms) +bool FormSysEventReceiver::ProviderFormUpdated(const int64_t formId, + const FormRecord &formRecord, const std::vector &targetForms) { APP_LOGI("%{public}s start", __func__); if (targetForms.empty()) { @@ -270,7 +269,7 @@ void FormSysEventReceiver::ClearTempFormRecordData(const int uid, std::map> &noHostFormDbMap, std::map &removedFormsMap) + std::set> &noHostFormDbMap, std::map &removedFormsMap) { std::set removableModuleSet; for (const auto &element: noHostFormDbMap) { @@ -280,7 +279,8 @@ std::set> &noHostFormDbMap, std::map &removedFormsMap) std::string abilityName = formIdKey.abilityName; int result = FormProviderMgr::GetInstance().NotifyProviderFormsBatchDelete(bundleName, abilityName, formIds); if (result != ERR_OK) { - APP_LOGE("%{public}s error, NotifyProviderFormsBatchDelete failed! bundleName:%{public}s, abilityName:%{public}s", + APP_LOGE("%{public}s error, NotifyProviderFormsBatchDelete failed! bundleName:%{public}s,\ + abilityName:%{public}s", __func__, bundleName.c_str(), abilityName.c_str()); for (int64_t formId : formIds) { FormDBInfo dbInfo; @@ -321,7 +321,7 @@ std::set> &noHostFormDbMap, std::map &removedFormsMap) * @param foundFormsMap Form Id list. */ void FormSysEventReceiver::BatchDeleteNoHostTempForms(const int uid, std::map> &noHostTempFormsMap, std::map &foundFormsMap) + std::set> &noHostTempFormsMap, std::map &foundFormsMap) { for (const auto &element : noHostTempFormsMap) { std::set formIds = element.second; @@ -330,7 +330,8 @@ std::set> &noHostTempFormsMap, std::map &foundFormsMap) std::string abilityName = formIdKey.abilityName; int result = FormProviderMgr::GetInstance().NotifyProviderFormsBatchDelete(bundleName, abilityName, formIds); if (result != ERR_OK) { - APP_LOGE("%{public}s error, NotifyProviderFormsBatchDelete failed! bundleName:%{public}s, abilityName:%{public}s", + APP_LOGE("%{public}s error, NotifyProviderFormsBatchDelete failed! bundleName:%{public}s,\ + abilityName:%{public}s", __func__, bundleName.c_str(), abilityName.c_str()); for (int64_t formId : formIds) { FormDataMgr::GetInstance().AddFormUserUid(formId, uid); @@ -369,8 +370,8 @@ void FormSysEventReceiver::ReCreateForm(const int64_t formId) want.SetParam(Constants::RECREATE_FORM_KEY, true); FormProviderMgr::GetInstance().ConnectAmsForRefresh(formId, reCreateRecord, want, false); } -void FormSysEventReceiver::GetTimerCfg(const bool updateEnabled, const int updateDuration, -const std::string &configUpdateAt, FormTimerCfg& cfg) +void FormSysEventReceiver::GetTimerCfg(const bool updateEnabled, + const int updateDuration, const std::string &configUpdateAt, FormTimerCfg& cfg) { APP_LOGI("%{public}s start", __func__); if (!updateEnabled) { @@ -414,7 +415,7 @@ const std::string &configUpdateAt, FormTimerCfg& cfg) } if (hour < Constants::MIN_TIME || hour > Constants::MAX_HOUR || min < Constants::MIN_TIME || min > - Constants::MAX_MININUTE) { + Constants::MAX_MININUTE) { APP_LOGE("%{public}s, time is invalid", __func__); return; } @@ -426,8 +427,8 @@ const std::string &configUpdateAt, FormTimerCfg& cfg) } } -void FormSysEventReceiver::HandleTimerUpdate(const int64_t formId, const FormRecord &record, -const FormTimerCfg &timerCfg) +void FormSysEventReceiver::HandleTimerUpdate(const int64_t formId, + const FormRecord &record, const FormTimerCfg &timerCfg) { // both disable if (!record.isEnableUpdate && !timerCfg.enableUpdate) { @@ -443,14 +444,14 @@ const FormTimerCfg &timerCfg) // disable to enable if (!record.isEnableUpdate && timerCfg.enableUpdate) { - FormDataMgr::GetInstance().SetUpdateInfo(formId, true, timerCfg.updateDuration, timerCfg.updateAtHour, - timerCfg.updateAtMin); + FormDataMgr::GetInstance().SetUpdateInfo(formId, true, + timerCfg.updateDuration, timerCfg.updateAtHour, timerCfg.updateAtMin); if (timerCfg.updateDuration > 0) { APP_LOGI("%{public}s, add interval timer:%{public}" PRId64 "", __func__, timerCfg.updateDuration); FormTimerMgr::GetInstance().AddFormTimer(formId, timerCfg.updateDuration); } else { - APP_LOGI("%{public}s, add at timer:%{public}d, %{public}d", __func__, timerCfg.updateAtHour, - timerCfg.updateAtMin); + APP_LOGI("%{public}s, add at timer:%{public}d, %{public}d", __func__, + timerCfg.updateAtHour, timerCfg.updateAtMin); FormTimerMgr::GetInstance().AddFormTimer(formId, timerCfg.updateAtHour, timerCfg.updateAtMin); } @@ -485,8 +486,8 @@ const FormTimerCfg &timerCfg) } } - FormDataMgr::GetInstance().SetUpdateInfo(formId, true, timerCfg.updateDuration, timerCfg.updateAtHour, - timerCfg.updateAtMin); + FormDataMgr::GetInstance().SetUpdateInfo(formId, true, + timerCfg.updateDuration, timerCfg.updateAtHour, timerCfg.updateAtMin); FormTimerMgr::GetInstance().UpdateFormTimer(formId, type, timerCfg); } } // namespace AppExecFwk diff --git a/services/formmgr/src/form_task_mgr.cpp b/services/formmgr/src/form_task_mgr.cpp index bcd4376d94d373c04c86c0851c841f9f0a4bf7f8..cbaa7fa32fd2b5308990b800b20333bde68f2361 100644 --- a/services/formmgr/src/form_task_mgr.cpp +++ b/services/formmgr/src/form_task_mgr.cpp @@ -20,6 +20,7 @@ #include "form_data_mgr.h" #include "form_host_interface.h" #include "form_item_info.h" +#include "form_mgr_adapter.h" #include "form_provider_interface.h" #include "form_supply_callback.h" #include "form_task_mgr.h" @@ -27,6 +28,7 @@ namespace OHOS { namespace AppExecFwk { +const int FORM_TASK_DELAY_TIME = 6; // ms FormTaskMgr::FormTaskMgr() {} FormTaskMgr::~FormTaskMgr() {} /** @@ -41,13 +43,9 @@ void FormTaskMgr::PostAcquireTask(const int64_t formId, const Want &want, const APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); return; } - std::function acquireProviderFormInfoFunc = std::bind( - &FormTaskMgr::AcquireProviderFormInfo, - this, - formId, - want, - remoteObject); - eventHandler_->PostTask(acquireProviderFormInfoFunc); + std::function acquireProviderFormInfoFunc = std::bind(&FormTaskMgr::AcquireProviderFormInfo, + this, formId, want, remoteObject); + eventHandler_->PostTask(acquireProviderFormInfoFunc, FORM_TASK_DELAY_TIME); } /** * @brief Delete form data from form provider(task). @@ -61,13 +59,9 @@ void FormTaskMgr::PostDeleteTask(const int64_t formId, const Want &want, const s APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); return; } - std::function notifyFormDeleteFunc = std::bind ( - &FormTaskMgr::NotifyFormDelete, - this, - formId, - want, - remoteObject); - eventHandler_->PostTask(notifyFormDeleteFunc); + std::function notifyFormDeleteFunc = std::bind(&FormTaskMgr::NotifyFormDelete, + this, formId, want, remoteObject); + eventHandler_->PostTask(notifyFormDeleteFunc, FORM_TASK_DELAY_TIME); } /** @@ -84,13 +78,9 @@ void FormTaskMgr::PostRefreshTask(const int64_t formId, const Want &want, const APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); return; } - std::function notifyFormUpdateFunc = std::bind ( - &FormTaskMgr::NotifyFormUpdate, - this, - formId, - want, - remoteObject); - eventHandler_->PostTask(notifyFormUpdateFunc); + std::function notifyFormUpdateFunc = std::bind(&FormTaskMgr::NotifyFormUpdate, + this, formId, want, remoteObject); + eventHandler_->PostTask(notifyFormUpdateFunc, FORM_TASK_DELAY_TIME); } /** @@ -107,13 +97,9 @@ void FormTaskMgr::PostCastTempTask(const int64_t formId, const Want &want, const APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); return; } - std::function notifyCastTempFunc = std::bind ( - &FormTaskMgr::NotifyCastTemp, - this, - formId, - want, - remoteObject); - eventHandler_->PostTask(notifyCastTempFunc); + std::function notifyCastTempFunc = std::bind(&FormTaskMgr::NotifyCastTemp, + this, formId, want, remoteObject); + eventHandler_->PostTask(notifyCastTempFunc, FORM_TASK_DELAY_TIME); } /** @@ -125,19 +111,15 @@ void FormTaskMgr::PostCastTempTask(const int64_t formId, const Want &want, const * @param remoteObject Form provider proxx object. */ void FormTaskMgr::PostAcquireTaskToHost(const int64_t formId, const FormRecord &record, -const sptr &remoteObject) + const sptr &remoteObject) { if (eventHandler_ == nullptr) { APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); return; } - std::function acquireTaskToHostFunc = std::bind ( - &FormTaskMgr::AcquireTaskToHost, - this, - formId, - record, - remoteObject); - eventHandler_->PostTask(acquireTaskToHostFunc); + std::function acquireTaskToHostFunc = std::bind(&FormTaskMgr::AcquireTaskToHost, + this, formId, record, remoteObject); + eventHandler_->PostTask(acquireTaskToHostFunc, FORM_TASK_DELAY_TIME); } /** @@ -149,7 +131,7 @@ const sptr &remoteObject) * @param remoteObject Form provider proxx object. */ void FormTaskMgr::PostUpdateTaskToHost(const int64_t formId, const FormRecord &record, -const sptr &remoteObject) + const sptr &remoteObject) { APP_LOGI("%{public}s called.", __func__); @@ -159,13 +141,9 @@ const sptr &remoteObject) } APP_LOGD("%{public}s, post the task of updateTaskToHostFunc.", __func__); - std::function updateTaskToHostFunc = std::bind ( - &FormTaskMgr::UpdateTaskToHost, - this, - formId, - record, - remoteObject); - eventHandler_->PostTask(updateTaskToHostFunc); + std::function updateTaskToHostFunc = std::bind(&FormTaskMgr::UpdateTaskToHost, + this, formId, record, remoteObject); + eventHandler_->PostTask(updateTaskToHostFunc, FORM_TASK_DELAY_TIME); } /** @@ -185,11 +163,9 @@ void FormTaskMgr::PostHostDiedTask(const sptr &remoteHost) APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); return; } - std::function postTaskFunc = std::bind ( - &FormTaskMgr::HostDied, - this, - remoteHost); - eventHandler_->PostTask(postTaskFunc); + std::function postTaskFunc = std::bind(&FormTaskMgr::HostDied, + this, remoteHost); + eventHandler_->PostTask(postTaskFunc, FORM_TASK_DELAY_TIME); } /** @@ -202,20 +178,15 @@ void FormTaskMgr::PostHostDiedTask(const sptr &remoteHost) * @return none. */ void FormTaskMgr::PostEventNotifyTask(const std::vector &formEvent, const int32_t formVisibleType, -const Want &want, const sptr &remoteObject) + const Want &want, const sptr &remoteObject) { if (eventHandler_ == nullptr) { APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); return; } - std::function eventNotifyFunc = std::bind ( - &FormTaskMgr::EventNotify, - this, - formEvent, - formVisibleType, - want, - remoteObject); - eventHandler_->PostTask(eventNotifyFunc); + std::function eventNotifyFunc = std::bind(&FormTaskMgr::EventNotify, + this, formEvent, formVisibleType, want, remoteObject); + eventHandler_->PostTask(eventNotifyFunc, FORM_TASK_DELAY_TIME); } /** * @brief Post provider batch delete. @@ -224,19 +195,15 @@ const Want &want, const sptr &remoteObject) * @param remoteObject Form provider proxy object. */ void FormTaskMgr::PostProviderBatchDeleteTask(std::set &formIds, const Want &want, -const sptr &remoteObject) + const sptr &remoteObject) { if (eventHandler_ == nullptr) { APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); return; } - std::function batchDeleteFunc = std::bind ( - &FormTaskMgr::ProviderBatchDelete, - this, - formIds, - want, - remoteObject); - eventHandler_->PostTask(batchDeleteFunc); + std::function batchDeleteFunc = std::bind(&FormTaskMgr::ProviderBatchDelete, + this, formIds, want, remoteObject); + eventHandler_->PostTask(batchDeleteFunc, FORM_TASK_DELAY_TIME); } /** * @brief Post message event to form provider. @@ -245,21 +212,16 @@ const sptr &remoteObject) * @param want The want of the request. * @param remoteObject Form provider proxy object. */ -void FormTaskMgr::PostFormEventTask(const int64_t formId, const std::string &message, const Want &want, -const sptr &remoteObject) +void FormTaskMgr::PostFormEventTask(const int64_t formId, const std::string &message, + const Want &want, const sptr &remoteObject) { if (eventHandler_ == nullptr) { APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); return; } - std::function formEventFunc = std::bind ( - &FormTaskMgr::FireFormEvent, - this, - formId, - message, - want, - remoteObject); - eventHandler_->PostTask(formEventFunc); + std::function formEventFunc = std::bind(&FormTaskMgr::FireFormEvent, + this, formId, message, want, remoteObject); + eventHandler_->PostTask(formEventFunc, FORM_TASK_DELAY_TIME); } /** @@ -274,12 +236,9 @@ void FormTaskMgr::PostUninstallTaskToHost(const std::vector &formIds, c APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); return; } - std::function uninstallFunc = std::bind ( - &FormTaskMgr::FormUninstall, - this, - formIds, - remoteObject); - eventHandler_->PostTask(uninstallFunc); + std::function uninstallFunc = std::bind(&FormTaskMgr::FormUninstall, + this, formIds, remoteObject); + eventHandler_->PostTask(uninstallFunc, FORM_TASK_DELAY_TIME); APP_LOGI("%{public}s end", __func__); } @@ -290,20 +249,9 @@ void FormTaskMgr::PostUninstallTaskToHost(const std::vector &formIds, c * @param remoteObject Form provider proxy object. */ void FormTaskMgr::AcquireProviderFormInfo(const int64_t formId, const Want &want, -const sptr &remoteObject) + const sptr &remoteObject) { - long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); - sptr formProviderProxy = iface_cast(remoteObject); - if (formProviderProxy == nullptr) { - FormSupplyCallback::GetInstance()->RemoveConnection(connectId); - APP_LOGE("%{public}s fail, Failed to get formProviderProxy", __func__); - return; - } - int error = formProviderProxy->AcquireProviderFormInfo(formId, want, FormSupplyCallback::GetInstance()); - if (error != ERR_OK) { - FormSupplyCallback::GetInstance()->RemoveConnection(connectId); - APP_LOGE("%{public}s fail, Failed to get acquire provider form info", __func__); - } + FormMgrAdapter::GetInstance().AcquireProviderFormInfo(formId, want, remoteObject); } /** @@ -316,18 +264,7 @@ const sptr &remoteObject) */ void FormTaskMgr::NotifyFormDelete(const int64_t formId, const Want &want, const sptr &remoteObject) { - long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); - sptr formProviderProxy = iface_cast(remoteObject); - if (formProviderProxy == nullptr) { - FormSupplyCallback::GetInstance()->RemoveConnection(connectId); - APP_LOGE("%{public}s fail, Failed to get formProviderProxy", __func__); - return; - } - int error = formProviderProxy->NotifyFormDelete(formId, want, FormSupplyCallback::GetInstance()); - if (error != ERR_OK) { - FormSupplyCallback::GetInstance()->RemoveConnection(connectId); - APP_LOGE("%{public}s fail, Failed to get acquire provider form info", __func__); - } + FormMgrAdapter::GetInstance().NotifyFormDelete(formId, want, remoteObject); } /** @@ -349,7 +286,6 @@ void FormTaskMgr::NotifyFormUpdate(const int64_t formId, const Want &want, const APP_LOGE("%{public}s fail, failed to get formProviderProxy", __func__); return; } - int error = formProviderProxy->NotifyFormUpdate(formId, want, FormSupplyCallback::GetInstance()); if (error != ERR_OK) { FormSupplyCallback::GetInstance()->RemoveConnection(connectId); @@ -366,8 +302,8 @@ void FormTaskMgr::NotifyFormUpdate(const int64_t formId, const Want &want, const * @param remoteObject The form provider proxy object. * @return none. */ -void FormTaskMgr::EventNotify(const std::vector &formEvents, const int32_t formVisibleType, const Want &want, -const sptr &remoteObject) +void FormTaskMgr::EventNotify(const std::vector &formEvents, const int32_t formVisibleType, + const Want &want, const sptr &remoteObject) { APP_LOGI("%{public}s called.", __func__); @@ -422,7 +358,7 @@ void FormTaskMgr::NotifyCastTemp(const int64_t formId, const Want &want, const s * @param remoteObject Form provider proxx object. */ void FormTaskMgr::AcquireTaskToHost(const int64_t formId, const FormRecord &record, -const sptr &remoteObject) + const sptr &remoteObject) { APP_LOGI("FormTaskMgr AcquireTaskToHost, formId:%{public}" PRId64 "", formId); @@ -445,7 +381,7 @@ const sptr &remoteObject) * @param remoteObject Form provider proxx object. */ void FormTaskMgr::UpdateTaskToHost(const int64_t formId, const FormRecord &record, -const sptr &remoteObject) + const sptr &remoteObject) { APP_LOGI("%{public}s start.", __func__); @@ -481,7 +417,7 @@ void FormTaskMgr::HostDied(const sptr &remoteHost) * @param remoteObject Form provider proxy object. */ void FormTaskMgr::ProviderBatchDelete(std::set &formIds, const Want &want, -const sptr &remoteObject) + const sptr &remoteObject) { APP_LOGI("%{public}s called.", __func__); long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); @@ -563,9 +499,9 @@ FormJsInfo FormTaskMgr::CreateFormJsInfo(const int64_t formId, const FormRecord form.formTempFlg = record.formTempFlg; form.jsFormCodePath = record.jsFormCodePath; form.formData = record.formProviderInfo.GetFormDataString(); - form.formProviderData = record.formProviderInfo.GetFormData(); - APP_LOGI("%{public}s end, jsPath: %{public}s, data: %{public}s", __func__, form.jsFormCodePath.c_str(), form.formData.c_str()); + APP_LOGI("%{public}s end, jsPath: %{public}s, data: %{public}s", __func__, + form.jsFormCodePath.c_str(), form.formData.c_str()); return form; } } // namespace AppExecFwk diff --git a/services/formmgr/src/form_timer_mgr.cpp b/services/formmgr/src/form_timer_mgr.cpp index 9d13f7c2e140a663947b27193fef855a98b1d4ea..886cef74cc4f0a5dc65a47ca46c3e5052316a599 100644 --- a/services/formmgr/src/form_timer_mgr.cpp +++ b/services/formmgr/src/form_timer_mgr.cpp @@ -14,7 +14,7 @@ */ #include - +#include "ability_context.h" #include "appexecfwk_errors.h" #include "app_log_wrapper.h" #include "common_event_manager.h" @@ -22,12 +22,14 @@ #include "form_constants.h" #include "form_provider_mgr.h" #include "form_refresh_limiter.h" +#include "form_timer_option.h" #include "form_timer_mgr.h" #include "form_util.h" #include "want.h" namespace OHOS { namespace AppExecFwk { + FormTimerMgr::FormTimerMgr() { Init(); @@ -46,7 +48,7 @@ bool FormTimerMgr::AddFormTimer(const FormTimer &task) APP_LOGI("%{public}s, formId: %{public}" PRId64 "", __func__, task.formId); if (task.isUpdateAt) { if (task.hour >= Constants::MIN_TIME && task.hour <= Constants::MAX_HOUR && task.min >= Constants::MIN_TIME && - task.min <= Constants::MAX_MININUTE) { + task.min <= Constants::MAX_MININUTE) { return AddUpdateAtTimer(task); } else { APP_LOGE("%{public}s failed, update at time is invalid", __func__); @@ -54,7 +56,7 @@ bool FormTimerMgr::AddFormTimer(const FormTimer &task) } } else { if (task.period >= Constants::MIN_PERIOD && task.period <= Constants::MAX_PERIOD && - (task.period % Constants::MIN_PERIOD) == 0) { + (task.period % Constants::MIN_PERIOD) == 0) { return AddIntervalTimer(task); } else { APP_LOGE("%{public}s failed, interval time is invalid", __func__); @@ -95,10 +97,16 @@ bool FormTimerMgr::RemoveFormTimer(const int64_t formId) APP_LOGI("%{public}s, task: %{public}" PRId64 "", __func__, formId); if (!DeleteIntervalTimer(formId)) { - DeleteUpdateAtTimer(formId); + if (!DeleteUpdateAtTimer(formId)) { + APP_LOGE("%{public}s, failed to DeleteUpdateAtTimer", __func__); + return false; + } } - DeleteDynamicItem(formId); + if (!DeleteDynamicItem(formId)) { + APP_LOGE("%{public}s, failed to DeleteDynamicItem", __func__); + return false; + } refreshLimiter_.DeleteItem(formId); return true; @@ -195,7 +203,10 @@ bool FormTimerMgr::UpdateAtTimerValue(const int64_t formId, const FormTimerCfg & AddUpdateAtItem(changedItem); } - UpdateAtTimerAlarm(); + if (!UpdateAtTimerAlarm()) { + APP_LOGE("%{public}s, failed to update attimer alarm.", __func__); + return false; + } return true; } /** @@ -259,7 +270,10 @@ bool FormTimerMgr::AtTimerToIntervalTimer(const int64_t formId, const FormTimerC } } - UpdateAtTimerAlarm(); + if (!UpdateAtTimerAlarm()) { + APP_LOGE("%{public}s, failed to update attimer alarm.", __func__); + return false; + } if (targetItem.refreshTask.formId == 0) { APP_LOGE("%{public}s failed, the update at timer is not exist", __func__); @@ -386,7 +400,7 @@ bool FormTimerMgr::AddUpdateAtTimer(const FormTimer &task) } if (!UpdateAtTimerAlarm()) { - APP_LOGE("%{public}s, failed to update alarm.", __func__); + APP_LOGE("%{public}s, failed to update attimer alarm.", __func__); return false; } @@ -409,7 +423,10 @@ bool FormTimerMgr::AddIntervalTimer(const FormTimer &task) } intervalTimerTasks_.emplace(task.formId, task); } - UpdateLimiterAlarm(); + if(!UpdateLimiterAlarm()) { + APP_LOGE("%{public}s, failed to UpdateLimiterAlarm", __func__); + return false; + } return refreshLimiter_.AddItem(task.formId); } /** @@ -445,19 +462,23 @@ void FormTimerMgr::AddUpdateAtItem(const UpdateAtItem &atItem) } /** * @brief Handle system time changed. + * @return Returns true on success, false on failure. */ -void FormTimerMgr::HandleSystemTimeChanged() +bool FormTimerMgr::HandleSystemTimeChanged() { APP_LOGI("%{public}s start", __func__); if (!updateAtTimerTasks_.empty()) { - UpdateAtTimerAlarm(); + return UpdateAtTimerAlarm(); } + APP_LOGI("%{public}s end", __func__); + return true; } /** * @brief Reset form limiter. + * @return Returns true on success, false on failure. */ -void FormTimerMgr::HandleResetLimiter() +bool FormTimerMgr::HandleResetLimiter() { APP_LOGI("%{public}s start", __func__); @@ -469,13 +490,16 @@ void FormTimerMgr::HandleResetLimiter() ExecTimerTask(task); } } + APP_LOGI("%{public}s end", __func__); + return true; } /** * @brief Update attime trigger. * @param updateTime Update time. + * @return Returns true on success, false on failure. */ -void FormTimerMgr::OnUpdateAtTrigger(long updateTime) +bool FormTimerMgr::OnUpdateAtTrigger(long updateTime) { APP_LOGI("%{public}s start, updateTime:%{public}ld", __func__, updateTime); std::vector updateList; @@ -489,7 +513,10 @@ void FormTimerMgr::OnUpdateAtTrigger(long updateTime) } } - UpdateAtTimerAlarm(); + if (!UpdateAtTimerAlarm()) { + APP_LOGE("%{public}s, failed to update attimer alarm.", __func__); + return false; + } if (!updateList.empty()) { APP_LOGI("%{public}s, update at timer triggered, trigged time: %{public}ld", __func__, updateTime); @@ -497,13 +524,16 @@ void FormTimerMgr::OnUpdateAtTrigger(long updateTime) ExecTimerTask(item.refreshTask); } } + APP_LOGI("%{public}s end", __func__); + return true; } /** * @brief Dynamic time trigger. * @param updateTime Update time. + * @return Returns true on success, false on failure. */ -void FormTimerMgr::OnDynamicTimeTrigger(long updateTime) +bool FormTimerMgr::OnDynamicTimeTrigger(long updateTime) { APP_LOGI("%{public}s start, updateTime:%{public}ld", __func__, updateTime); std::vector updateList; @@ -528,14 +558,20 @@ void FormTimerMgr::OnDynamicTimeTrigger(long updateTime) std::sort(dynamicRefreshTasks_.begin(), dynamicRefreshTasks_.end(), CompareDynamicRefreshItem); } - UpdateDynamicAlarm(); + if (!UpdateDynamicAlarm()) { + APP_LOGE("%{public}s, failed to update dynamic alarm.", __func__); + return false; + } + if (!updateList.empty()) { APP_LOGI("%{public}s triggered, trigged time: %{public}ld", __func__, updateTime); for (auto &task : updateList) { ExecTimerTask(task); } } + APP_LOGI("%{public}s end", __func__); + return true; } /** * @brief Get remind tasks. @@ -551,14 +587,18 @@ bool FormTimerMgr::GetRemindTasks(std::vector &remindTasks) remindTasks.emplace_back(formTimer); } - UpdateLimiterAlarm(); + if(!UpdateLimiterAlarm()) { + APP_LOGE("%{public}s, failed to UpdateLimiterAlarm", __func__); + return false; + } if(remindTasks.size() > 0) { + APP_LOGI("%{public}s end", __func__); return true; } else { + APP_LOGI("%{public}s end, remindTasks is empty", __func__); return false; } - APP_LOGI("%{public}s end", __func__); } /** * @brief Set enableFlag for interval timer task. @@ -601,8 +641,9 @@ bool FormTimerMgr::DeleteIntervalTimer(const int64_t formId) /** * @brief Delete update at timer. * @param formId The Id of the form. + * @return Returns true on success, false on failure. */ -void FormTimerMgr::DeleteUpdateAtTimer(const int64_t formId) +bool FormTimerMgr::DeleteUpdateAtTimer(const int64_t formId) { APP_LOGI("%{public}s start", __func__); { @@ -616,15 +657,18 @@ void FormTimerMgr::DeleteUpdateAtTimer(const int64_t formId) } } - UpdateAtTimerAlarm(); - + if (!UpdateAtTimerAlarm()) { + APP_LOGE("%{public}s, failed to update attimer alarm.", __func__); + return false; + } + return true; APP_LOGI("%{public}s end", __func__); } /** * @brief Delete dynamic refresh item. * @param formId The Id of the form. */ -void FormTimerMgr::DeleteDynamicItem(const int64_t formId) +bool FormTimerMgr::DeleteDynamicItem(const int64_t formId) { APP_LOGI("%{public}s start", __func__); std::lock_guard lock(dynamicMutex_); @@ -637,8 +681,12 @@ void FormTimerMgr::DeleteDynamicItem(const int64_t formId) } } std::sort(dynamicRefreshTasks_.begin(), dynamicRefreshTasks_.end(), CompareDynamicRefreshItem); - - UpdateDynamicAlarm(); + + if (!UpdateDynamicAlarm()) { + APP_LOGE("%{public}s, failed to UpdateDynamicAlarm", __func__); + return false; + } + return true; APP_LOGI("%{public}s end", __func__); } /** @@ -667,6 +715,7 @@ void FormTimerMgr::OnIntervalTimeOut() } APP_LOGI("%{public}s end", __func__); } + /** * @brief Update at timer task alarm. * @return Returns true on success, false on failure. @@ -674,92 +723,41 @@ void FormTimerMgr::OnIntervalTimeOut() bool FormTimerMgr::UpdateAtTimerAlarm() { APP_LOGI("%{public}s start", __func__); - // AlarmManager* alarm = GetAlarmManagerLocked(); - // if (alarm == nullptr) { - // APP_LOGE("%{public}s failed, failed to get alarm manager, can not updateAlarm", __func__); - // return false; - // } - struct tm tmAtTime = {0}; - auto tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); - struct tm* ptm = localtime_r(&tt, &tmAtTime); - if (ptm == nullptr) { - APP_LOGE("%{public}s failed, localtime error", __func__); - return false; - } - int nowAtTime = tmAtTime.tm_hour * Constants::MIN_PER_HOUR + tmAtTime.tm_min; - long currentTime = FormUtil::GetCurrentMillisecond(); - UpdateAtItem findedItem; - bool bFinded = FindNextAtTimerItem(nowAtTime, findedItem); - if (!bFinded) { - ClearUpdateAtTimerResource(); - APP_LOGI("%{public}s, no update at task in system now.", __func__); - return true; - } + APP_LOGI("%{public}s end", __func__); + return true; +} - int nextWakeUpTime = findedItem.updateAtTime; - tmAtTime.tm_sec = 0; - tmAtTime.tm_hour = findedItem.refreshTask.hour; - tmAtTime.tm_min = findedItem.refreshTask.min; - long selectTime = FormUtil::GetMillisecondFromTm(tmAtTime); - if (selectTime < currentTime) { - tmAtTime.tm_mday += 1; - nextWakeUpTime += (Constants::HOUR_PER_DAY * Constants::MIN_PER_HOUR); - } - if (nextWakeUpTime == atTimerWakeUpTime_) { - APP_LOGW("%{public}s end, wakeUpTime not change, no need update alarm.", __func__); - return true; - } - - // PendingIntent pendingIntent = getPendingIntent(findedItem.updateAtTime); - // if (pendingIntent == null) { - // HiLog.error(LABEL_LOG, "create pendingIntent failed."); - // return false; - // } - atTimerWakeUpTime_ = nextWakeUpTime; - // if (currentPendingIntent != null) { - // alarm.cancel(currentPendingIntent); - // } - // currentPendingIntent = pendingIntent; - // alarm.setExact(AlarmManager.RTC_WAKEUP, FormUtil::GetMillisecondFromTm(tmAtTime), pendingIntent); +/** + * @brief Clear update at timer resource. + */ +void FormTimerMgr::ClearUpdateAtTimerResource() +{ + APP_LOGI("%{public}s start", __func__); APP_LOGI("%{public}s end", __func__); - return true; } + /** * @brief Update limiter task alarm. * @return Returns true on success, false on failure. */ bool FormTimerMgr::UpdateLimiterAlarm() +{ + APP_LOGI("%{public}s start", __func__); + + return true; +} +/** + * @brief Clear limiter timer resource. + */ +void FormTimerMgr::ClearLimiterTimerResource() { APP_LOGI("%{public}s start", __func__); - // AlarmManager alarm = getAlarmManagerLocked(); - // if (alarm == null) { - // HiLog.error(LABEL_LOG, "faied to get alarm manager, can not updateLimiterAlarm"); - // return false; - // } - - // PendingIntent pendingIntent = getLimiterPendingIntent(); - // if (pendingIntent == null) { - // HiLog.error(LABEL_LOG, "create limiterPendingIntent failed."); - // return false; - // } - - // if (limiterPendingIntent != null) { - // alarm.cancel(limiterPendingIntent); - // } - // limiterPendingIntent = pendingIntent; - - // Calendar calendar = Calendar.getInstance(); - // calendar.set(Calendar.DATE, Calendar.getInstance().get(Calendar.DATE)); - // calendar.set(Calendar.HOUR_OF_DAY, MAX_HOUR); - // calendar.set(Calendar.MINUTE, MAX_MININUTE); - // calendar.set(Calendar.SECOND, MAX_SECOND); - // calendar.set(Calendar.MILLISECOND, LIMIT_MS); - // alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); APP_LOGI("%{public}s end", __func__); - return true; } + + /** * @brief Update dynamic refresh task alarm. * @return Returns true on success, false on failure. @@ -767,59 +765,18 @@ bool FormTimerMgr::UpdateLimiterAlarm() bool FormTimerMgr::UpdateDynamicAlarm() { APP_LOGI("%{public}s start", __func__); - if (dynamicRefreshTasks_.empty()) { - ClearDynamicResource(); - return true; - } - - bool needUpdate = false; - DynamicRefreshItem firstTask = dynamicRefreshTasks_.at(0); - if (dynamicWakeUpTime_ != firstTask.settedTime) { - dynamicWakeUpTime_ = firstTask.settedTime; - needUpdate = true; - } - - if (!needUpdate) { - APP_LOGE("%{public}s failed, no need to UpdateDynamicAlarm.", __func__); - return true; - } - // AlarmManager alarm = getAlarmManagerLocked(); - // if (alarm == null) { - // HiLog.error(LABEL_LOG, "faied to get alarm manager, can not UpdateDynamicAlarm."); - // return false; - // } - - // PendingIntent pendingIntent = getDynamicPendingIntent(dynamicWakeUpTime); - // if (pendingIntent == null) { - // HiLog.error(LABEL_LOG, "create dynamic pendingIntent failed.", __func__); - // return false; - // } - // if (dynamicPendingIntent != null) { - // alarm.cancel(dynamicPendingIntent); - // } - // dynamicPendingIntent = pendingIntent; - // alarm.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, dynamicWakeUpTime, pendingIntent); APP_LOGI("%{public}s end", __func__); return true; } + /** * @brief Clear dynamic refresh resource. */ void FormTimerMgr::ClearDynamicResource() { APP_LOGI("%{public}s start", __func__); - // AlarmManager alarm = getAlarmManagerLocked(); - // if (alarm == null) { - // return; - // } - - // if (dynamicPendingIntent != null) { - // alarm.cancel(dynamicPendingIntent); - // dynamicPendingIntent = null; - // } - dynamicWakeUpTime_ = LONG_MAX; APP_LOGI("%{public}s end", __func__); } /** @@ -851,49 +808,17 @@ bool FormTimerMgr::FindNextAtTimerItem(const int nowTime, UpdateAtItem &updateAt APP_LOGI("%{public}s end", __func__); return true; } -/** - * @brief Clear update at timer resource. - */ -void FormTimerMgr::ClearUpdateAtTimerResource() -{ - APP_LOGI("%{public}s start", __func__); - if (!updateAtTimerTasks_.empty()) { - APP_LOGW("%{public}s, updateAtTimerTasks_ is not empty", __func__); - return; - } - - // AlarmManager alarm = getAlarmManagerLocked(); - // if (alarm == null) { - // return; - // } - - // if (currentPendingIntent != null) { - // alarm.cancel(currentPendingIntent); - // currentPendingIntent = null; - // } - atTimerWakeUpTime_ = LONG_MAX; - APP_LOGI("%{public}s end", __func__); -} /** * @brief Ensure init interval timer resource. */ void FormTimerMgr::EnsureInitIntervalTimer() { - if (intervalTimer_ != NULL) { + if (intervalTimerId_ != 0L) { return; } APP_LOGI("%{public}s, init base timer task", __func__); - intervalTimer_ = new Utils::Timer("interval timer"); - uint32_t iResult = intervalTimer_->Setup(); - if (iResult != ERR_OK) { - APP_LOGE("%{public}s failed, init base timer task error", __func__); - return; - } - auto timeCallback = std::bind(&FormTimerMgr::OnIntervalTimeOut, this); - intervalTimer_->Register(timeCallback, Constants::MIN_PERIOD); - APP_LOGI("%{public}s end", __func__); } /** @@ -902,13 +827,6 @@ void FormTimerMgr::EnsureInitIntervalTimer() void FormTimerMgr::ClearIntervalTimer() { APP_LOGI("%{public}s start", __func__); - if (intervalTimer_ != nullptr) { - APP_LOGI("%{public}s clear interval timer start", __func__); - intervalTimer_->Shutdown(); - delete intervalTimer_; - intervalTimer_ = nullptr; - APP_LOGI("%{public}s clear interval timer end", __func__); - } APP_LOGI("%{public}s end", __func__); } /** @@ -963,7 +881,10 @@ void FormTimerMgr::Init() timerReceiver_ = std::make_shared(subscribeInfo); EventFwk::CommonEventManager::SubscribeCommonEvent(timerReceiver_); - intervalTimer_ = nullptr; + intervalTimerId_ = 0L; + updateAtTimerId_ = 0L; + dynamicAlarmTimerId_ = 0L; + limiterTimerId_ = 0L; taskExecutor_ = nullptr; APP_LOGI("%{public}s end", __func__); diff --git a/services/formmgr/src/form_util.cpp b/services/formmgr/src/form_util.cpp index a4d3d30f76fa9811c8bc6d0c189e7d5bec4806bf..d033818a1bf2addffede4129143fa14cfb905b98 100644 --- a/services/formmgr/src/form_util.cpp +++ b/services/formmgr/src/form_util.cpp @@ -1,203 +1,191 @@ -/* - * 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 -#include -#include -// #include - -#include "app_log_wrapper.h" -#include "form_constants.h" -#include "form_util.h" -#include "ohos_account_kits.h" - -namespace OHOS { -namespace AppExecFwk { -using namespace std; -using namespace std::chrono; - -constexpr int64_t SEC_TO_NANOSEC = 1000000000; -constexpr int64_t SEC_TO_MILLISEC = 1000; -constexpr int64_t MILLISEC_TO_NANOSEC = 1000000; -constexpr int64_t INVALID_UDID_HASH = 0; -/** - * @brief create want for form. - * @param formName The name of the form. - * @param specificationId specification id. - * @param isTemporaryForm temporary form or not. - * @param want The want of the form. - */ -void FormUtil::CreateFormWant(const std::string &formName, const int32_t specificationId, const bool isTemporaryForm, -Want &want) -{ - want.SetParam(Constants::PARAM_FORM_NAME_KEY, formName); - want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, specificationId); - want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, isTemporaryForm); -} - -/** - * @brief create default want for form. - * @param want The want of the form.. - * @param uri The uri. - * @param connectId connect id. - */ -void FormUtil::CreateDefaultFormWant(Want &want, const std::string &uri, const int32_t connectId) -{ - want.SetParam(Constants::FORM_CONNECT_ID, connectId); - want.SetParam(Constants::FORM_SUPPLY_INFO, uri); -} - -/** - * @brief create udid for form. - * @return udid. - */ -std::string FormUtil::GenerateUdid() -{ - // uuid_t uuid; - char buf[256] = {0}; - // uuid_generate(uuid); - - // uuid_unparse(uuid, buf); - return buf; -} - -/** - * @brief create form id for form. - * @param udidHash udid hash - * @return new form id. - */ -int64_t FormUtil::GenerateFormId(int64_t udidHash) -{ - struct timespec t; - t.tv_sec = 0; - t.tv_nsec = 0; - clock_gettime(CLOCK_REALTIME, &t); - - int64_t elapsedTime { ((t.tv_sec) * SEC_TO_NANOSEC + t.tv_nsec) }; - size_t elapsedHash = std::hash()(std::to_string(elapsedTime)); - APP_LOGI("%{public}s, GenerateFormId generate elapsed hash %{public}zu", __func__, elapsedHash); - int64_t formId = udidHash | (int32_t)(elapsedHash & 0x000000007fffffffL); - APP_LOGI("%{public}s, GenerateFormId generate formId %{public}" PRId64 "", __func__, formId); - return formId; -} - -/** - * @brief padding form id. - * @param formId The id of the form. - * @param udidHash udid hash - * @return new form id. - */ -int64_t FormUtil::PaddingUDIDHash(int64_t formId, int64_t udidHash) -{ - // Compatible with int form id. - if ((formId & 0xffffffff00000000L) == 0) { - return udidHash | formId; - } - - return formId; -} -/** - * @brief create udid hash. - * @param udidHash udid hash. - * @return Returns true on success, false on failure. - */ -bool FormUtil::GenerateUdidHash(int64_t &udidHash) -{ - APP_LOGI("%{public}s start, udidHash: %{public}" PRId64 "", __func__, udidHash); - if (udidHash != INVALID_UDID_HASH) { - return true; - } - - // std::string deviceId = GenerateUdid(); - // if (deviceId.empty()) { - // APP_LOGE("%{public}s fail, get udid failed.", __func__); - // return false; - // } - - // u_int64_t hashId = std::hash()(deviceId); - u_int64_t hashId = 0L; - const int32_t thirtyTwo = 32; - udidHash = (hashId & 0x0000000000ffffffL) << thirtyTwo; - if(udidHash < 0) { - udidHash = 0L; - } - APP_LOGI("%{public}s, FormAdapter generate hash %{public}" PRId64 "", __func__, udidHash); - - return true; -} -/** - * @brief Get current system nanosecond. - * @return Current system nanosecond. - */ -long FormUtil::GetCurrentNanosecond() -{ - struct timespec ts; - ts.tv_sec = 0; - ts.tv_nsec = 0; - clock_gettime(CLOCK_REALTIME, &ts); - return (ts.tv_sec * SEC_TO_NANOSEC + ts.tv_nsec); -} -/** - * @brief Get current system millisecond. - * @return Current system millisecond. - */ -long FormUtil::GetCurrentMillisecond() -{ - struct timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - return (ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC); -} -/** - * @brief Get millisecond from tm. - * @param tmAtTime tm time. - * @return Millisecond. - */ -long FormUtil::GetMillisecondFromTm(struct tm &tmAtTime) -{ - time_t inputTime = mktime(&tmAtTime); - if (inputTime == -1) { - APP_LOGE("%{public}s fail, mktime failed.", __func__); - return -1; - } - system_clock::time_point pointTime = system_clock::from_time_t(inputTime); - auto timeMilliseconds = chrono::duration_cast(pointTime.time_since_epoch()); - return timeMilliseconds.count(); -} - -/** -* @brief split string. - * @param in string. - * @param delim delimiter. - * @return string list. - */ -std::vector FormUtil::StringSplit(const std::string &in, const std::string &delim) -{ - std::vector vEmpty; - try { - std::regex reg { delim }; - return std::vector { - std::sregex_token_iterator(in.begin(), in.end(), reg, -1), - std::sregex_token_iterator() - }; - } catch (const std::exception& e) { - APP_LOGE("%{public}s, failed to split string.", __func__); - } - return vEmpty; -} -} // namespace AppExecFwk +/* + * 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 +#include + +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_util.h" +#include "ohos_account_kits.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace std; +using namespace std::chrono; + +constexpr int64_t SEC_TO_NANOSEC = 1000000000; +constexpr int64_t SEC_TO_MILLISEC = 1000; +constexpr int64_t MILLISEC_TO_NANOSEC = 1000000; +constexpr int64_t INVALID_UDID_HASH = 0; +/** + * @brief create want for form. + * @param formName The name of the form. + * @param specificationId specification id. + * @param isTemporaryForm temporary form or not. + * @param want The want of the form. + */ +void FormUtil::CreateFormWant(const std::string &formName, + const int32_t specificationId, const bool isTemporaryForm, Want &want) +{ + want.SetParam(Constants::PARAM_FORM_NAME_KEY, formName); + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, specificationId); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, isTemporaryForm); +} + +/** + * @brief create default want for form. + * @param want The want of the form.. + * @param uri The uri. + * @param connectId connect id. + */ +void FormUtil::CreateDefaultFormWant(Want &want, const std::string &uri, const int32_t connectId) +{ + want.SetParam(Constants::FORM_CONNECT_ID, connectId); + want.SetParam(Constants::FORM_SUPPLY_INFO, uri); +} + +/** + * @brief create udid for form. + * @return udid. + */ +std::string FormUtil::GenerateUdid() +{ + char buf[256] = {0}; + return buf; +} + +/** + * @brief create form id for form. + * @param udidHash udid hash + * @return new form id. + */ +int64_t FormUtil::GenerateFormId(int64_t udidHash) +{ + struct timespec t; + t.tv_sec = 0; + t.tv_nsec = 0; + clock_gettime(CLOCK_REALTIME, &t); + + int64_t elapsedTime { ((t.tv_sec) * SEC_TO_NANOSEC + t.tv_nsec) }; + size_t elapsedHash = std::hash()(std::to_string(elapsedTime)); + APP_LOGI("%{public}s, GenerateFormId generate elapsed hash %{public}zu", __func__, elapsedHash); + uint64_t unsignedudidHash = static_cast(udidHash); + uint64_t formId = unsignedudidHash | (int32_t)(elapsedHash & 0x000000007fffffffL); + APP_LOGI("%{public}s, GenerateFormId generate formId %{public}" PRId64 "", __func__, formId); + return formId; +} + +/** + * @brief padding form id. + * @param formId The id of the form. + * @param udidHash udid hash + * @return new form id. + */ +int64_t FormUtil::PaddingUDIDHash(uint64_t formId, uint64_t udidHash) +{ + // Compatible with int form id. + if ((formId & 0xffffffff00000000L) == 0) { + return udidHash | formId; + } + + return formId; +} +/** + * @brief create udid hash. + * @param udidHash udid hash. + * @return Returns true on success, false on failure. + */ +bool FormUtil::GenerateUdidHash(int64_t &udidHash) +{ + APP_LOGI("%{public}s start, udidHash: %{public}" PRId64 "", __func__, udidHash); + if (udidHash != INVALID_UDID_HASH) { + return true; + } + + u_int64_t hashId = 0L; + const int32_t thirtyTwo = 32; + udidHash = (hashId & 0x0000000000ffffffL) << thirtyTwo; + if (udidHash < 0) { + udidHash = 0L; + } + APP_LOGI("%{public}s, FormAdapter generate hash %{public}" PRId64 "", __func__, udidHash); + + return true; +} +/** + * @brief Get current system nanosecond. + * @return Current system nanosecond. + */ +long FormUtil::GetCurrentNanosecond() +{ + struct timespec ts; + ts.tv_sec = 0; + ts.tv_nsec = 0; + clock_gettime(CLOCK_REALTIME, &ts); + return (ts.tv_sec * SEC_TO_NANOSEC + ts.tv_nsec); +} +/** + * @brief Get current system millisecond. + * @return Current system millisecond. + */ +long FormUtil::GetCurrentMillisecond() +{ + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + return (ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC); +} +/** + * @brief Get millisecond from tm. + * @param tmAtTime tm time. + * @return Millisecond. + */ +long FormUtil::GetMillisecondFromTm(struct tm &tmAtTime) +{ + time_t inputTime = mktime(&tmAtTime); + if (inputTime == -1) { + APP_LOGE("%{public}s fail, mktime failed.", __func__); + return -1; + } + system_clock::time_point pointTime = system_clock::from_time_t(inputTime); + auto timeMilliseconds = chrono::duration_cast(pointTime.time_since_epoch()); + return timeMilliseconds.count(); +} + +/** +* @brief split string. + * @param in string. + * @param delim delimiter. + * @return string list. + */ +std::vector FormUtil::StringSplit(const std::string &in, const std::string &delim) +{ + std::vector vEmpty; + try { + std::regex reg { delim }; + return std::vector { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), + std::sregex_token_iterator() + }; + } catch (const std::exception& e) { + APP_LOGE("%{public}s, failed to split string.", __func__); + } + return vEmpty; +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/test/BUILD.gn b/services/formmgr/test/BUILD.gn index ffbcd46101e85956762e903ab73d4e2aaaa1602c..5ab060b4507e3cd058f90ba026214edd74486efa 100644 --- a/services/formmgr/test/BUILD.gn +++ b/services/formmgr/test/BUILD.gn @@ -48,6 +48,7 @@ group("unittest") { "unittest/fms_form_host_record_test:unittest", "unittest/fms_form_mgr_add_form_test:unittest", "unittest/fms_form_mgr_cast_temp_form_test:unittest", + "unittest/fms_form_mgr_death_callback_test:unittest", "unittest/fms_form_mgr_delete_form_test:unittest", "unittest/fms_form_mgr_lifecycle_update_test:unittest", "unittest/fms_form_mgr_message_event_test:unittest", diff --git a/services/formmgr/test/mock/include/mock_form_death_callback.h b/services/formmgr/test/mock/include/mock_form_death_callback.h index 2563698580783f0e12d037f88958f0e071577f2e..55bc225a85dfd9c4938b22da6797fb077fcb84cd 100644 --- a/services/formmgr/test/mock/include/mock_form_death_callback.h +++ b/services/formmgr/test/mock/include/mock_form_death_callback.h @@ -26,7 +26,7 @@ #include "app_log_wrapper.h" #include "event_handler.h" #include "form_constants.h" -#include "form_death_callback.h" +#include "form_callback_interface.h" #include "form_mgr_stub.h" #include "form_js_info.h" #include "form_provider_data.h" @@ -39,7 +39,7 @@ namespace AppExecFwk { * @class MockFormDeathCallback. * The MockFormDeathCallback for form mgr test. */ -class MockFormDeathCallback : public FormDeathCallback { +class MockFormDeathCallback : public FormCallbackInterface { public: MockFormDeathCallback() = default; virtual ~MockFormDeathCallback() = default; @@ -49,7 +49,22 @@ public: APP_LOGI("%{public}s called.", __func__); } - void OnReconnectFailed() + /** + * @brief Update form. + * + * @param formJsInfo Indicates the obtained {@code FormJsInfo} instance. + */ + void ProcessFormUpdate(const FormJsInfo &formJsInfo) + { + APP_LOGI("%{public}s called.", __func__); + } + + /** + * @brief Uninstall form. + * + * @param formId Indicates the ID of the form to uninstall. + */ + void ProcessFormUninstall(const int64_t formId) { APP_LOGI("%{public}s called.", __func__); } diff --git a/services/formmgr/test/mock/src/mock_bundle_manager.cpp b/services/formmgr/test/mock/src/mock_bundle_manager.cpp index 4905e226128237654beeb5e4eac41b12840d4420..4555049f67ee15708c5c05b90ca54422afe80d5b 100644 --- a/services/formmgr/test/mock/src/mock_bundle_manager.cpp +++ b/services/formmgr/test/mock/src/mock_bundle_manager.cpp @@ -53,7 +53,7 @@ bool BundleMgrProxy::GetFormsInfoByApp(const std::string &bundleName, std::vecto return true; } bool BundleMgrProxy::GetFormsInfoByModule(const std::string &bundleName, const std::string &moduleName, -std::vector &formInfo) + std::vector &formInfo) { return true; } @@ -135,7 +135,7 @@ bool BundleMgrService::GetFormsInfoByApp(const std::string &bundleName, std::vec return true; } bool BundleMgrService::GetFormsInfoByModule(const std::string &bundleName, const std::string &moduleName, -std::vector &formInfo) + std::vector &formInfo) { FormInfo form; form.bundleName = bundleName; diff --git a/services/formmgr/test/mock/src/mock_form_host_client.cpp b/services/formmgr/test/mock/src/mock_form_host_client.cpp index ad90b9ad4c6e7a0874c391b33f68012696ce8153..92dd97e82e58d6eded8fee20138b2210fde30b46 100644 --- a/services/formmgr/test/mock/src/mock_form_host_client.cpp +++ b/services/formmgr/test/mock/src/mock_form_host_client.cpp @@ -1,76 +1,64 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include "appexecfwk_errors.h" -#include "app_log_wrapper.h" -#include "errors.h" -#include "mock_form_host_client.h" -#include "string_ex.h" - -namespace OHOS { -namespace AppExecFwk { -// void MockFormHostClient::AddForm(const Ability& slice, int64_t formId){ - -// } - -// void MockFormHostClient::RemoveForm(const Ability& slice, int64_t formId{ - -// } - -// bool MockFormHostClient::ContainsForm(int64_t formId){ -// return false; -// } - -/** - * Request to give back a Form. - * - * @param formInfo, Form info. - * @return none. - */ -void MockFormHostClient::OnAcquired(const FormJsInfo &formInfo) -{ - APP_LOGD("MockFormHostClient OnAcquired"); - - int64_t formId = formInfo.formId; - ASSERT_FALSE(formId == 0); - PostVoid(); -} - -/** -* Form is updated. -* -* @param bundleName, Provider ability bundleName. -* @return none. -*/ -void MockFormHostClient::OnUpdate(const FormJsInfo &formInfo) -{ - APP_LOGD("MockFormHostClient OnUpdate"); - PostVoid(); -} - - -/** - * Form provider is uninstalled - * - * @param formIds, The Id list of the forms. - * @return none. - */ -void MockFormHostClient::OnUninstall(const std::vector &formIds) -{ - APP_LOGD("MockFormHostClient OnUnInstall"); - PostVoid(); -} -} // namespace AppExecFwk -} // namespace OHOS +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "errors.h" +#include "mock_form_host_client.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { + +/** + * Request to give back a Form. + * + * @param formInfo, Form info. + * @return none. + */ +void MockFormHostClient::OnAcquired(const FormJsInfo &formInfo) +{ + APP_LOGD("MockFormHostClient OnAcquired"); + + int64_t formId = formInfo.formId; + ASSERT_FALSE(formId == 0); + PostVoid(); +} + +/** +* Form is updated. +* +* @param bundleName, Provider ability bundleName. +* @return none. +*/ +void MockFormHostClient::OnUpdate(const FormJsInfo &formInfo) +{ + APP_LOGD("MockFormHostClient OnUpdate"); + PostVoid(); +} + +/** + * Form provider is uninstalled + * + * @param formIds, The Id list of the forms. + * @return none. + */ +void MockFormHostClient::OnUninstall(const std::vector &formIds) +{ + APP_LOGD("MockFormHostClient OnUnInstall"); + PostVoid(); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/test/mock/src/mock_form_provider_client.cpp b/services/formmgr/test/mock/src/mock_form_provider_client.cpp index 2b94d46ec1df787e6f0f045ac58248443d70c401..ff1e3a499a2e7743c5cb8d634840378d32da3558 100644 --- a/services/formmgr/test/mock/src/mock_form_provider_client.cpp +++ b/services/formmgr/test/mock/src/mock_form_provider_client.cpp @@ -1,142 +1,134 @@ -/* - * 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 "app_log_wrapper.h" -#include "errors.h" -#include "form_constants.h" -#include "form_supply_interface.h" -#include "mock_form_provider_client.h" -#include "string_ex.h" - -namespace OHOS { -namespace AppExecFwk { -/** - * Acquire to give back an ProviderFormInfo. This is sync API. - * - * @param want, The want of the form to create. - * @param callerToken, Caller ability token. - * @return none. - */ -int MockFormProviderClient::AcquireProviderFormInfo(const int64_t formId, const Want &want, -const sptr &callerToken) -{ - // avoid the user modify the number in onCreate - - APP_LOGD("Acquire provider form info"); - - sptr formSupply = iface_cast(callerToken); - if (formSupply == nullptr) { - APP_LOGE("failed to get formSupplyProxy"); - } - // Want newWant; - // newWant.SetElement(want.GetElement()); - // long formId = want.GetLongParam(Constants::PARAM_FORM_IDENTITY_KEY, 0); - // APP_LOGD("AcquireProviderFormInfo, formId:%{public}ld", formId); - - // newWant.SetParam(Constants::PARAM_FORM_IDENTITY_KEY, formId); - - // int type = want.GetIntParam(Constants::ACQUIRE_TYPE, 0); - // newWant.SetParam(Constants::ACQUIRE_TYPE, type); - FormProviderInfo formProviderInfo; - formSupply->OnAcquire(formProviderInfo, want); - return ERR_OK; -} - -/** - * Notify provider when the form was deleted. - * - * @param formId, The Id of the form. - * @param callerToken, Caller ability token. - * @return none. - */ -int MockFormProviderClient::NotifyFormDelete(const int64_t formId, const Want &want, -const sptr &callerToken) -{ - APP_LOGD("Notify form delete"); - return ERR_OK; -} -/** - * Notify provider when the forms was deleted. - * - * @param formIds, The id list of forms. - * @param want Indicates the structure containing form info. - * @param callerToken, Caller ability token. - * @return none. - */ -int MockFormProviderClient::NotifyFormsDelete(const std::vector &formIds, const Want &want, -const sptr &callerToken) -{ - APP_LOGD("Notify forms delete"); - return ERR_OK; -} - -/** - * @brief Notify provider when the form need update. - * @param formId The Id of the form. - * @param want Indicates the structure containing form info. - * @param callerToken Caller ability token. - */ -int MockFormProviderClient::NotifyFormUpdate(const int64_t formId, const Want &want, -const sptr &callerToken) -{ - APP_LOGD("Notify form update"); - return ERR_OK; -} - -/** - * @brief Event notify when change the form visible. - * - * @param formEvents The vector of form ids. - * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. - * @param want Indicates the structure containing form info. - * @param callerToken Caller ability token. - * @return Returns ERR_OK on success, others on failure. - */ -int MockFormProviderClient::EventNotify(const std::vector &formIds, const int32_t formVisibleType, - const Want &want, const sptr &callerToken) -{ - APP_LOGD("Event notify"); - return ERR_OK; -} - -/** - * Notify provider when the temp form was cast to normal form. - * - * @param formId, The Id of the form to update. - * @param callerToken, Caller ability token. - * @return none. - */ -int MockFormProviderClient::NotifyFormCastTempForm(const int64_t formId, const Want &want, -const sptr &callerToken) -{ - APP_LOGD("Notify cast temp form"); - return ERR_OK; -} -/** - * @brief Fire message event to form provider. - * @param formId The Id of the from. - * @param message Event message. - * @param want The want of the request. - * @param callerToken Form provider proxy object. - * @return Returns ERR_OK on success, others on failure. - */ -int MockFormProviderClient::FireFormEvent(const int64_t formId, const std::string &message, const Want &want, -const sptr &callerToken) -{ - APP_LOGD("Fire form event"); - return ERR_OK; -} -} // namespace AppExecFwk -} // namespace OHOS +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "app_log_wrapper.h" +#include "errors.h" +#include "form_constants.h" +#include "form_supply_interface.h" +#include "mock_form_provider_client.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * Acquire to give back an ProviderFormInfo. This is sync API. + * + * @param want, The want of the form to create. + * @param callerToken, Caller ability token. + * @return none. + */ +int MockFormProviderClient::AcquireProviderFormInfo(const int64_t formId, const Want &want, + const sptr &callerToken) +{ + // avoid the user modify the number in onCreate + + APP_LOGD("Acquire provider form info"); + + sptr formSupply = iface_cast(callerToken); + if (formSupply == nullptr) { + APP_LOGE("failed to get formSupplyProxy"); + } + + FormProviderInfo formProviderInfo; + formSupply->OnAcquire(formProviderInfo, want); + return ERR_OK; +} + +/** + * Notify provider when the form was deleted. + * + * @param formId, The Id of the form. + * @param callerToken, Caller ability token. + * @return none. + */ +int MockFormProviderClient::NotifyFormDelete(const int64_t formId, const Want &want, + const sptr &callerToken) +{ + APP_LOGD("Notify form delete"); + return ERR_OK; +} +/** + * Notify provider when the forms was deleted. + * + * @param formIds, The id list of forms. + * @param want Indicates the structure containing form info. + * @param callerToken, Caller ability token. + * @return none. + */ +int MockFormProviderClient::NotifyFormsDelete(const std::vector &formIds, const Want &want, + const sptr &callerToken) +{ + APP_LOGD("Notify forms delete"); + return ERR_OK; +} + +/** + * @brief Notify provider when the form need update. + * @param formId The Id of the form. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + */ +int MockFormProviderClient::NotifyFormUpdate(const int64_t formId, const Want &want, + const sptr &callerToken) +{ + APP_LOGD("Notify form update"); + return ERR_OK; +} + +/** + * @brief Event notify when change the form visible. + * + * @param formEvents The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int MockFormProviderClient::EventNotify(const std::vector &formIds, const int32_t formVisibleType, + const Want &want, const sptr &callerToken) +{ + APP_LOGD("Event notify"); + return ERR_OK; +} + +/** + * Notify provider when the temp form was cast to normal form. + * + * @param formId, The Id of the form to update. + * @param callerToken, Caller ability token. + * @return none. + */ +int MockFormProviderClient::NotifyFormCastTempForm(const int64_t formId, const Want &want, + const sptr &callerToken) +{ + APP_LOGD("Notify cast temp form"); + return ERR_OK; +} +/** + * @brief Fire message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param callerToken Form provider proxy object. + * @return Returns ERR_OK on success, others on failure. + */ +int MockFormProviderClient::FireFormEvent(const int64_t formId, const std::string &message, const Want &want, + const sptr &callerToken) +{ + APP_LOGD("Fire form event"); + return ERR_OK; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/test/unittest/fms_form_cache_mgr_test/fms_form_cache_mgr_test.cpp b/services/formmgr/test/unittest/fms_form_cache_mgr_test/fms_form_cache_mgr_test.cpp index 5942712a56984e81f3c5b0475871d376fc20dd26..4416792dee3eabc4ed712d2155b47b72d8b97569 100644 --- a/services/formmgr/test/unittest/fms_form_cache_mgr_test/fms_form_cache_mgr_test.cpp +++ b/services/formmgr/test/unittest/fms_form_cache_mgr_test/fms_form_cache_mgr_test.cpp @@ -124,7 +124,7 @@ HWTEST_F(FmsFormCacheMgrTest, FmsFormCacheMgrTest_004, TestSize.Level0) std::string dataResult2 = "{'a':'2','b':'2'}"; formCacheMgr_.AddData(PARAM_FORM_ID_FIRST, dataResult1); EXPECT_TRUE(formCacheMgr_.AddData(PARAM_FORM_ID_SECOND, dataResult2)); - EXPECT_EQ(formCacheMgr_.cacheData_[PARAM_FORM_ID_SECOND],dataResult2); + EXPECT_EQ(formCacheMgr_.cacheData_[PARAM_FORM_ID_SECOND], dataResult2); GTEST_LOG_(INFO) << "fms_form_cache_mgr_test_004 end"; } diff --git a/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp b/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp index 9864114ed6bcc22e2b3b9fa7995c60b52d61ff4f..c76f6e4c3c476e3b867bd41cd7df05a3867050e5 100644 --- a/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp +++ b/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp @@ -95,7 +95,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_001, TestSize.Le FormItemInfo form_item_info; InitFormItemInfo(formId, form_item_info); - FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); EXPECT_EQ(formId, recordResult.formId); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_001 end"; @@ -123,7 +123,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_002, TestSize.Le FormRecord record = formDataMgr_.CreateFormRecord(form_item_info, callingUid); formDataMgr_.formRecords_.emplace(formId, record); - FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); EXPECT_EQ(formId, recordResult.formId); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_002 end"; @@ -156,7 +156,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_003, TestSize.Le FormRecord record = formDataMgr_.CreateFormRecord(otherFormItemInfo, callingUid); formDataMgr_.formRecords_.emplace(otherformId, record); - FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); EXPECT_EQ(formId, recordResult.formId); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_003 end"; @@ -182,7 +182,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_004, TestSize.Le InitFormItemInfo(formId, form_item_info); form_item_info.SetUpdateDuration(Constants::MAX_CONFIG_DURATION); - FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); EXPECT_EQ(formId, recordResult.formId); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_004 end"; @@ -208,7 +208,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_005, TestSize.Le InitFormItemInfo(formId, form_item_info); form_item_info.SetUpdateDuration(Constants::MAX_CONFIG_DURATION-2); - FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); EXPECT_EQ(formId, recordResult.formId); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_005 end"; @@ -235,7 +235,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_006, TestSize.Le form_item_info.SetUpdateDuration(0); form_item_info.scheduledUpdateTime_.clear(); - FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); EXPECT_EQ(formId, recordResult.formId); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_006 end"; @@ -262,7 +262,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_007, TestSize.Le form_item_info.SetUpdateDuration(0); form_item_info.SetScheduledUpdateTime("10:30:10"); - FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); EXPECT_EQ(formId, recordResult.formId); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_007 end"; @@ -291,7 +291,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_008, TestSize.Le form_item_info.SetScheduledUpdateTime("10:70"); form_item_info.hapSourceDirs_.clear(); - FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); EXPECT_EQ(formId, recordResult.formId); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_008 end"; @@ -317,7 +317,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_009, TestSize.Le InitFormItemInfo(formId, form_item_info); form_item_info.SetUpdateDuration(0); - FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); EXPECT_EQ(formId, recordResult.formId); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_009 end"; @@ -368,7 +368,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormHostRecord_002, TestSiz int64_t formId = 2; int callingUid = 0; - //create FormItemInfo + // create FormItemInfo FormItemInfo formItemInfo; InitFormItemInfo(formId, formItemInfo); @@ -462,7 +462,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_CheckTempEnoughForm_002, TestSiz for (int index = 0; index < Constants::MAX_TEMP_FORMS; index++) { formDataMgr_.tempForms_.emplace_back(index); } - EXPECT_EQ(ERR_MAX_SYSTEM_TEMP_FORMS, formDataMgr_.CheckTempEnoughForm()); + EXPECT_EQ(ERR_APPEXECFWK_FORM_MAX_SYSTEM_TEMP_FORMS, formDataMgr_.CheckTempEnoughForm()); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CheckTempEnoughForm_002 end"; } @@ -489,7 +489,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_CheckEnoughForm_001, TestSize.Le formDataMgr_.formRecords_.emplace(formId_index, record); } - EXPECT_EQ(ERR_MAX_SYSTEM_FORMS, formDataMgr_.CheckEnoughForm(callingUid)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_MAX_SYSTEM_FORMS, formDataMgr_.CheckEnoughForm(callingUid)); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CheckEnoughForm_001 end"; } @@ -534,7 +534,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_CheckEnoughForm_003, TestSize.Le formDataMgr_.formRecords_.emplace(formId_index, record); } - EXPECT_EQ(ERR_MAX_RECORDS_PER_APP, formDataMgr_.CheckEnoughForm(callingUid)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_MAX_FORMS_PER_CLIENT, formDataMgr_.CheckEnoughForm(callingUid)); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CheckEnoughForm_003 end"; } @@ -1349,6 +1349,12 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GetUpdatedForm_001, TestSize.Lev GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetUpdatedForm_001 start"; FormRecord record; + record.bundleName = ""; + record.moduleName = ""; + record.abilityName = ""; + record.formName = ""; + record.specification = 0; + std::vector targetForms; FormInfo updatedForm; @@ -1768,7 +1774,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetVersionUpgrade_001, TestSize. /** * @tc.number: FmsFormDataMgrTest_SetVersionUpgrade_002 - * @tc.name: SetFormCacheInitedTrue + * @tc.name: SetFormCacheInited * @tc.desc: Verify that the return value is correct. * @tc.details: * formRecords_ is found. @@ -1856,7 +1862,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostFormFlag_001, TestSize std::vector refreshForms; - EXPECT_EQ(ERR_FORM_INVALID_PARAM, formDataMgr_.UpdateHostFormFlag(formIds, token_, flag, refreshForms)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, formDataMgr_.UpdateHostFormFlag(formIds, token_, flag, refreshForms)); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_001 end"; } diff --git a/services/formmgr/test/unittest/fms_form_db_record_test/fms_form_db_record_test.cpp b/services/formmgr/test/unittest/fms_form_db_record_test/fms_form_db_record_test.cpp index 944bfb5e83bd889aa6558b0d86698aa4690b2c36..b91066b8351acee81e1b170c42f15f2fff1368ca 100644 --- a/services/formmgr/test/unittest/fms_form_db_record_test/fms_form_db_record_test.cpp +++ b/services/formmgr/test/unittest/fms_form_db_record_test/fms_form_db_record_test.cpp @@ -189,7 +189,7 @@ HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_010, TestSize.Level0) // Delet HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_011, TestSize.Level0) // DeleteDbRecord not exist { GTEST_LOG_(INFO) << "FmsFormDbRecordTest_011 start"; - EXPECT_EQ(ERR_APPEXECFWK_FORM_JSON_DELETE_FAIL, FormDbCache::GetInstance().DeleteFormInfo(2)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_COMMON_CODE, FormDbCache::GetInstance().DeleteFormInfo(2)); GTEST_LOG_(INFO) << "FmsFormDbRecordTest_011 end"; } } diff --git a/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp b/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp index c9956ac308e4695956474ed43298c718fe58ccf0..e062b3f41cd0b93b935d97aec6fcfb81ac5ac230 100644 --- a/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp +++ b/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp @@ -104,8 +104,8 @@ void FmsFormHostRecordTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, - 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } diff --git a/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp index 2213089b19d1b04143eb57ade603dfa6790ed8ee..1d7f2c0a86549a5644f4784fc3b1071c7389994f 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp @@ -110,8 +110,8 @@ void FmsFormMgrAddFormTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, - 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -417,7 +417,7 @@ HWTEST_F(FmsFormMgrAddFormTest, AddForm_006, TestSize.Level0) want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); GTEST_LOG_(INFO) << "formId :"<Wait(); FormDataMgr::GetInstance().DeleteFormRecord(formId); @@ -470,7 +470,7 @@ HWTEST_F(FmsFormMgrAddFormTest, AddForm_007, TestSize.Level0) want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); GTEST_LOG_(INFO) << "formId :"<Wait(); FormDataMgr::GetInstance().DeleteFormRecord(formId); @@ -530,7 +530,7 @@ HWTEST_F(FmsFormMgrAddFormTest, AddForm_008, TestSize.Level0) want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); GTEST_LOG_(INFO) << "formId :"<Wait(); FormDataMgr::GetInstance().DeleteFormRecord(formId); diff --git a/services/formmgr/test/unittest/fms_form_mgr_cast_temp_form_test/fms_form_mgr_cast_temp_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_cast_temp_form_test/fms_form_mgr_cast_temp_form_test.cpp index 7c848885f80db64ab3c353310a03556a30a56546..6bd87bac092088030d1c40491f806f8c1ad80931 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_cast_temp_form_test/fms_form_mgr_cast_temp_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_cast_temp_form_test/fms_form_mgr_cast_temp_form_test.cpp @@ -106,8 +106,8 @@ void FmsFormMgrCastTempFormTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, - 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -182,10 +182,10 @@ HWTEST_F(FmsFormMgrCastTempFormTest, CastTempForm_002, TestSize.Level0) { GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_002 start"; // form id <= 0 - ASSERT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().CastTempForm(0L, token_)); + ASSERT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().CastTempForm(0L, token_)); // Caller ability token is nullptr int64_t formId {FormDataMgr::GetInstance().GenerateFormId()}; - ASSERT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().CastTempForm(formId, nullptr)); + ASSERT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().CastTempForm(formId, nullptr)); GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_002 end"; } @@ -202,7 +202,7 @@ HWTEST_F(FmsFormMgrCastTempFormTest, CastTempForm_003, TestSize.Level0) GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_003 start"; int64_t formId {FormDataMgr::GetInstance().GenerateFormId()}; // form is not exist in cache - ASSERT_EQ(ERR_NOT_EXIST_ID, FormMgr::GetInstance().CastTempForm(formId, token_)); + ASSERT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormMgr::GetInstance().CastTempForm(formId, token_)); GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_003 end"; } @@ -231,7 +231,7 @@ HWTEST_F(FmsFormMgrCastTempFormTest, CastTempForm_004, TestSize.Level0) record1.SetTemporaryFlag(true); FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); - ASSERT_EQ(ERR_OPERATION_FORM_NOT_SELF, FormMgr::GetInstance().CastTempForm(formId, token_)); + ASSERT_EQ(ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, FormMgr::GetInstance().CastTempForm(formId, token_)); FormDataMgr::GetInstance().DeleteFormRecord(formId); FormDbCache::GetInstance().DeleteFormInfo(formId); diff --git a/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/BUILD.gn index 35100ba0d244e7404d6d8cfe235cb58d3ff9f8a3..0ab6a7845a3eb295280c9feb5833ee71089d8752 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/BUILD.gn +++ b/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/BUILD.gn @@ -15,3 +15,74 @@ import("//build/test.gni") import("//foundation/appexecfwk/standard/appexecfwk.gni") module_output_path = "appexecfwk_standard/formmgrservice" + +ohos_unittest("FmsFormMgrDeathCallbackTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/src/form_mgr.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + + # "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_death_callback.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", + ] + sources += [ "fms_form_mgr_death_callback_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include/", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/appexecfwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + + # "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:formmgr_sdk_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/fmskit:fmskit_native", + "${libs_path}/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//base/startup/appspawn_standard:appspawn_socket_client", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + + #"${services_path}/bundlemgr:bms_target", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormMgrDeathCallbackTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/fms_form_mgr_death_callback_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/fms_form_mgr_death_callback_test.cpp index e18f830ad221d64bba3116b69eb3a62c66945d62..3b78d9aa083889c50627c54de0efea44b1b0205e 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/fms_form_mgr_death_callback_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/fms_form_mgr_death_callback_test.cpp @@ -111,8 +111,8 @@ void FmsFormMgrDeathCallbackTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, - 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -144,7 +144,7 @@ HWTEST_F(FmsFormMgrDeathCallbackTest, OnRemoteDied_001, TestSize.Level0) EXPECT_EQ(ERR_OK, FormMgr::GetInstance().AddForm(0L, want, token_, formJsInfo)); token_->Wait(); - std::shared_ptr deathCallback = std::make_shared(); + std::shared_ptr deathCallback = std::make_shared(); FormMgr::GetInstance().RegisterDeathCallback(deathCallback); EXPECT_EQ(true, FormMgr::GetInstance().CheckIsDeathCallbackRegistered(deathCallback)); FormMgr::GetInstance().GetDeathRecipient()->OnRemoteDied(formyMgrServ_->AsObject()); @@ -191,7 +191,7 @@ HWTEST_F(FmsFormMgrDeathCallbackTest, OnRemoteDied_002, TestSize.Level0) EXPECT_EQ(ERR_OK, FormMgr::GetInstance().AddForm(0L, want, token_, formJsInfo)); token_->Wait(); - std::shared_ptr deathCallback = std::make_shared(); + std::shared_ptr deathCallback = std::make_shared(); FormMgr::GetInstance().RegisterDeathCallback(deathCallback); EXPECT_EQ(true, FormMgr::GetInstance().CheckIsDeathCallbackRegistered(deathCallback)); diff --git a/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/fms_form_mgr_delete_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/fms_form_mgr_delete_form_test.cpp index 05bc3c5e86740b4ee912dabe79d48c6e566be4ba..fee5463c9d5c77a913e439bd774e3bfa5d144ff9 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/fms_form_mgr_delete_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/fms_form_mgr_delete_form_test.cpp @@ -104,8 +104,8 @@ void FmsFormMgrDeleteFormTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, - 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -232,9 +232,9 @@ HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_003, TestSize.Level0) { GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_003 start"; // case when formId<=0 - EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().DeleteForm(0, token_)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().DeleteForm(0, token_)); // case when token is nullptr - EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().DeleteForm(123L, nullptr)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().DeleteForm(123L, nullptr)); GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_003 end"; } @@ -325,7 +325,7 @@ HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_006, TestSize.Level0) FormItemInfo info; FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); - EXPECT_EQ(ERR_NOT_EXIST_ID, FormMgr::GetInstance().DeleteForm(formId, token_)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormMgr::GetInstance().DeleteForm(formId, token_)); FormDataMgr::GetInstance().DeleteFormRecord(formId); FormDbCache::GetInstance().DeleteFormInfo(formId); @@ -362,7 +362,7 @@ HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_007, TestSize.Level0) FormItemInfo info; FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); - ASSERT_EQ(ERR_OPERATION_FORM_NOT_SELF, FormMgr::GetInstance().DeleteForm(formId, token_)); + ASSERT_EQ(ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, FormMgr::GetInstance().DeleteForm(formId, token_)); // Cache uid is not deleted yet. FormRecord formInfo; @@ -415,7 +415,7 @@ HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_008, TestSize.Level0) FormItemInfo info; FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); - ASSERT_EQ(ERR_CODE_COMMON, FormMgr::GetInstance().DeleteForm(formId, token_)); + ASSERT_EQ(ERR_APPEXECFWK_FORM_COMMON_CODE, FormMgr::GetInstance().DeleteForm(formId, token_)); // Cache uid is not deleted yet. FormRecord formInfo; @@ -441,7 +441,7 @@ HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_008, TestSize.Level0) FormDBInfo formDBInfo1(formId, retFormRec); FormDbCache::GetInstance().SaveFormInfo(formDBInfo1); - EXPECT_EQ(ERR_CODE_COMMON, FormMgr::GetInstance().DeleteForm(formId, token_)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_COMMON_CODE, FormMgr::GetInstance().DeleteForm(formId, token_)); // Cache uid is not deleted yet. ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); diff --git a/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp index 86deffae18a98f1e43868560cafd5a2d08a85f1d..01e862d910d339eafe0170c70e175d2ccbe96dbd 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp @@ -92,8 +92,8 @@ void FmsFormMgrLifecycleUpdateTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, - 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -151,7 +151,7 @@ HWTEST_F(FmsFormMgrLifecycleUpdateTest, FmsFormMgrLifecycleUpdateTest_LifecycleU std::vector formIds; int32_t updateType = OHOS::AppExecFwk::FormMgrService::ENABLE_FORM_UPDATE; - EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().LifecycleUpdate(formIds, token_, updateType)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().LifecycleUpdate(formIds, token_, updateType)); GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_002 end"; } @@ -171,7 +171,7 @@ HWTEST_F(FmsFormMgrLifecycleUpdateTest, FmsFormMgrLifecycleUpdateTest_LifecycleU int32_t updateType = OHOS::AppExecFwk::FormMgrService::ENABLE_FORM_UPDATE; - EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().LifecycleUpdate(formIds, token_, updateType)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().LifecycleUpdate(formIds, token_, updateType)); GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_003 end"; } diff --git a/services/formmgr/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp index 12d4e8395f8bd64594bc64db8d987c258e4531e6..27a72210b4dc61f1f0f7b8564e36121862bbf529 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp @@ -106,8 +106,8 @@ void FmsFormMgrMessageEventTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, - 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -284,7 +284,7 @@ HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_006, TestSize.Level0) want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); want.SetParam(Constants::PARAM_MESSAGE_KEY, FORM_MESSAGE_EVENT_VALUE_1); - EXPECT_EQ(ERR_APPEXECFWK_FORM_INFO_NOT_EXIST, FormMgr::GetInstance().MessageEvent(formId, want, token_)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormMgr::GetInstance().MessageEvent(formId, want, token_)); GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_006 end"; } /* @@ -306,7 +306,7 @@ HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_007, TestSize.Level0) want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); want.SetParam(Constants::PARAM_MESSAGE_KEY, FORM_MESSAGE_EVENT_VALUE_1); - EXPECT_EQ(ERR_APPEXECFWK_FORM_HOST_INFO_NOT_EXIST, FormMgr::GetInstance().MessageEvent(formId, want, + EXPECT_EQ(ERR_APPEXECFWK_FORM_COMMON_CODE, FormMgr::GetInstance().MessageEvent(formId, want, new (std::nothrow) MockFormHostClient())); GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_007 end"; } @@ -350,7 +350,7 @@ HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_008, TestSize.Level0) want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); want.SetParam(Constants::PARAM_MESSAGE_KEY, FORM_MESSAGE_EVENT_VALUE_1); - EXPECT_EQ(ERR_OPERATION_FORM_NOT_SELF, FormMgr::GetInstance().MessageEvent(formId2, want, token_)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, FormMgr::GetInstance().MessageEvent(formId2, want, token_)); GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_008 end"; } } \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/fms_form_mgr_notify_invisible_forms_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/fms_form_mgr_notify_invisible_forms_test.cpp index d1d1d1d1dc3a954c39eaff20cf20e2da71659687..16f74195dccb53b829eda5afecf54e57bc88c687 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/fms_form_mgr_notify_invisible_forms_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/fms_form_mgr_notify_invisible_forms_test.cpp @@ -91,10 +91,12 @@ void FmsFormMgrNotifyInvisibleFormsTest::SetUp(void) permDef.descriptionId = 1; permList.emplace_back(permDef); OHOS::Security::Permission::PermissionKit::AddDefPermissions(permList); + std::vector permnameList; + permnameList.emplace_back(PERMISSION_NAME_REQUIRE_FORM); OHOS::Security::Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_HOST_BUNDLE_NAME, - {PERMISSION_NAME_REQUIRE_FORM}, 0); + permnameList, 0); OHOS::Security::Permission::PermissionKit::GrantUserGrantedPermission(FORM_HOST_BUNDLE_NAME, - PERMISSION_NAME_REQUIRE_FORM, 0); + PERMISSION_NAME_REQUIRE_FORM, 0); } void FmsFormMgrNotifyInvisibleFormsTest::TearDown(void) @@ -120,8 +122,8 @@ TestSize.Level0) OHOS::Security::Permission::PermissionKit::RemoveUserGrantedReqPermissions(FORM_HOST_BUNDLE_NAME, 0); OHOS::Security::Permission::PermissionKit::RemoveSystemGrantedReqPermissions(FORM_HOST_BUNDLE_NAME); - EXPECT_EQ(ERR_APPEXECFWK_FORM_PERMISSION_DENY, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, - token_, Constants::FORM_INVISIBLE )); + EXPECT_EQ(ERR_APPEXECFWK_FORM_PERMISSION_DENY, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, + token_, Constants::FORM_INVISIBLE)); GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_001 end"; } @@ -145,13 +147,14 @@ TestSize.Level0) iteminfo.formId_ = formId; iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + iteminfo.temporaryFlag_ = true; FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); // clear callerToken token_ = nullptr; - EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, - token_, Constants::FORM_INVISIBLE )); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, + token_, Constants::FORM_INVISIBLE)); GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_002 end"; } @@ -170,7 +173,7 @@ TestSize.Level0) std::vector formIds; formIds.push_back(formId); - EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, token_, Constants::FORM_INVISIBLE )); + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_INVISIBLE)); GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_003 end"; } @@ -194,9 +197,10 @@ TestSize.Level0) iteminfo.formId_ = formId; iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + iteminfo.temporaryFlag_ = true; FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); - EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, token_, Constants::FORM_INVISIBLE )); + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_INVISIBLE)); GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_004 end"; } @@ -221,12 +225,13 @@ TestSize.Level0) iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; iteminfo.formVisibleNotify_ = false; + iteminfo.temporaryFlag_ = true; FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); // creat clientRecords_ FormDataMgr::GetInstance().AllotFormHostRecord(iteminfo, token_, formId, 0); - EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, token_, Constants::FORM_INVISIBLE )); + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_INVISIBLE)); GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_005 end"; } @@ -251,12 +256,13 @@ TestSize.Level0) iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; iteminfo.formVisibleNotify_ = true; + iteminfo.temporaryFlag_ = true; FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); // creat clientRecords_ FormDataMgr::GetInstance().AllotFormHostRecord(iteminfo, token_, formId, 0); - EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, token_, Constants::FORM_INVISIBLE )); + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_INVISIBLE)); GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_006 end"; } @@ -282,6 +288,7 @@ TestSize.Level0) iteminfo.providerBundleName_ = mockBundleName; iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; iteminfo.formVisibleNotify_ = true; + iteminfo.temporaryFlag_ = true; FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); // creat clientRecords_ @@ -305,7 +312,7 @@ TestSize.Level0) OHOS::Security::Permission::PermissionKit::GrantUserGrantedPermission(mockBundleName, PERMISSION_NAME_REQUIRE_FORM, 0); - EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, token_, Constants::FORM_INVISIBLE )); + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_INVISIBLE)); GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_007 end"; } } diff --git a/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp index 83f9d5a58807d54af200400610d38512280aacf6..b9cd43b3bb131b03759347a209b79421ba55b076 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp @@ -88,10 +88,12 @@ void FmsFormMgrNotifyVisibleFormsTest::SetUp(void) permDef.descriptionId = 1; permList.emplace_back(permDef); OHOS::Security::Permission::PermissionKit::AddDefPermissions(permList); + std::vector permnameList; + permnameList.emplace_back(PERMISSION_NAME_REQUIRE_FORM); OHOS::Security::Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, - {PERMISSION_NAME_REQUIRE_FORM}, 0); + permnameList, 0); OHOS::Security::Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, - PERMISSION_NAME_REQUIRE_FORM, 0); + PERMISSION_NAME_REQUIRE_FORM, 0); } void FmsFormMgrNotifyVisibleFormsTest::TearDown(void) diff --git a/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp index 1ec263f000f801931dec8394a2b587445ca34c94..30a5b3673c285f24401dfdcfa932f9c028a60bb1 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp @@ -91,8 +91,8 @@ void FmsFormMgrReleaseFormTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, - 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -206,9 +206,9 @@ HWTEST_F(FmsFormMgrReleaseFormTest, ReleaseForm_003, TestSize.Level0) GTEST_LOG_(INFO) << "fms_form_mgr_release_test_003 start"; int64_t formId = FormDataMgr::GetInstance().GenerateFormId(); // formId<=0 - EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().ReleaseForm(0L, token_, false)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().ReleaseForm(0L, token_, false)); // sptr is nullptr - EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().ReleaseForm(formId, nullptr, false)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().ReleaseForm(formId, nullptr, false)); // Remove Permission OHOS::Security::Permission::PermissionKit::RemoveDefPermissions(FORM_PROVIDER_BUNDLE_NAME); @@ -246,7 +246,7 @@ HWTEST_F(FmsFormMgrReleaseFormTest, ReleaseForm_004, TestSize.Level0) { GTEST_LOG_(INFO) << "fms_form_mgr_release_test_004 start"; int64_t formId = FormDataMgr::GetInstance().GenerateFormId(); - EXPECT_EQ(ERR_NOT_EXIST_ID, FormMgr::GetInstance().ReleaseForm(formId, token_, true)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormMgr::GetInstance().ReleaseForm(formId, token_, true)); GTEST_LOG_(INFO) << "fms_form_mgr_release_test_004 end"; } @@ -268,7 +268,7 @@ HWTEST_F(FmsFormMgrReleaseFormTest, ReleaseForm_005, TestSize.Level0) record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); record.SetTemporaryFlag(false); FormDataMgr::GetInstance().AllotFormRecord(record, 0); - EXPECT_EQ(ERR_OPERATION_FORM_NOT_SELF, FormMgr::GetInstance().ReleaseForm(formId, token_, true)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, FormMgr::GetInstance().ReleaseForm(formId, token_, true)); GTEST_LOG_(INFO) << "fms_form_mgr_release_test_005 end"; } } \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_mgr_request_form_test/fms_form_mgr_request_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_request_form_test/fms_form_mgr_request_form_test.cpp index f6d4824741384a3c12eddad993ff143dc248d1d6..cef35f47929c5cac8ff3c1786f6711937eb53133 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_request_form_test/fms_form_mgr_request_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_request_form_test/fms_form_mgr_request_form_test.cpp @@ -94,8 +94,8 @@ void FmsFormMgrRequestFormTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, - 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -202,7 +202,7 @@ HWTEST_F(FmsFormMgrRequestFormTest, RequestForm_003, TestSize.Level0) FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); Want want; - EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().RequestForm(formId, token_, want)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().RequestForm(formId, token_, want)); token_->Wait(); FormDataMgr::GetInstance().DeleteFormRecord(formId); @@ -235,7 +235,7 @@ HWTEST_F(FmsFormMgrRequestFormTest, RequestForm_004, TestSize.Level0) FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, fakeFormId, 0); Want want; - EXPECT_EQ(ERR_OPERATION_FORM_NOT_SELF, FormMgr::GetInstance().RequestForm(formId, token_, want)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, FormMgr::GetInstance().RequestForm(formId, token_, want)); token_->Wait(); FormDataMgr::GetInstance().DeleteFormRecord(formId); diff --git a/services/formmgr/test/unittest/fms_form_mgr_update_form_test/fms_form_mgr_update_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_update_form_test/fms_form_mgr_update_form_test.cpp index 0f051fc1b05a2f63a58dd0b69a24de67774c3167..bde926b055812207a4470dfcf43484a65f5cddbf 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_update_form_test/fms_form_mgr_update_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_update_form_test/fms_form_mgr_update_form_test.cpp @@ -102,8 +102,8 @@ void FmsFormMgrUpdateFormTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, - 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -231,7 +231,7 @@ HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_003, TestSize.Level0) FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); // test exec - EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_003 end"; } @@ -267,7 +267,7 @@ HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_004, TestSize.Level0) FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); // test exec - EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_004 end"; } @@ -303,7 +303,7 @@ HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_005, TestSize.Level0) FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); // test exec - EXPECT_EQ(ERR_NOT_EXIST_ID, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_005 end"; } @@ -339,7 +339,7 @@ HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_006, TestSize.Level0) FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); // test exec - EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_006 end"; } diff --git a/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp b/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp index 31c9bd4191f960d53bce3e53c04eb5fc4656ad9b..f20fec9b9bc0b10186e0d7d008e10208b1d1814b 100644 --- a/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp +++ b/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp @@ -31,7 +31,7 @@ using namespace OHOS; using namespace OHOS::AppExecFwk; namespace { -const char* FORM_DB_DATA_BASE_FILE_DIR = "/data/formmgr"; +const std::string FORM_DB_DATA_BASE_FILE_DIR = "/data/formmgr"; const int32_t four = 4; const int32_t ten = 10; const int32_t eleven = 11; @@ -45,16 +45,15 @@ public: bool CreateJsonFileByJsonData1(const nlohmann::json &jsonData); bool CreateJsonFileByJsonData2(const nlohmann::json &jsonData); bool CreateMergeJsonFileByJsonData3(const nlohmann::json &jsonData); - // bool createJsonFileByStringData(); nlohmann::json jsonData_; }; void FmsFormProviderDataTest::SetUp() { - DIR *dirptr = opendir(FORM_DB_DATA_BASE_FILE_DIR); + DIR *dirptr = opendir(FORM_DB_DATA_BASE_FILE_DIR.c_str()); if (dirptr == nullptr) { APP_LOGW("%{public}s, opendir is fail", __func__); - if (-1 == mkdir(FORM_DB_DATA_BASE_FILE_DIR, S_IRWXU)) { + if (-1 == mkdir(FORM_DB_DATA_BASE_FILE_DIR.c_str(), S_IRWXU)) { APP_LOGE("%{public}s, dir create fail", __func__); return; } @@ -87,7 +86,7 @@ bool FmsFormProviderDataTest::CreateJsonFileByJsonData1(const nlohmann::json &js o.close(); std::fstream f("/data/formmgr/ByJsonFile1.json"); - if(f.good() == false) { + if (f.good() == false) { return false; } @@ -103,7 +102,7 @@ bool FmsFormProviderDataTest::CreateJsonFileByJsonData2(const nlohmann::json &js o.close(); std::fstream f("/data/formmgr/ByJsonFile2.json"); - if(f.good() == false) { + if (f.good() == false) { return false; } @@ -119,7 +118,7 @@ bool FmsFormProviderDataTest::CreateMergeJsonFileByJsonData3(const nlohmann::jso o.close(); std::fstream f("/data/formmgr/ByJsonFile3.json"); - if(f.good() == false) { + if (f.good() == false) { return false; } diff --git a/services/formmgr/test/unittest/fms_form_provider_mgr_test/fms_form_provider_mgr_test.cpp b/services/formmgr/test/unittest/fms_form_provider_mgr_test/fms_form_provider_mgr_test.cpp index c8a7d78eccec5d6b7a11d03e23aaeb485e9de4bd..742782f7ec6e546512f0e8ce8f319fa3dd4c9b74 100644 --- a/services/formmgr/test/unittest/fms_form_provider_mgr_test/fms_form_provider_mgr_test.cpp +++ b/services/formmgr/test/unittest/fms_form_provider_mgr_test/fms_form_provider_mgr_test.cpp @@ -108,8 +108,8 @@ void FmsFormProviderMgrTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, - 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -130,7 +130,7 @@ HWTEST_F(FmsFormProviderMgrTest, AcquireForm_001, TestSize.Level0) GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_001 start"; int64_t formId = 0x114514aa00000000; FormProviderInfo formProviderInfo; - EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormProviderMgr::GetInstance().AcquireForm(-114514L, formProviderInfo)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormProviderMgr::GetInstance().AcquireForm(-114514L, formProviderInfo)); int callingUid {0}; FormItemInfo record; record.SetFormId(formId); @@ -154,7 +154,7 @@ HWTEST_F(FmsFormProviderMgrTest, AcquireForm_002, TestSize.Level0) GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_002 start"; int64_t formId = 0x11451aaa00000000; FormProviderInfo formProviderInfo; - EXPECT_EQ(ERR_APPEXECFWK_FORM_INFO_NOT_EXIST,FormProviderMgr::GetInstance().AcquireForm(formId,formProviderInfo)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormProviderMgr::GetInstance().AcquireForm(formId, formProviderInfo)); int callingUid {0}; FormItemInfo record; record.SetFormId(formId); @@ -183,8 +183,8 @@ HWTEST_F(FmsFormProviderMgrTest, AcquireForm_003, TestSize.Level0) FormItemInfo record; record.SetFormId(formId); FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); - EXPECT_EQ(ERR_APPEXECFWK_FORM_HOST_INFO_NOT_EXIST, - FormProviderMgr::GetInstance().AcquireForm(formId,formProviderInfo)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_COMMON_CODE, + FormProviderMgr::GetInstance().AcquireForm(formId, formProviderInfo)); FormItemInfo info; FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_003 end"; @@ -206,7 +206,7 @@ HWTEST_F(FmsFormProviderMgrTest, RefreshForm_001, TestSize.Level0) int64_t formId = 0x1145aaaa00001200; Want want; int callingUid {0}; - EXPECT_EQ(ERR_APPEXECFWK_FORM_INFO_NOT_EXIST, FormProviderMgr::GetInstance().RefreshForm(formId, want)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormProviderMgr::GetInstance().RefreshForm(formId, want)); FormItemInfo record; record.SetFormId(formId); record.SetModuleName(PARAM_FORM_NAME); @@ -240,7 +240,7 @@ HWTEST_F(FmsFormProviderMgrTest, RefreshForm_002, TestSize.Level0) FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); FormItemInfo info; FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); - EXPECT_EQ(ERR_APPEXECFWK_FORM_SUPPLIER_DEL_FAIL, FormProviderMgr::GetInstance().RefreshForm(formId, want)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_PROVIDER_DEL_FAIL, FormProviderMgr::GetInstance().RefreshForm(formId, want)); GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_005 end"; } } \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_set_next_refresh_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/BUILD.gn index 16adef3efec1680e7ddf8501ba56d4a741feaefa..705667c2aadaa5bcb977d4cac7344760722a60fb 100644 --- a/services/formmgr/test/unittest/fms_form_set_next_refresh_test/BUILD.gn +++ b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/BUILD.gn @@ -58,12 +58,15 @@ ohos_unittest("FmsFormSetNextRefreshTest") { "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/interfaces/innerkits/fmskit:fmskit_native", "${services_path}/formmgr:fms_target", + "//base/miscservices/time/services:time_service", + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", #"${libs_path}/libeventhandler:libeventhandler_target", #"//base/startup/appspawn_standard:appspawn_socket_client", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", diff --git a/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp index 76a978a7892529a009499e1663b0c128ac5a00db..d6e661b62e6006ce51257d88f0f3a24594690306 100644 --- a/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp +++ b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp @@ -86,7 +86,7 @@ HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime int64_t formId = 0; // invalid formId int64_t nextTime = Constants::MIN_NEXT_TIME; - EXPECT_EQ(ERR_FORM_INVALID_PARAM, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_001 end"; } @@ -101,7 +101,7 @@ HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime int64_t formId = 2; int64_t nextTime = Constants::MIN_NEXT_TIME; - EXPECT_EQ(ERR_APPEXECFWK_FORM_INFO_NOT_EXIST, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_002 end"; } @@ -124,6 +124,7 @@ HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime iteminfo.formId_ = formId; iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + iteminfo.temporaryFlag_ = true; FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); EXPECT_EQ(ERR_OK, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); @@ -150,9 +151,10 @@ HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime iteminfo.formId_ = formId; iteminfo.providerBundleName_ = "other_bundleName"; iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + iteminfo.temporaryFlag_ = true; FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); - EXPECT_EQ(ERR_OPERATION_FORM_NOT_SELF, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_004 end"; } @@ -172,6 +174,7 @@ HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime iteminfo.formId_ = formId; iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + iteminfo.temporaryFlag_ = true; FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); // Creat dynamicRefreshTasks_ @@ -213,6 +216,7 @@ HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime iteminfo.formId_ = formId; iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + iteminfo.temporaryFlag_ = true; FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); // set timerRefreshedCount @@ -223,7 +227,7 @@ HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime } else { iter->second.refreshCount = Constants::LIMIT_COUNT; } - EXPECT_EQ(ERR_MAX_REFRESH, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_MAX_REFRESH, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_006 end"; } diff --git a/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/BUILD.gn index e2ef82595509819b4c79a915dea1a99bd56fcef8..ef6b82067dd485bce5010185d5e564b8962a2d20 100644 --- a/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/BUILD.gn +++ b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/BUILD.gn @@ -60,6 +60,8 @@ ohos_unittest("FmsFormSysEventReceiverTest") { "${appexecfwk_path}/interfaces/innerkits/fmskit:fmskit_native", "${libs_path}/libeventhandler:libeventhandler_target", "${services_path}/formmgr:fms_target", + "//base/miscservices/time/services:time_service", + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", "//base/startup/appspawn_standard:appspawn_socket_client", "//foundation/aafwk/standard/interfaces/innerkits/base:base", @@ -67,6 +69,7 @@ ohos_unittest("FmsFormSysEventReceiverTest") { #"${services_path}/bundlemgr:bms_target", "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", diff --git a/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp index 66aaa586a5ca0c8d619ef6245469997f7bfa59f8..2b094e5940ea45bcfe11a965c994497da4124fa8 100644 --- a/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp +++ b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp @@ -73,7 +73,8 @@ public: static void TearDownTestCase(); void SetUp(); void TearDown(); - void CreateEventData(std::string bundle, int64_t formId, int callingUid, std::string actionType, EventFwk::CommonEventData &eventData); + void CreateEventData(std::string bundle, int64_t formId, + int callingUid, std::string actionType, EventFwk::CommonEventData &eventData); void CreateFormRecordAndFormInfo(std::string bundle, int64_t formId, int callingUid); void ClearFormRecord(int64_t formId); @@ -119,15 +120,16 @@ void FmsFormSysEventReceiverTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, - 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } void FmsFormSysEventReceiverTest::TearDown() {} -void FmsFormSysEventReceiverTest::CreateEventData(std::string bundle, int64_t formId, int callingUid, std::string actionType, EventFwk::CommonEventData &eventData) +void FmsFormSysEventReceiverTest::CreateEventData(std::string bundle, int64_t formId, + int callingUid, std::string actionType, EventFwk::CommonEventData &eventData) { Want want; want.SetAction(actionType); @@ -205,7 +207,7 @@ HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_001, TestSize.Level0) FormSysEventReceiver testCase; testCase.OnReceiveEvent(eventData); FormDbCache::GetInstance().GetAllFormInfo(allFormInfo); - EXPECT_EQ(ERR_APPEXECFWK_FORM_JSON_DELETE_FAIL, FormDbCache::GetInstance().DeleteFormInfo(formId)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_COMMON_CODE, FormDbCache::GetInstance().DeleteFormInfo(formId)); FormDataMgr::GetInstance().DeleteFormRecord(formId); FormDbCache::GetInstance().DeleteFormInfo(formId); FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); @@ -352,7 +354,7 @@ HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_006, TestSize.Level0) EventFwk::CommonEventData eventData; CreateEventData(bundle, formId, callingUid, actionType, eventData); - //CreateFormRecordAndFormInfo + // CreateFormRecordAndFormInfo FormItemInfo record; record.SetFormId(formId); record.SetProviderBundleName(bundle); @@ -362,7 +364,7 @@ HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_006, TestSize.Level0) record.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); record.SetTemporaryFlag(true); FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); - ////AddFormUserUid + // AddFormUserUid int new_callingUid = 150; FormDataMgr::GetInstance().AddFormUserUid(formId, new_callingUid); FormRecord realFormRecord; @@ -440,13 +442,13 @@ HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_008, TestSize.Level0) EventFwk::CommonEventData eventData; CreateEventData(bundle, formId, callingUid, actionType, eventData); - //CreateFormRecordAndFormInfo + // CreateFormRecordAndFormInfo FormItemInfo record; record.SetFormId(formId); record.SetProviderBundleName(bundle); record.SetModuleName(PARAM_PROVIDER_MODULE_NAME); // model name - record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); //ability name - record.SetFormName(PARAM_FORM_NAME); //form name + record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); // ability name + record.SetFormName(PARAM_FORM_NAME); // form name record.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); record.SetTemporaryFlag(true); @@ -469,5 +471,4 @@ HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_008, TestSize.Level0) GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_008 end"; } - } \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_timer_mgr_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_timer_mgr_test/BUILD.gn index 6cf9c8dbff8483f7caff7d10f8e795e5d8644242..93ef619b6164f6a1b85cb4239bd27f508cfafd34 100644 --- a/services/formmgr/test/unittest/fms_form_timer_mgr_test/BUILD.gn +++ b/services/formmgr/test/unittest/fms_form_timer_mgr_test/BUILD.gn @@ -27,6 +27,7 @@ ohos_unittest("FmsFormTimerMgrTest") { "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", + "//base/miscservices/time/interfaces/innerkits/include", ] configs = [ @@ -39,17 +40,21 @@ ohos_unittest("FmsFormTimerMgrTest") { } deps = [ "${appexecfwk_path}/common:libappexecfwk_common", - "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", - "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${services_path}/formmgr:fms_target", - "//foundation/aafwk/standard/interfaces/innerkits/base:base", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//base/miscservices/time/services:time_service", + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", + "//base/notification/ces_standard/frameworks/common:libevent_common", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", "//third_party/googletest:gmock_main", "//utils/native/base:utils", ] external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "appexecfwk_standard:libeventhandler", "ces_standard:cesfwk_core", "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", diff --git a/services/formmgr/test/unittest/fms_form_timer_mgr_test/fms_form_timer_mgr_test.cpp b/services/formmgr/test/unittest/fms_form_timer_mgr_test/fms_form_timer_mgr_test.cpp index efb9fe31a78ceb24f815c8e1a2da83c9ad84e3de..b8c72fada0bdf4c63b64d51f83e292d832c0a0ba 100644 --- a/services/formmgr/test/unittest/fms_form_timer_mgr_test/fms_form_timer_mgr_test.cpp +++ b/services/formmgr/test/unittest/fms_form_timer_mgr_test/fms_form_timer_mgr_test.cpp @@ -178,26 +178,16 @@ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0007, Function | MediumTest | Lev } /** * @tc.number: Fms_FormTimerMgr_0008 - * @tc.name: TimerReceiver::OnReceiveEvent. - * @tc.desc: Receive common event(COMMON_EVENT_TIME_CHANGED). + * @tc.name: HandleSystemTimeChanged. + * @tc.desc: Handle system time changed. */ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0008, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0008 start"; bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_1, 11, 30); EXPECT_EQ(isAddOk5, true); - - /* Publish */ - - // make a want - AAFwk::Want want; - want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_TIME_CHANGED); - // make common event data - EventFwk::CommonEventData data; - data.SetWant(want); - // publish a common event - bool publishResult = EventFwk::CommonEventManager::PublishCommonEvent(data); - EXPECT_EQ(publishResult, true); + bool isAddOk6 = FormTimerMgr::GetInstance().HandleSystemTimeChanged(); + EXPECT_EQ(isAddOk6, true); GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0008 end"; } @@ -212,52 +202,31 @@ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0009, Function | MediumTest | Lev GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0009 start"; bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_2, 11, 30); EXPECT_EQ(isAddOk5, true); - - /* Publish */ - - // make a want - AAFwk::Want want; - want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED); - // make common event data - EventFwk::CommonEventData data; - data.SetWant(want); - // publish a common event - bool publishResult = EventFwk::CommonEventManager::PublishCommonEvent(data); - EXPECT_EQ(publishResult, true); + bool isAddOk6 = FormTimerMgr::GetInstance().HandleSystemTimeChanged(); + EXPECT_EQ(isAddOk6, true); GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0009 end"; } /** * @tc.number: Fms_FormTimerMgr_0010 - * @tc.name: TimerReceiver::OnReceiveEvent. - * @tc.desc: Receive common event(ACTION_UPDATEATTIMER - TYPE_RESET_LIMIT). + * @tc.name: HandleResetLimiter. + * @tc.desc: Handle reset limiter. */ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0010, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0010 start"; - bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_3, 11, 30); + bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_3, 16, 30); EXPECT_EQ(isAddOk5, true); - - /* Publish */ - - // make a want - AAFwk::Want want; - want.SetAction(Constants::ACTION_UPDATEATTIMER); - want.SetParam(Constants::KEY_ACTION_TYPE, Constants::TYPE_RESET_LIMIT); - // make common event data - EventFwk::CommonEventData data; - data.SetWant(want); - // publish a common event - bool publishResult = EventFwk::CommonEventManager::PublishCommonEvent(data); - EXPECT_EQ(publishResult, true); + bool isAddOk6 = FormTimerMgr::GetInstance().HandleResetLimiter(); + EXPECT_EQ(isAddOk6, true); GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0010 end"; } /** * @tc.number: Fms_FormTimerMgr_0011 - * @tc.name: TimerReceiver::OnReceiveEvent. - * @tc.desc: Receive common event(ACTION_UPDATEATTIMER - TYPE_STATIC_UPDATE). + * @tc.name: OnUpdateAtTrigger. + * @tc.desc:handle attimer update. */ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0011, Function | MediumTest | Level1) { @@ -265,26 +234,15 @@ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0011, Function | MediumTest | Lev bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_4, 11, 30); EXPECT_EQ(isAddOk5, true); - /* Publish */ - - // make a want - AAFwk::Want want; - want.SetAction(Constants::ACTION_UPDATEATTIMER); - want.SetParam(Constants::KEY_ACTION_TYPE, Constants::TYPE_STATIC_UPDATE); - want.SetParam(Constants::KEY_WAKEUP_TIME, 90L); - // make common event data - EventFwk::CommonEventData data; - data.SetWant(want); - // publish a common event - bool publishResult = EventFwk::CommonEventManager::PublishCommonEvent(data); - EXPECT_EQ(publishResult, true); + bool isAddOk6 = FormTimerMgr::GetInstance().OnUpdateAtTrigger(90L); + EXPECT_EQ(isAddOk6, true); GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0011 end"; } /** * @tc.number: Fms_FormTimerMgr_0012 - * @tc.name: TimerReceiver::OnReceiveEvent. - * @tc.desc: Receive common event(ACTION_UPDATEATTIMER - TYPE_DYNAMIC_UPDATE). + * @tc.name: OnDynamicTimeTrigger. + * @tc.desc: handle dynamic update. */ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0012, Function | MediumTest | Level1) { @@ -292,19 +250,8 @@ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0012, Function | MediumTest | Lev bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_5, 11, 30); EXPECT_EQ(isAddOk5, true); - /* Publish */ - - // make a want - AAFwk::Want want; - want.SetAction(Constants::ACTION_UPDATEATTIMER); - want.SetParam(Constants::KEY_ACTION_TYPE, Constants::TYPE_DYNAMIC_UPDATE); - want.SetParam(Constants::KEY_WAKEUP_TIME, 90L); - // make common event data - EventFwk::CommonEventData data; - data.SetWant(want); - // publish a common event - bool publishResult = EventFwk::CommonEventManager::PublishCommonEvent(data); - EXPECT_EQ(publishResult, true); + bool isAddOk6 = FormTimerMgr::GetInstance().OnDynamicTimeTrigger(90L); + EXPECT_EQ(isAddOk6, true); GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0012 end"; } @@ -526,7 +473,7 @@ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0024, Function | MediumTest | Lev FormRefreshLimiter refreshLimiter; bool isAddOk = refreshLimiter.AddItem(PARAM_FORM_ID_VALUE_6); EXPECT_EQ(isAddOk, true); - for(int iIndex = 0; iIndex < Constants::LIMIT_COUNT; iIndex++){ + for (int iIndex = 0; iIndex < Constants::LIMIT_COUNT; iIndex++) { refreshLimiter.Increase(PARAM_FORM_ID_VALUE_6); } @@ -548,7 +495,7 @@ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0025, Function | MediumTest | Lev FormRefreshLimiter refreshLimiter; bool isAddOk = refreshLimiter.AddItem(PARAM_FORM_ID_VALUE_6); EXPECT_EQ(isAddOk, true); - for(int iIndex = 0; iIndex < Constants::LIMIT_COUNT + 1; iIndex++) { + for (int iIndex = 0; iIndex < Constants::LIMIT_COUNT + 1; iIndex++) { refreshLimiter.Increase(PARAM_FORM_ID_VALUE_6); } @@ -570,7 +517,7 @@ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0026, Function | MediumTest | Lev FormRefreshLimiter refreshLimiter; bool isAddOk = refreshLimiter.AddItem(PARAM_FORM_ID_VALUE_6); EXPECT_EQ(isAddOk, true); - for(int iIndex = 0; iIndex < Constants::LIMIT_COUNT + 1; iIndex++) { + for (int iIndex = 0; iIndex < Constants::LIMIT_COUNT + 1; iIndex++) { refreshLimiter.Increase(PARAM_FORM_ID_VALUE_6); } diff --git a/test/resource/amssystemtestability/abilitySrc/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/BUILD.gn index f8459bf203aa6947909c105bd20e1c27ba24082d..f583aff6456955f30da23a691294f598e85819f6 100644 --- a/test/resource/amssystemtestability/abilitySrc/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/BUILD.gn @@ -13,53 +13,52 @@ group("ams_system_test_app") { deps = [ - "amsAbilityAppendTestA:amsAbilityAppendTestA", - "amsAbilityAppendTestB:amsAbilityAppendTestB", - "amsAbilityVisibleTestPageA:amsAbilityVisibleTestPageA", - "amsAbilityVisibleTestServiceB:amsAbilityVisibleTestServiceB", - "amsConfigurationUpdatedTest:amsConfigurationUpdatedTest", - "amsDataSystemTestA:amsDataSystemTestA", - "amsDataSystemTestB:amsDataSystemTestB", - "amsDataSystemTestC:amsDataSystemTestC", - "amsKitSTAbilityManager:amsKitSTAbilityManager", - "amsKitSystemTest:amsKitSystemTest", - "amsKitSystemTestA:amsKitSystemTestA", - "amsKitSystemTestB:amsKitSystemTestB", - "amsKitSystemTestDataA:amsKitSystemTestDataA", - "amsKitSystemTestDataB:amsKitSystemTestDataB", - "amsKitSystemTestPageA:amsKitSystemTestPageA", - "amsKitSystemTestService:amsKitSystemTestService", - "amsMissionStackTest:amsMissionStackTest", - "amsMissionStackTestSubsidiary:amsMissionStackTestSubsidiary", - "amsSystemTestA:amsSystemTestA", - "amsSystemTestB:amsSystemTestB", - "amsSystemTestC:amsSystemTestC", - "amsSystemTestD:amsSystemTestD", - "amsSystemTestDFX:amsSystemTestDFX", - "amsSystemTestE:amsSystemTestE", - "amsSystemTestErrorK:amsSystemTestErrorK", - "amsSystemTestErrorL:amsSystemTestErrorL", - "amsSystemTestF:amsSystemTestF", - "amsSystemTestG:amsSystemTestG", - "amsSystemTestH:amsSystemTestH", - "amsSystemTestI:amsSystemTestI", - "amsSystemTestM:amsSystemTestM", - "amsSystemTestN:amsSystemTestN", - "amsSystemTestO:amsSystemTestO", - "amsSystemTestP:amsSystemTestP", - "amsSystemTestQ:amsSystemTestQ", - "amsSystemTestR:amsSystemTestR", - "amsSystemTestServiceA:amsSystemTestServiceA", - "amsSystemTestServiceB:amsSystemTestServiceB", - "amsSystemTestServiceC:amsSystemTestServiceC", - - # "amsSystemTestServiceD:amsSystemTestServiceD", - "amsSystemTestServiceE:amsSystemTestServiceE", - "amsSystemTestServiceF:amsSystemTestServiceF", - "amsSystemTestServiceG:amsSystemTestServiceG", - "amsSystemTestServiceH:amsSystemTestServiceH", - "serviceAbilityA:serviceAbilityA", - "taskDispatcherTestA:taskDispatcherTestA", - "taskDispatcherTestB:taskDispatcherTestB", + #"amsAbilityAppendTestA:amsAbilityAppendTestA", + #"amsAbilityAppendTestB:amsAbilityAppendTestB", + #"amsAbilityVisibleTestPageA:amsAbilityVisibleTestPageA", + #"amsAbilityVisibleTestServiceB:amsAbilityVisibleTestServiceB", + #"amsConfigurationUpdatedTest:amsConfigurationUpdatedTest", + #"amsDataSystemTestA:amsDataSystemTestA", + #"amsDataSystemTestB:amsDataSystemTestB", + #"amsDataSystemTestC:amsDataSystemTestC", + #"amsKitSTAbilityManager:amsKitSTAbilityManager", + #"amsKitSystemTest:amsKitSystemTest", + #"amsKitSystemTestA:amsKitSystemTestA", + #"amsKitSystemTestB:amsKitSystemTestB", + #"amsKitSystemTestDataA:amsKitSystemTestDataA", + #"amsKitSystemTestDataB:amsKitSystemTestDataB", + #"amsKitSystemTestPageA:amsKitSystemTestPageA", + #"amsKitSystemTestService:amsKitSystemTestService", + #"amsMissionStackTest:amsMissionStackTest", + #"amsMissionStackTestSubsidiary:amsMissionStackTestSubsidiary", + #"amsSystemTestA:amsSystemTestA", + #"amsSystemTestB:amsSystemTestB", + #"amsSystemTestC:amsSystemTestC", + #"amsSystemTestD:amsSystemTestD", + #"amsSystemTestDFX:amsSystemTestDFX", + #"amsSystemTestE:amsSystemTestE", + #"amsSystemTestErrorK:amsSystemTestErrorK", + #"amsSystemTestErrorL:amsSystemTestErrorL", + #"amsSystemTestF:amsSystemTestF", + #"amsSystemTestG:amsSystemTestG", + #"amsSystemTestH:amsSystemTestH", + #"amsSystemTestI:amsSystemTestI", + #"amsSystemTestM:amsSystemTestM", + #"amsSystemTestN:amsSystemTestN", + #"amsSystemTestO:amsSystemTestO", + #"amsSystemTestP:amsSystemTestP", + #"amsSystemTestQ:amsSystemTestQ", + #"amsSystemTestR:amsSystemTestR", + #"amsSystemTestServiceA:amsSystemTestServiceA", + #"amsSystemTestServiceB:amsSystemTestServiceB", + #"amsSystemTestServiceC:amsSystemTestServiceC", + ## "amsSystemTestServiceD:amsSystemTestServiceD", + #"amsSystemTestServiceE:amsSystemTestServiceE", + #"amsSystemTestServiceF:amsSystemTestServiceF", + #"amsSystemTestServiceG:amsSystemTestServiceG", + #"amsSystemTestServiceH:amsSystemTestServiceH", + #"serviceAbilityA:serviceAbilityA", + #"taskDispatcherTestA:taskDispatcherTestA", + #"taskDispatcherTestB:taskDispatcherTestB", ] } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/BUILD.gn index 959cca097bb82084ddf7062b7c554d1c84b2fbcd..d9fbfd025ba42dcaefc29b825397d21fdbcea7c5 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/BUILD.gn @@ -56,6 +56,8 @@ ohos_shared_library("amsAbilityAppendTestA") { "${innerkits_path}/appexecfwk_core:appexecfwk_core", "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/BUILD.gn index 94db70137542f2660dd2eae0ce219ccc1ed7424d..c510161b409741c5ed49b41194b4706022a31b73 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/BUILD.gn @@ -55,6 +55,8 @@ ohos_shared_library("amsAbilityAppendTestB") { "${innerkits_path}/appexecfwk_core:appexecfwk_core", "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/BUILD.gn index 47d0c6613f81ff009a68a58ef0ded978ea8ce16d..edea9e7b8463bf365cd7d920a2d6dc691877375d 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/BUILD.gn @@ -52,6 +52,8 @@ ohos_shared_library("amsAbilityVisibleTestPageA") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//utils/native/base:utilsbase", ] diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea1.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea1.cpp index b54bb086d55ed747d90d7c4cd0db86f2705069c1..0c0e041b426fa9634a1ee7baf65b51dd4302e683 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea1.cpp @@ -17,6 +17,7 @@ namespace OHOS { namespace AppExecFwk { +using namespace OHOS::NativeRdb; void AmsAbilityVisibleTestPageA1::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) @@ -89,7 +90,7 @@ void AmsAbilityVisibleTestPageA1::OnActive() if (startAbilityType == "Data") { Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); - AppExecFwk::ValuesBucket bucket; + NativeRdb::ValuesBucket bucket; helper->Insert(dataAbilityUri, bucket); } } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea2.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea2.cpp index 1dd32126b946cda35b2ac232d21b8b27e6e43d00..169897284c4c5885d78b51e19f615971a1d680fb 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea2.cpp @@ -17,6 +17,7 @@ namespace OHOS { namespace AppExecFwk { + void AmsAbilityVisibleTestPageA2::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) @@ -89,7 +90,7 @@ void AmsAbilityVisibleTestPageA2::OnActive() if (startAbilityType == "Data") { Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; helper->Insert(dataAbilityUri, bucket); } if (startAbilityType == "TriggerWantAgentPageAbility") { diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea3.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea3.cpp index 8a041eb3f6e44221064dc13fa106cf7c0befe6ba..3a10f80656d8a96d4885999ec4696d179971f613 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea3.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea3.cpp @@ -17,6 +17,7 @@ namespace OHOS { namespace AppExecFwk { + void AmsAbilityVisibleTestPageA3::OnStart(const Want &want) { GetWantInfo(want); @@ -79,7 +80,7 @@ void AmsAbilityVisibleTestPageA3::OnActive() if (startAbilityType == "Data") { Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; helper->Insert(dataAbilityUri, bucket); } } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea4.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea4.cpp index 22816749749d1e9e1a705d255b7bba96f06550e1..c122ba32b9be2aad813ad493c9ae23aa697a7d6d 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea4.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea4.cpp @@ -17,6 +17,7 @@ namespace OHOS { namespace AppExecFwk { + void AmsAbilityVisibleTestPageA4::OnStart(const Want &want) { GetWantInfo(want); @@ -80,7 +81,7 @@ void AmsAbilityVisibleTestPageA4::OnActive() if (startAbilityType == "Data") { Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; helper->Insert(dataAbilityUri, bucket); } } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/BUILD.gn index 4985c58073318cad1478ccb0cd79d16f6902c2d0..0eafd1b592e649e793df8f50579dde01c57faf43 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/BUILD.gn @@ -53,6 +53,8 @@ ohos_shared_library("amsAbilityVisibleTestServiceB") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//utils/native/base:utilsbase", ] diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb1.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb1.cpp index c3ab87e077f7acef41090264caecca2285d7a8e7..29a044e5b841a98b81f856b72908d27a1272fe0d 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb1.cpp @@ -17,6 +17,7 @@ namespace OHOS { namespace AppExecFwk { + void AmsAbilityVisibleTestPageB1::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) @@ -89,7 +90,7 @@ void AmsAbilityVisibleTestPageB1::OnActive() if (startAbilityType == "Data") { Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; helper->Insert(dataAbilityUri, bucket); } } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb2.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb2.cpp index 2caba9013d0579c77da46623421b7e3049325ce2..36516ae9a5df48605e3201efe6b5bb7daabc9d94 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb2.cpp @@ -17,6 +17,7 @@ namespace OHOS { namespace AppExecFwk { + void AmsAbilityVisibleTestPageB2::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) @@ -90,7 +91,7 @@ void AmsAbilityVisibleTestPageB2::OnActive() if (startAbilityType == "Data" || startAbilityType == "DataRelease") { Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; helper->Insert(dataAbilityUri, bucket); if (startAbilityType == "DataRelease") { helper->Release(); diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservice.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservice.cpp index a4ee376ae8f281ad5f7d0f8abb3d4a80afc38d78..d6c3935407a9967842649eb5dede4332b1a5fd65 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservice.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservice.cpp @@ -116,7 +116,7 @@ sptr AmsAbilityVisibleTestService::OnConnect(const Want &want) if (startAbilityType == "Data") { Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; helper->Insert(dataAbilityUri, bucket); } } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservicea1.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservicea1.cpp index 208056c5250385a7970fe6fa753c02aa120e8fdb..a7bb23c23067f378f13c300df8e679abf6a3df1e 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservicea1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservicea1.cpp @@ -116,7 +116,7 @@ sptr AmsAbilityVisibleTestServiceA1::OnConnect(const Want &want) if (startAbilityType == "Data") { Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; helper->Insert(dataAbilityUri, bucket); } } diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/BUILD.gn index 901930e78c5f561df13734ef94c74c59e2b41e69..ed06c53138da221155adb084fc48d6026938d5ab 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/BUILD.gn @@ -57,6 +57,8 @@ ohos_shared_library("amsDataSystemTestA") { "${innerkits_path}/appexecfwk_core:appexecfwk_core", "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_data_a.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_data_a.cpp index d20ed6adc089dbdbd7289d59c0884e279cbd6362..e930e4b026e83d51e2237a4366e272891719cfe0 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_data_a.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_data_a.cpp @@ -162,7 +162,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_page_a.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_page_a.cpp index 4e78eae2eb880e425b9866caedfa561c76dc5553..83c3d4752a94e4189720e4e0e078f67cc06411d2 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_page_a.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_page_a.cpp @@ -149,7 +149,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/BUILD.gn index 0397152f27eb6d55345a486ae357e1a42e7b7c07..99440ff945f619d3edcbd7eaed9e8251069aa5c0 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/BUILD.gn @@ -56,6 +56,8 @@ ohos_shared_library("amsDataSystemTestB") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_data_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_data_b.cpp index cf5edc7b80c20053227de433639a4aee6b110348..8b0a9509b04186fe70e0d6546f5969b057f1540a 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_data_b.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_data_b.cpp @@ -150,7 +150,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_page_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_page_b.cpp index 2a48fa711c33edbeb643fcb8cbffcff4cc28e75f..5d03834da1ad231a14729e526652568b8093fbaf 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_page_b.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_page_b.cpp @@ -151,7 +151,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/BUILD.gn index 84231830d3a5eaf60aa8044569f6359e82cfc540..84116a2f76d062578358d0c8bb062d639237cdfc 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/BUILD.gn @@ -56,6 +56,8 @@ ohos_shared_library("amsDataSystemTestC") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c1.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c1.cpp index 43a1358dcd0c85aa6637385f89cb60a53c44cf9d..6a71906f6645ab7534036933f4e8460efced6e22 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c1.cpp @@ -149,7 +149,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -187,7 +187,7 @@ void DataTestDataC1EventSubscriber::GetResultBySelf( { if (child->GetOperatorName() == OPERATOR_INSERT) { APP_LOGI("---------------------Insert--------------------"); - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = std::to_string(mainAbility->Insert(dataAbilityUri, bucket)); } else if (child->GetOperatorName() == OPERATOR_DELETE) { APP_LOGI("---------------------Delete--------------------"); @@ -195,7 +195,7 @@ void DataTestDataC1EventSubscriber::GetResultBySelf( result = std::to_string(mainAbility->Delete(dataAbilityUri, predicates)); } else if (child->GetOperatorName() == OPERATOR_UPDATE) { APP_LOGI("---------------------Update--------------------"); - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; AppExecFwk::DataAbilityPredicates predicates; result = std::to_string(mainAbility->Update(dataAbilityUri, bucket, predicates)); } else if (child->GetOperatorName() == OPERATOR_QUERY) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c2.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c2.cpp index 85edd1abbe650fb5ecac4f5c13e65cb9834c5f7c..c8bd58b4382aa152b51ba980fdb7ad4287fa9f11 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c2.cpp @@ -150,7 +150,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/src/kit_test_ability_manager_second.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/src/kit_test_ability_manager_second.cpp index 009b1c10c2a637fd6a655d187ac75b275e0a42bc..d056f2a265c1fee4c1a7c030ee48cdc28fce9f75 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/src/kit_test_ability_manager_second.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/src/kit_test_ability_manager_second.cpp @@ -36,6 +36,8 @@ bool isMoveMissionToTop = false; int moveMissionToTopCode = -1; bool isClearUpApplicationData = false; int clearUpApplicationDataCode = -1; +int numTwo = 2; +int numThree = 3; } // namespace bool KitTestAbilityManagerSecond::PublishEvent(const std::string &eventName, const int &code, const std::string &data) diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/main_ability.h index 268205e3660aff79414556e752ffa3cfc2da0173..ec3e1ed23742f4211ec6b87151860cf7d4313888 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/main_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/main_ability.h @@ -23,7 +23,6 @@ namespace OHOS { namespace AppExecFwk { - class FirstEventSubscriber; class MainAbility : public Ability { public: diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/second_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/second_ability.h index d00a9d128cf4f02f8a300db15061ba6809f58b28..385591ba2615eeb89a4438756a7ec7d2b8517d7b 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/second_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/second_ability.h @@ -1534,7 +1534,6 @@ public: SecondAbility *secondAbility; std::unordered_map> mapTestFunc_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // _AMS_KIT_SYSTEM_TEST_SECOND_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/sixth_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/sixth_ability.h index cafc175ccd93a09b67aa9625a9d51f199a1d66c8..cf145f0a098b859321a56fff020026d90eafd9bd 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/sixth_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/sixth_ability.h @@ -254,7 +254,6 @@ public: private: CallbackCount callbackCount_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // _Six_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/test_utils.h index 741c48789435a96eabc28bd1306749d03209d116..0af55daf4ded4319a4da63849373fcf9ba3d4b03 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/test_utils.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/test_utils.h @@ -34,9 +34,6 @@ public: static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, std::map params); - static std::string ApplicationInfoToString(std::shared_ptr applicationInfo); - static std::string AbilityInfoToString(std::shared_ptr abilityInfo); - static std::string ProcessInfoToString(std::shared_ptr processInfo); static std::vector split(const std::string &in, const std::string &delim); }; } // namespace AppExecFwk diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/third_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/third_ability.h index 4ce2399a1f747b1b199b72eeb1933df24f9af30a..f83e7bb013421d718a97b190d761cc8ca85cddad 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/third_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/third_ability.h @@ -162,7 +162,6 @@ public: private: std::unordered_map> mapTestFunc_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // _THIRD_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp index 13294bba9686516da807451d333719e798d2de54..a2a1df81f8b7247901bdde73a7256a4830afb7e4 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp @@ -248,7 +248,7 @@ void FifthAbility::WantParamsSetParamCase9(int code) TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); } -template +template static void SetArray(const InterfaceID &id, const std::vector &value, sptr &ao) { typename std::vector::size_type size = value.size(); @@ -258,7 +258,7 @@ static void SetArray(const InterfaceID &id, const std::vector &value, sptr +template static void FillArray(IArray *ao, std::vector &array) { auto func = [&](IInterface *object) { array.push_back(T2::Unbox(T3::Query(object))); }; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fourth_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fourth_ability.cpp index 9a17782414b37c68978c09626939de7c343c109c..c1054ae2265aa4ba65513975bd8d069a500c923f 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fourth_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fourth_ability.cpp @@ -34,7 +34,6 @@ namespace AppExecFwk { using namespace OHOS::EventFwk; using namespace OHOS::AAFwk; namespace { - const std::string normalString = "kitapp.system.test"; // Special string const std::string specialString = "@#¥#//\\%&*_=+[]^:!~();,.'?3243adsafdf_中文"; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/kit_test_ability_manager.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/kit_test_ability_manager.cpp index 121c03c7696bb58beb078f251156ce2ff66f2ad4..484d0c62b7a7468b0c416d5aa328f957d8e71495 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/kit_test_ability_manager.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/kit_test_ability_manager.cpp @@ -21,10 +21,8 @@ namespace OHOS { namespace AppExecFwk { - using namespace OHOS::EventFwk; using namespace OHOS::AAFwk; - namespace { const std::string bundleName = "com.ohos.amsst.AppKitAbilityManager"; const std::string abilityName = "KitTestAbilityManagerSecond"; @@ -35,6 +33,7 @@ const std::string launchProcessInfo = "com.ix.launcher"; bool isMoveMissionToTop = false; int moveMissionToTopCode = -1; int isClearUpApplicationData = false; +int numThree = 3; } // namespace void KitTestAbilityManager::SubscribeEvent(const vector_conststr &eventList) @@ -534,8 +533,8 @@ void KitTestAbilityManager::OnBackground() Ability::OnBackground(); if (isMoveMissionToTop) { std::vector info; - info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(3, RECENT_WITH_EXCLUDED); - if (1 == info.size() && 1 == info[0].size) { + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); + if (info.size() == 1 && info[0].size == 1) { GetAbilityManager()->MoveMissionToTop(info[0].id); } } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/main_ability.cpp index 8847d2be14333c1638ae5c070a5f2d6ccc844bc9..cfd54c7116f9ef39a5078997851729a45e407011 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/main_ability.cpp @@ -162,7 +162,6 @@ void MainAbility::GetAbilityPackageCase1(int code) // get want from empty Want void MainAbility::GetWantCase1(int code) { - Want want; auto getWant = Ability::GetWant(); bool result = getWant == nullptr; TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); @@ -172,7 +171,6 @@ void MainAbility::GetWantCase1(int code) void MainAbility::GetWantCase2(int code) { std::string action = "action"; - Want want; Want setWant; setWant.SetAction(action); Ability::SetWant(setWant); @@ -184,7 +182,6 @@ void MainAbility::GetWantCase2(int code) void MainAbility::GetWantCase3(int code) { std::string action = "action"; - Want want; bool result = true; std::string tmpAction; for (int i = 0; i < pressureTimes; i++) { @@ -217,7 +214,6 @@ void MainAbility::DumpCase1(int code) void MainAbility::SetWantCase1(int code) { std::string empty; - Want want; Want setWant; Ability::SetWant(setWant); bool result = Ability::GetWant()->GetAction() == empty; @@ -228,7 +224,6 @@ void MainAbility::SetWantCase1(int code) void MainAbility::SetWantCase2(int code) { std::string action = "action"; - Want want; std::string tmpAction; for (int i = 0; i < pressureTimes; i++) { Want setWant; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp index 1955898e7d234c620a4a4ed20d354f4b80f5fec4..2f2a3710e19377507e3536aef93df5de7fcfe9d2 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp @@ -35,7 +35,7 @@ namespace OHOS { namespace AppExecFwk { using namespace AAFwk; using namespace OHOS::EventFwk; - +namespace { constexpr size_t ARRAY_SIZE = 10000; constexpr int LARGE_STR_LEN = 65534; constexpr int SMALL_INT = 5; @@ -46,6 +46,7 @@ constexpr int even = 2; constexpr int index_f = 0; constexpr int index_s = 1; constexpr int index_t = 2; +} bool SecondAbility::CompareWantNoParams(const Want &source, const Want &target) { @@ -1293,7 +1294,7 @@ void SecondAbility::WantRemoveEntityCase2(int code) void SecondAbility::WantRemoveEntityCase3(int code) { Want want; - std::vector entities{"entity1", "entity2", "entity3"}; + std::vector entities {"entity1", "entity2", "entity3"}; bool result = true; for (const auto &entity : entities) { want.AddEntity(entity); @@ -1945,7 +1946,7 @@ void SecondAbility::WantParseUriCase23(int code) bool result = (want != nullptr); if (want != nullptr) { auto parsedValue = want->GetStringArrayParam(key); - result = result && (parsedValue == (std::vector{"aa", "bb", "cc"})); + result = result && (parsedValue == (std::vector {"aa", "bb", "cc"})); delete want; } TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); @@ -5142,24 +5143,24 @@ void SecondAbility::WantOperationEqualsCase2(int code) OperationBuilder opBuilder; std::vector vec = {"entities1", "entities2"}; auto operation = opBuilder.WithAbilityName("abilityName") - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .WithEntities(vec) - .WithFlags(1) - .WithUri(Uri("uri")) - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .WithEntities(vec) + .WithFlags(1) + .WithUri(Uri("uri")) + .build(); Want wantOne; wantOne.SetOperation(*operation); OperationBuilder opBuilderTwo; auto operationTwo = opBuilderTwo.WithAbilityName("abilityName2") - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .WithEntities(vec) - .WithFlags(1) - .WithUri(Uri("uri")) - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .WithEntities(vec) + .WithFlags(1) + .WithUri(Uri("uri")) + .build(); Want wantTwo; wantTwo.SetOperation(*operationTwo); bool result = !wantOne.OperationEquals(wantTwo); @@ -5171,18 +5172,18 @@ void SecondAbility::WantOperationEqualsCase3(int code) { OperationBuilder opBuilder; auto operation = opBuilder.WithAbilityName("abilityName") - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); Want wantOne; wantOne.SetOperation(*operation); OperationBuilder opBuilderTwo; auto operationTwo = opBuilderTwo.WithAbilityName("abilityName") - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); Want wantTwo; wantTwo.SetOperation(*operationTwo); bool result = wantOne.OperationEquals(wantTwo); @@ -5194,10 +5195,10 @@ void SecondAbility::WantOperationEqualsCase4(int code) { OperationBuilder opBuilder; auto operation = opBuilder.WithAbilityName("abilityName" + std::to_string(pressureTimes - 1)) - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); Want wantOne; wantOne.SetOperation(*operation); Want wantTwo; @@ -5206,10 +5207,10 @@ void SecondAbility::WantOperationEqualsCase4(int code) bool result = true; for (int i = 0; i < pressureTimes; i++) { operationTwo = opBuilderTwo.WithAbilityName("abilityName" + std::to_string(i)) - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); wantTwo.SetOperation(*operationTwo); if (i == pressureTimes - 1) { result = result && wantOne.OperationEquals(wantTwo); @@ -5238,10 +5239,10 @@ void SecondAbility::WantCloneOperationCase2(int code) { OperationBuilder opBuilder; auto operation = opBuilder.WithAbilityName("abilityName") - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); Want want; want.SetOperation(*operation); Want *wantClone = want.CloneOperation(); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/sixth_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/sixth_ability.cpp index 4b61a8c75357304e0ce910ff4aea54f85d97d546..e47f52510313182dac419e7c7eb224ab34391b03 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/sixth_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/sixth_ability.cpp @@ -26,6 +26,8 @@ using namespace OHOS::EventFwk; namespace { const int cycleCount = 1000; +const int paramCnt = 3; +const int caseIndx = 2; } // namespace #define APPREGISTERABILITYLIFECYCALLBACK(onAbilityFunctionName, getAbilityCountFunction, expected, code) \ @@ -466,9 +468,9 @@ void KitTestSixEventSubscriber::OnReceiveEvent(const CommonEventData &data) auto target = data.GetData(); vector_str splitResult = TestUtils::split(target, "_"); auto keyMap = splitResult.at(0); - if (mapTestFunc_.find(keyMap) != mapTestFunc_.end() && splitResult.size() >= 3) { + if (mapTestFunc_.find(keyMap) != mapTestFunc_.end() && splitResult.size() >= paramCnt) { auto apiIndex = atoi(splitResult.at(1).c_str()); - auto caseIndex = atoi(splitResult.at(2).c_str()); + auto caseIndex = atoi(splitResult.at(caseIndx).c_str()); mapTestFunc_[keyMap](apiIndex, caseIndex, data.GetCode()); } else { if (keyMap == "TerminateAbility") { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/test_utils.cpp index b9d744c1e6d8458333507c763ca7ce47487e382d..1f7fa556737647aecddbe3a8190286ad772fbb23 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/test_utils.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/test_utils.cpp @@ -45,85 +45,12 @@ Want TestUtils::MakeWant( return want; } -std::string TestUtils::ApplicationInfoToString(std::shared_ptr applicationInfo) -{ - std::stringstream sstream; - sstream << "name:" << applicationInfo->name << ","; - sstream << "bundleName:" << applicationInfo->bundleName << ","; - sstream << "description:" << applicationInfo->description << ","; - sstream << "iconPath:" << applicationInfo->iconPath << ","; - sstream << "label:" << applicationInfo->label << ","; - sstream << "deviceId:" << applicationInfo->deviceId << ","; - sstream << "signatureKey:" << applicationInfo->signatureKey << ","; - sstream << "isSystemApp:" << std::boolalpha << applicationInfo->isSystemApp << ","; - sstream << "isLauncherApp:" << applicationInfo->isLauncherApp << ","; - sstream << "supportedModes:" << applicationInfo->supportedModes << ","; - sstream << "process:" << applicationInfo->process << ","; - std::string permissions = - std::accumulate(applicationInfo->permissions.begin(), applicationInfo->permissions.end(), std::string(",")); - sstream << "permissions:" << permissions << ","; - std::string moduleSourceDirs = std::accumulate( - applicationInfo->moduleSourceDirs.begin(), applicationInfo->moduleSourceDirs.end(), std::string(",")); - sstream << "moduleSourceDirs:" << moduleSourceDirs << ","; - sstream << "entryDir:" << applicationInfo->entryDir << ","; - sstream << "codePath:" << applicationInfo->codePath << ","; - sstream << "dataDir:" << applicationInfo->dataDir << ","; - sstream << "dataBaseDir:" << applicationInfo->dataBaseDir << ","; - sstream << "cacheDir:" << applicationInfo->cacheDir; - return sstream.str(); -} - -std::string TestUtils::AbilityInfoToString(std::shared_ptr abilityInfo) -{ - std::stringstream sstream; - sstream << "name:" << abilityInfo->name << ","; - sstream << "label:" << abilityInfo->label << ","; - sstream << "description:" << abilityInfo->description << ","; - sstream << "iconPath:" << abilityInfo->iconPath << ","; - sstream << "visible:" << std::boolalpha << abilityInfo->visible << ","; - sstream << "kind:" << abilityInfo->kind << ","; - auto type = static_cast::type>(abilityInfo->type); - sstream << "type:" << type << ","; - auto orientation = - static_cast::type>(abilityInfo->orientation); - sstream << "orientation:" << orientation << ","; - auto launchMode = static_cast::type>(abilityInfo->launchMode); - sstream << "launchMode:" << launchMode << ","; - std::string permissions = - std::accumulate(abilityInfo->permissions.begin(), abilityInfo->permissions.end(), std::string(",")); - sstream << "permissions:" << permissions << ","; - sstream << "process:" << abilityInfo->process << ","; - std::string deviceTypes = - std::accumulate(abilityInfo->deviceTypes.begin(), abilityInfo->deviceTypes.end(), std::string(",")); - sstream << "deviceTypes:" << deviceTypes << ","; - std::string deviceCapabilities = std::accumulate( - abilityInfo->deviceCapabilities.begin(), abilityInfo->deviceCapabilities.end(), std::string(",")); - sstream << "deviceCapabilities:" << deviceCapabilities << ","; - sstream << "uri:" << abilityInfo->uri << ","; - sstream << "package:" << abilityInfo->package << ","; - sstream << "bundleName:" << abilityInfo->bundleName << ","; - sstream << "moduleName:" << abilityInfo->moduleName << ","; - sstream << "applicationName:" << abilityInfo->applicationName << ","; - sstream << "deviceId:" << abilityInfo->deviceId << ","; - sstream << "codePath:" << abilityInfo->codePath << ","; - sstream << "resourcePath:" << abilityInfo->resourcePath << ","; - sstream << "libPath:" << abilityInfo->libPath; - return sstream.str(); -} - -std::string TestUtils::ProcessInfoToString(std::shared_ptr processInfo) -{ - std::stringstream sstream; - sstream << "pid:" << processInfo->GetPid() << ","; - sstream << "processName:" << processInfo->GetProcessName(); - return sstream.str(); -} - std::vector TestUtils::split(const std::string &in, const std::string &delim) { std::regex reg(delim); std::vector res = { - std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator()}; + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() + }; return res; } } // namespace AppExecFwk diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/main_ability.h index f77383f16b8aca1809e2c3573e09ace3dff92cfc..cec4a093d9e97579b656e85fec1e7c5a6788c0d6 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/main_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/main_ability.h @@ -113,9 +113,11 @@ public: void GetApplicationContextCase1(int code); - MainAbility() - { - mapCase_ = { + std::unordered_map>> mapCase_; + ~MainAbility(); + + void initCaseFirst() { + std::unordered_map>> first = { {(int)AbilityContextApi::GetApplicationInfo, { [this](int code) { GetApplicationInfoCase1(code); }, @@ -146,6 +148,12 @@ public: [this](int code) { GetDataDirCase2(code); }, [this](int code) { GetDataDirCase3(code); }, }}, + }; + mapCase_.insert(first.begin(), first.end()); + } + + void initCaseSecond() { + std::unordered_map>> second = { {(int)AbilityContextApi::GetDir, { [this](int code) { GetDirCase1(code); }, @@ -188,6 +196,12 @@ public: { [this](int code) { GetContextCase1(code); }, }}, + }; + mapCase_.insert(second.begin(), second.end()); + } + + void initCaseThird() { + std::unordered_map>> third = { {(int)AbilityContextApi::GetAbilityManager, { [this](int code) { GetAbilityManagerCase1(code); }, @@ -232,10 +246,15 @@ public: [this](int code) { GetHapModuleInfoCase3(code); }, }}, }; + mapCase_.insert(third.begin(), third.end()); } - std::unordered_map>> mapCase_; - ~MainAbility(); + MainAbility() + { + initCaseFirst(); + initCaseSecond(); + initCaseThird(); + } protected: void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/second_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/second_ability.h index 2070529579d563e5202623790d100cd374851610..aa64ae6499c1fbfeda7139581bbf41881f315aca 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/second_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/second_ability.h @@ -115,7 +115,13 @@ public: SecondAbility() { - mapCase_ = { + initCaseFirst(); + initCaseSecond(); + initCaseThird(); + } + + void initCaseFirst() { + std::unordered_map>> first = { {(int)AbilityContextApi::GetApplicationInfo, { [this](int code) { GetApplicationInfoCase1(code); }, @@ -146,12 +152,12 @@ public: [this](int code) { GetDataDirCase2(code); }, [this](int code) { GetDataDirCase3(code); }, }}, - {(int)AbilityContextApi::GetDir, - { - [this](int code) { GetDirCase1(code); }, - [this](int code) { GetDirCase2(code); }, - [this](int code) { GetDirCase3(code); }, - }}, + }; + mapCase_.insert(first.begin(), first.end()); + } + + void initCaseSecond() { + std::unordered_map>> second = { {(int)AbilityContextApi::GetBundleManager, { [this](int code) { GetBundleManagerCase1(code); }, @@ -188,6 +194,12 @@ public: { [this](int code) { GetContextCase1(code); }, }}, + }; + mapCase_.insert(second.begin(), second.end()); + } + + void initCaseThird() { + std::unordered_map>> third = { {(int)AbilityContextApi::GetAbilityManager, { [this](int code) { GetAbilityManagerCase1(code); }, @@ -232,8 +244,8 @@ public: [this](int code) { GetHapModuleInfoCase3(code); }, }}, }; + mapCase_.insert(third.begin(), third.end()); } - std::unordered_map>> mapCase_; int callingTime = 0; ~SecondAbility(); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/test_utils.h index 8d2303da0503acfcbbc8b45d187b11003da431b9..64b40f888ec52c9ea73da85d972d20bc734ad447 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/test_utils.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/test_utils.h @@ -34,9 +34,6 @@ public: static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, std::map params); - static std::string ApplicationInfoToString(std::shared_ptr applicationInfo); - static std::string AbilityInfoToString(std::shared_ptr abilityInfo); - static std::string ProcessInfoToString(std::shared_ptr processInfo); static std::vector split(const std::string &in, const std::string &delim); }; } // namespace AppExecFwk diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/main_ability.cpp index a4f3df5d30f4137f0d0c29a4e009327afb472098..241f5a44d2d365ad3eb31f4e323afae00b6bb164 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/main_ability.cpp @@ -20,8 +20,13 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; - +namespace { const int MainAbilityACode = 100; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +constexpr int numThree = 3; +} void MainAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -126,11 +131,11 @@ void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (std::strcmp(eventName.c_str(), g_EVENT_REQU_FIRST.c_str()) == 0) { auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); - if (caseInfo.size() < 3) { + if (caseInfo.size() < numThree) { return; } - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } @@ -150,10 +155,8 @@ void MainAbility::TestAbility(int apiIndex, int caseIndex, int code) void MainAbility::GetApplicationInfoCase1(int code) { auto appInfo = AbilityContext::GetApplicationInfo(); - string appInfoStr = ""; string result = ""; if (appInfo != nullptr) { - appInfoStr = TestUtils::ApplicationInfoToString(appInfo); result = appInfo->name; } @@ -162,10 +165,8 @@ void MainAbility::GetApplicationInfoCase1(int code) void MainAbility::GetApplicationInfoCase2(int code) { auto appInfo = AbilityContext::GetApplicationInfo(); - string appInfoStr = ""; string result = ""; if (appInfo != nullptr) { - appInfoStr = TestUtils::ApplicationInfoToString(appInfo); result = appInfo->name; } @@ -174,10 +175,8 @@ void MainAbility::GetApplicationInfoCase2(int code) void MainAbility::GetApplicationInfoCase3(int code) { auto appInfo = AbilityContext::GetApplicationInfo(); - string appInfoStr = ""; string result = ""; if (appInfo != nullptr) { - appInfoStr = TestUtils::ApplicationInfoToString(appInfo); result = appInfo->name; } @@ -392,10 +391,8 @@ void MainAbility::GetAbilityManagerCase1(int code) void MainAbility::GetProcessInfoCase1(int code) { auto processInfo = AbilityContext::GetProcessInfo(); - string processInfoStr = ""; string result = ""; if (processInfo != nullptr) { - processInfoStr = TestUtils::ProcessInfoToString(processInfo); result = processInfo->GetProcessName(); } @@ -405,10 +402,8 @@ void MainAbility::GetProcessInfoCase1(int code) void MainAbility::GetProcessInfoCase2(int code) { auto processInfo = AbilityContext::GetProcessInfo(); - string processInfoStr = ""; string result = ""; if (processInfo != nullptr) { - processInfoStr = TestUtils::ProcessInfoToString(processInfo); result = processInfo->GetProcessName(); } @@ -418,10 +413,8 @@ void MainAbility::GetProcessInfoCase2(int code) void MainAbility::GetProcessInfoCase3(int code) { auto processInfo = AbilityContext::GetProcessInfo(); - string processInfoStr = ""; string result = ""; if (processInfo != nullptr) { - processInfoStr = TestUtils::ProcessInfoToString(processInfo); result = processInfo->GetProcessName(); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/second_ability.cpp index 775f91de81484de99ad075cd034e7c56464fa541..70aa48177ed9dcee0083fe94206c63455d30d707 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/second_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/second_ability.cpp @@ -20,8 +20,13 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; - +namespace { const int SecondAbilityACode = 200; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +constexpr int numThree = 3; +} void SecondAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -126,11 +131,11 @@ void SecondEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (std::strcmp(eventName.c_str(), g_EVENT_REQU_SECOND.c_str()) == 0) { auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); - if (caseInfo.size() < 3) { + if (caseInfo.size() < numThree) { return; } - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } @@ -152,10 +157,8 @@ void SecondAbility::GetApplicationInfoCase1(int code) void SecondAbility::GetApplicationInfoCase2(int code) { auto appInfo = AbilityContext::GetApplicationInfo(); - string appInfoStr = ""; string result = ""; if (appInfo != nullptr) { - appInfoStr = TestUtils::ApplicationInfoToString(appInfo); result = appInfo->name; } @@ -305,10 +308,8 @@ void SecondAbility::GetProcessInfoCase1(int code) void SecondAbility::GetProcessInfoCase2(int code) { auto processInfo = AbilityContext::GetProcessInfo(); - string processInfoStr = ""; string result = ""; if (processInfo != nullptr) { - processInfoStr = TestUtils::ProcessInfoToString(processInfo); result = processInfo->GetProcessName(); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/test_utils.cpp index 48a7ea6b0e9e382b37cda3da859643a0f2928093..3e75bdf815379f71af430ad9d5c979da62400675 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/test_utils.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/test_utils.cpp @@ -45,85 +45,12 @@ Want TestUtils::MakeWant( return want; } -std::string TestUtils::ApplicationInfoToString(std::shared_ptr applicationInfo) -{ - std::stringstream sstream; - sstream << "name:" << applicationInfo->name << ","; - sstream << "bundleName:" << applicationInfo->bundleName << ","; - sstream << "description:" << applicationInfo->description << ","; - sstream << "iconPath:" << applicationInfo->iconPath << ","; - sstream << "label:" << applicationInfo->label << ","; - sstream << "deviceId:" << applicationInfo->deviceId << ","; - sstream << "signatureKey:" << applicationInfo->signatureKey << ","; - sstream << "isSystemApp:" << std::boolalpha << applicationInfo->isSystemApp << ","; - sstream << "isLauncherApp:" << applicationInfo->isLauncherApp << ","; - sstream << "supportedModes:" << applicationInfo->supportedModes << ","; - sstream << "process:" << applicationInfo->process << ","; - std::string permissions = - std::accumulate(applicationInfo->permissions.begin(), applicationInfo->permissions.end(), std::string(",")); - sstream << "permissions:" << permissions << ","; - std::string moduleSourceDirs = std::accumulate( - applicationInfo->moduleSourceDirs.begin(), applicationInfo->moduleSourceDirs.end(), std::string(",")); - sstream << "moduleSourceDirs:" << moduleSourceDirs << ","; - sstream << "entryDir:" << applicationInfo->entryDir << ","; - sstream << "codePath:" << applicationInfo->codePath << ","; - sstream << "dataDir:" << applicationInfo->dataDir << ","; - sstream << "dataBaseDir:" << applicationInfo->dataBaseDir << ","; - sstream << "cacheDir:" << applicationInfo->cacheDir; - return sstream.str(); -} - -std::string TestUtils::AbilityInfoToString(std::shared_ptr abilityInfo) -{ - std::stringstream sstream; - sstream << "name:" << abilityInfo->name << ","; - sstream << "label:" << abilityInfo->label << ","; - sstream << "description:" << abilityInfo->description << ","; - sstream << "iconPath:" << abilityInfo->iconPath << ","; - sstream << "visible:" << std::boolalpha << abilityInfo->visible << ","; - sstream << "kind:" << abilityInfo->kind << ","; - auto type = static_cast::type>(abilityInfo->type); - sstream << "type:" << type << ","; - auto orientation = - static_cast::type>(abilityInfo->orientation); - sstream << "orientation:" << orientation << ","; - auto launchMode = static_cast::type>(abilityInfo->launchMode); - sstream << "launchMode:" << launchMode << ","; - std::string permissions = - std::accumulate(abilityInfo->permissions.begin(), abilityInfo->permissions.end(), std::string(",")); - sstream << "permissions:" << permissions << ","; - sstream << "process:" << abilityInfo->process << ","; - std::string deviceTypes = - std::accumulate(abilityInfo->deviceTypes.begin(), abilityInfo->deviceTypes.end(), std::string(",")); - sstream << "deviceTypes:" << deviceTypes << ","; - std::string deviceCapabilities = std::accumulate( - abilityInfo->deviceCapabilities.begin(), abilityInfo->deviceCapabilities.end(), std::string(",")); - sstream << "deviceCapabilities:" << deviceCapabilities << ","; - sstream << "uri:" << abilityInfo->uri << ","; - sstream << "package:" << abilityInfo->package << ","; - sstream << "bundleName:" << abilityInfo->bundleName << ","; - sstream << "moduleName:" << abilityInfo->moduleName << ","; - sstream << "applicationName:" << abilityInfo->applicationName << ","; - sstream << "deviceId:" << abilityInfo->deviceId << ","; - sstream << "codePath:" << abilityInfo->codePath << ","; - sstream << "resourcePath:" << abilityInfo->resourcePath << ","; - sstream << "libPath:" << abilityInfo->libPath; - return sstream.str(); -} - -std::string TestUtils::ProcessInfoToString(std::shared_ptr processInfo) -{ - std::stringstream sstream; - sstream << "pid:" << processInfo->GetPid() << ","; - sstream << "processName:" << processInfo->GetProcessName(); - return sstream.str(); -} - std::vector TestUtils::split(const std::string &in, const std::string &delim) { - std::regex reg{delim}; - return std::vector{ - std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator()}; + std::regex reg {delim}; + return std::vector { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() + }; } } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/main_ability.h index a14c52c2f06a74ba810052457e9dfa8e9bd34477..b68fb8b68e98a7f228740a8d63dd1791fd6ae511 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/main_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/main_ability.h @@ -112,7 +112,14 @@ public: MainAbility() { - mapCase_ = { + initCaseFirst(); + initCaseSecond(); + initCaseThird(); + } + + void initCaseFirst() + { + std::unordered_map>> testCase = { {(int)AbilityContextApi::GetApplicationInfo, { [this](int code) { GetApplicationInfoCase1(code); }, @@ -143,6 +150,13 @@ public: [this](int code) { GetDataDirCase2(code); }, [this](int code) { GetDataDirCase3(code); }, }}, + }; + mapCase_.insert(testCase.begin(), testCase.end()); + } + + void initCaseSecond() + { + std::unordered_map>> testCase = { {(int)AbilityContextApi::GetDir, { [this](int code) { GetDirCase1(code); }, @@ -185,6 +199,13 @@ public: { [this](int code) { GetContextCase1(code); }, }}, + }; + mapCase_.insert(testCase.begin(), testCase.end()); + } + + void initCaseThird() + { + std::unordered_map>> testCase = { {(int)AbilityContextApi::GetAbilityManager, { [this](int code) { GetAbilityManagerCase1(code); }, @@ -229,6 +250,7 @@ public: [this](int code) { GetHapModuleInfoCase3(code); }, }}, }; + mapCase_.insert(testCase.begin(), testCase.end()); } void SubscribeEvent(); void TestAbility(int apiIndex, int caseIndex, int code); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/test_utils.h index 8d2303da0503acfcbbc8b45d187b11003da431b9..64b40f888ec52c9ea73da85d972d20bc734ad447 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/test_utils.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/test_utils.h @@ -34,9 +34,6 @@ public: static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, std::map params); - static std::string ApplicationInfoToString(std::shared_ptr applicationInfo); - static std::string AbilityInfoToString(std::shared_ptr abilityInfo); - static std::string ProcessInfoToString(std::shared_ptr processInfo); static std::vector split(const std::string &in, const std::string &delim); }; } // namespace AppExecFwk diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/main_ability.cpp index aa08cabf14c914211188697cd65e00572460f8ea..c2411fd614d05c2998f280ec91b46e92bf1fd754 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/main_ability.cpp @@ -20,8 +20,13 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; - +namespace { const int MainAbilityBCode = 300; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +constexpr int numThree = 3; +} void MainAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -126,11 +131,11 @@ void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (std::strcmp(eventName.c_str(), g_EVENT_REQU_FIRSTB.c_str()) == 0) { auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); - if (caseInfo.size() < 3) { + if (caseInfo.size() < numThree) { return; } - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } @@ -158,10 +163,8 @@ void MainAbility::GetApplicationInfoCase2(int code) void MainAbility::GetApplicationInfoCase3(int code) { auto appInfo = AbilityContext::GetApplicationInfo(); - string appInfoStr = ""; string result = ""; if (appInfo != nullptr) { - appInfoStr = TestUtils::ApplicationInfoToString(appInfo); result = appInfo->name; } @@ -357,10 +360,8 @@ void MainAbility::GetProcessInfoCase2(int code) void MainAbility::GetProcessInfoCase3(int code) { auto processInfo = AbilityContext::GetProcessInfo(); - string processInfoStr = ""; string result = ""; if (processInfo != nullptr) { - processInfoStr = TestUtils::ProcessInfoToString(processInfo); result = processInfo->GetProcessName(); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/test_utils.cpp index 48a7ea6b0e9e382b37cda3da859643a0f2928093..07ebf00c47128276f0e83d0aa5783fec0a417147 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/test_utils.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/test_utils.cpp @@ -45,80 +45,6 @@ Want TestUtils::MakeWant( return want; } -std::string TestUtils::ApplicationInfoToString(std::shared_ptr applicationInfo) -{ - std::stringstream sstream; - sstream << "name:" << applicationInfo->name << ","; - sstream << "bundleName:" << applicationInfo->bundleName << ","; - sstream << "description:" << applicationInfo->description << ","; - sstream << "iconPath:" << applicationInfo->iconPath << ","; - sstream << "label:" << applicationInfo->label << ","; - sstream << "deviceId:" << applicationInfo->deviceId << ","; - sstream << "signatureKey:" << applicationInfo->signatureKey << ","; - sstream << "isSystemApp:" << std::boolalpha << applicationInfo->isSystemApp << ","; - sstream << "isLauncherApp:" << applicationInfo->isLauncherApp << ","; - sstream << "supportedModes:" << applicationInfo->supportedModes << ","; - sstream << "process:" << applicationInfo->process << ","; - std::string permissions = - std::accumulate(applicationInfo->permissions.begin(), applicationInfo->permissions.end(), std::string(",")); - sstream << "permissions:" << permissions << ","; - std::string moduleSourceDirs = std::accumulate( - applicationInfo->moduleSourceDirs.begin(), applicationInfo->moduleSourceDirs.end(), std::string(",")); - sstream << "moduleSourceDirs:" << moduleSourceDirs << ","; - sstream << "entryDir:" << applicationInfo->entryDir << ","; - sstream << "codePath:" << applicationInfo->codePath << ","; - sstream << "dataDir:" << applicationInfo->dataDir << ","; - sstream << "dataBaseDir:" << applicationInfo->dataBaseDir << ","; - sstream << "cacheDir:" << applicationInfo->cacheDir; - return sstream.str(); -} - -std::string TestUtils::AbilityInfoToString(std::shared_ptr abilityInfo) -{ - std::stringstream sstream; - sstream << "name:" << abilityInfo->name << ","; - sstream << "label:" << abilityInfo->label << ","; - sstream << "description:" << abilityInfo->description << ","; - sstream << "iconPath:" << abilityInfo->iconPath << ","; - sstream << "visible:" << std::boolalpha << abilityInfo->visible << ","; - sstream << "kind:" << abilityInfo->kind << ","; - auto type = static_cast::type>(abilityInfo->type); - sstream << "type:" << type << ","; - auto orientation = - static_cast::type>(abilityInfo->orientation); - sstream << "orientation:" << orientation << ","; - auto launchMode = static_cast::type>(abilityInfo->launchMode); - sstream << "launchMode:" << launchMode << ","; - std::string permissions = - std::accumulate(abilityInfo->permissions.begin(), abilityInfo->permissions.end(), std::string(",")); - sstream << "permissions:" << permissions << ","; - sstream << "process:" << abilityInfo->process << ","; - std::string deviceTypes = - std::accumulate(abilityInfo->deviceTypes.begin(), abilityInfo->deviceTypes.end(), std::string(",")); - sstream << "deviceTypes:" << deviceTypes << ","; - std::string deviceCapabilities = std::accumulate( - abilityInfo->deviceCapabilities.begin(), abilityInfo->deviceCapabilities.end(), std::string(",")); - sstream << "deviceCapabilities:" << deviceCapabilities << ","; - sstream << "uri:" << abilityInfo->uri << ","; - sstream << "package:" << abilityInfo->package << ","; - sstream << "bundleName:" << abilityInfo->bundleName << ","; - sstream << "moduleName:" << abilityInfo->moduleName << ","; - sstream << "applicationName:" << abilityInfo->applicationName << ","; - sstream << "deviceId:" << abilityInfo->deviceId << ","; - sstream << "codePath:" << abilityInfo->codePath << ","; - sstream << "resourcePath:" << abilityInfo->resourcePath << ","; - sstream << "libPath:" << abilityInfo->libPath; - return sstream.str(); -} - -std::string TestUtils::ProcessInfoToString(std::shared_ptr processInfo) -{ - std::stringstream sstream; - sstream << "pid:" << processInfo->GetPid() << ","; - sstream << "processName:" << processInfo->GetProcessName(); - return sstream.str(); -} - std::vector TestUtils::split(const std::string &in, const std::string &delim) { std::regex reg{delim}; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/BUILD.gn index be5a60832a5414c421b41a781a3742cc1bb7749a..a93204d5740e197743574aa84e5ecb10dda1976b 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/BUILD.gn @@ -60,6 +60,8 @@ ohos_shared_library("amsKitSystemTestDataA") { "${innerkits_path}/appexecfwk_core:appexecfwk_core", "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a1.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a1.cpp index 90924e5db44ca23ef89a24dfbd4392df256bdf9f..e90d848cc0386fbd33bd62b962fdd4b741755be2 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a1.cpp @@ -23,6 +23,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_DATA_CODE = 250; static const int LIFECYCLE_CALLBACKS = 251; static const int LIFECYCLE_OBSERVER = 252; @@ -40,6 +41,8 @@ static const int DEFAULT_DELETE_RESULT = 2222; static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} void AmsStKitDataAbilityDataA1LifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) { @@ -299,7 +302,7 @@ std::vector AmsStKitDataAbilityDataA1::GetFileTypes(const Uri &uri, { APP_LOGI("AmsStKitDataAbilityDataA1 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "GetFileTypes"); - std::vector fileType{"filetypes"}; + std::vector fileType {"filetypes"}; return fileType; } @@ -335,7 +338,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt AmsStKitDataAbilityDataA1 *mainAbility, Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -360,9 +363,10 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; - if (!feof(file)) - fgets(str, 5, file); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -380,7 +384,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestDataA1EventSubscriber::TestPost(const std::string funName) { - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a2.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a2.cpp index b7fa06d391523f02b905b0e13c7989c4c8f69f39..a55f0cb723f234e70101ad6536be81d7501a1e35 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a2.cpp @@ -23,6 +23,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_DATA_CODE = 260; static const int LIFECYCLE_CALLBACKS = 261; static const int LIFECYCLE_OBSERVER = 262; @@ -38,6 +39,8 @@ static const int DEFAULT_DELETE_RESULT = 2222; static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} void AmsStKitDataAbilityDataA2LifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) { @@ -296,7 +299,7 @@ std::vector AmsStKitDataAbilityDataA2::GetFileTypes(const Uri &uri, { APP_LOGI("AmsStKitDataAbilityDataA2 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "GetFileTypes"); - std::vector fileType{"filetypes"}; + std::vector fileType {"filetypes"}; return fileType; } @@ -334,7 +337,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt AmsStKitDataAbilityDataA2 *mainAbility, Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -359,9 +362,10 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; - if (!feof(file)) - fgets(str, 5, file); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -372,7 +376,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestDataA2EventSubscriber::TestPost(const std::string funName) { - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a3.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a3.cpp index a56dcf79f7d80b4aeaa4e023d9fcc2f60b7c13e3..db581024b182303dc63b123876ad03ea8a5e47bc 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a3.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a3.cpp @@ -23,6 +23,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_DATA_CODE = 290; static const int LIFECYCLE_CALLBACKS = 291; static const int LIFECYCLE_OBSERVER = 292; @@ -38,6 +39,8 @@ static const int DEFAULT_DELETE_RESULT = 2222; static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} void AmsStKitDataAbilityDataA3LifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) { @@ -299,7 +302,7 @@ std::vector AmsStKitDataAbilityDataA3::GetFileTypes(const Uri &uri, { APP_LOGI("AmsStKitDataAbilityDataA3 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "GetFileTypes"); - std::vector fileType{"filetypes"}; + std::vector fileType {"filetypes"}; return fileType; } @@ -337,7 +340,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt AmsStKitDataAbilityDataA3 *mainAbility, Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -362,9 +365,10 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; - if (!feof(file)) - fgets(str, 5, file); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -375,7 +379,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestDataA3EventSubscriber::TestPost(const std::string funName) { - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_page_a.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_page_a.cpp index 68c42c58f06ba15bfd89f1e044427915605b60b1..d10c3ddf77d4138b487b4b8cbb6a839af782e7e0 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_page_a.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_page_a.cpp @@ -26,6 +26,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_PAGE_CODE = 130; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -34,6 +35,8 @@ static const std::string OPERATOR_QUERY = "Query"; static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; static const std::string OPERATOR_OPENFILE = "OpenFile"; static const std::string OPERATOR_GETTYPE = "GetType"; +constexpr int charCnt = 5; +} bool AmsStKitDataAbilityPageA::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -70,7 +73,7 @@ AmsStKitDataAbilityPageA::~AmsStKitDataAbilityPageA() void AmsStKitDataAbilityPageA::SubscribeEvent(const Want &want) { - Want mwant{want}; + Want mwant {want}; std::vector eventList = { "event_data_test_action", }; @@ -133,7 +136,7 @@ void AmsStKitDataAbilityPageA::OnBackground() void AmsStKitDataAbilityPageA::GetWantInfo(const Want &want) { Want mWant(want); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; std::vector vectorOperator = mWant.GetStringArrayParam("operator"); STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator); @@ -150,7 +153,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt AmsStKitDataAbilityPageA *mainAbility, Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -175,9 +178,10 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; - if (!feof(file)) - fgets(str, 5, file); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -189,7 +193,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestPageAEventSubscriber::TestPost(const std::string funName) { APP_LOGI("KitTestPageAEventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_service_a.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_service_a.cpp index 17140dc40642fc1b1ec6159f045593c92402a380..23c6068037ef81a99b2b1bd1104260c1ef4af285 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_service_a.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_service_a.cpp @@ -26,6 +26,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_SERVICE_CODE = 310; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -34,6 +35,8 @@ static const std::string OPERATOR_QUERY = "Query"; static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; static const std::string OPERATOR_OPENFILE = "OpenFile"; static const std::string OPERATOR_GETTYPE = "GetType"; +constexpr int charCnt = 5; +} bool AmsStKitDataAbilityServiceA::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -70,7 +73,7 @@ AmsStKitDataAbilityServiceA::~AmsStKitDataAbilityServiceA() void AmsStKitDataAbilityServiceA::SubscribeEvent(const Want &want) { - Want mwant{want}; + Want mwant {want}; std::vector eventList = { "event_data_test_action", }; @@ -159,7 +162,7 @@ void AmsStKitDataAbilityServiceA::OnDisconnect(const Want &want) void AmsStKitDataAbilityServiceA::GetWantInfo(const Want &want) { Want mWant(want); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; std::vector vectorOperator = mWant.GetStringArrayParam("operator"); STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator); @@ -176,7 +179,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt AmsStKitDataAbilityServiceA *mainAbility, Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -201,9 +204,9 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; + char str[charCnt]; if (!feof(file)) - fgets(str, 5, file); + fgets(str, charCnt, file); result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -215,7 +218,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestServiceAEventSubscriber::TestPost(const std::string funName) { APP_LOGI("KitTestServiceAEventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/BUILD.gn index 84cfa990b8f864771329875cfcb5cdd1e47eb71a..6b0bd12020f032563c46a00ab4e45506b16a7844 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/BUILD.gn @@ -58,6 +58,8 @@ ohos_shared_library("amsKitSystemTestDataB") { "${innerkits_path}/appexecfwk_core:appexecfwk_core", "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_page_b.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_page_b.h index 7a355e5d75a21626c64f055579ee8570126e791d..d52b7ef6ce72247748f3b459600f90106a3fed2c 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_page_b.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_page_b.h @@ -58,11 +58,13 @@ public: KitTestPageBEventSubscriber(const CommonEventSubscribeInfo &sp, AmsStKitDataAbilityPageB *ability) : CommonEventSubscriber(sp) { - mapTestFunc_ = {{"OnStart", [this]() { TestPost("OnStart"); }}, + mapTestFunc_ = { + {"OnStart", [this]() { TestPost("OnStart"); }}, {"OnStop", [this]() { TestPost("OnStop"); }}, {"OnActive", [this]() { TestPost("OnActive"); }}, {"OnInactive", [this]() { TestPost("OnInactive"); }}, - {"OnBackground", [this]() { TestPost("OnBackground"); }}}; + {"OnBackground", [this]() { TestPost("OnBackground"); }} + }; mainAbility_ = ability; }; virtual void OnReceiveEvent(const CommonEventData &data); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_data_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_data_b.cpp index b79c784dc0bdc4f280fac7a986826b8f9289ebd4..b15d455f71ae00b853bf854eaf2303f165dc5ce7 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_data_b.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_data_b.cpp @@ -23,6 +23,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_DATA_CODE = 270; static const int LIFECYCLE_CALLBACKS = 271; static const int LIFECYCLE_OBSERVER = 272; @@ -38,6 +39,8 @@ static const int DEFAULT_DELETE_RESULT = 2222; static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} void AmsStKitDataAbilityDataBLifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) { @@ -296,7 +299,7 @@ std::vector AmsStKitDataAbilityDataB::GetFileTypes(const Uri &uri, { APP_LOGI("AmsStKitDataAbilityDataB <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "GetFileTypes"); - std::vector fileType{"filetypes"}; + std::vector fileType {"filetypes"}; return fileType; } @@ -317,7 +320,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt AmsStKitDataAbilityDataB *mainAbility, Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -342,9 +345,10 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; - if (!feof(file)) - fgets(str, 5, file); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -356,7 +360,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestDataBEventSubscriber::TestPost(const std::string funName) { APP_LOGI("KitTestDataBEventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_page_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_page_b.cpp index 8deb7457a7bb9144a5deb9af5e4d4fafa320e726..8ceb1505dc642f92079ea8b4c34d16f7eb1a168e 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_page_b.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_page_b.cpp @@ -26,6 +26,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_PAGE_CODE = 140; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -34,6 +35,8 @@ static const std::string OPERATOR_QUERY = "Query"; static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; static const std::string OPERATOR_OPENFILE = "OpenFile"; static const std::string OPERATOR_GETTYPE = "GetType"; +constexpr int charCnt = 5; +} bool AmsStKitDataAbilityPageB::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -70,7 +73,7 @@ AmsStKitDataAbilityPageB::~AmsStKitDataAbilityPageB() void AmsStKitDataAbilityPageB::SubscribeEvent(const Want &want) { - Want mwant{want}; + Want mwant {want}; std::vector eventList = { "event_data_test_action", }; @@ -133,7 +136,7 @@ void AmsStKitDataAbilityPageB::OnBackground() void AmsStKitDataAbilityPageB::GetWantInfo(const Want &want) { Want mWant(want); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; std::vector vectorOperator = mWant.GetStringArrayParam("operator"); STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator); @@ -150,7 +153,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt AmsStKitDataAbilityPageB *mainAbility, Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -175,9 +178,10 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; - if (!feof(file)) - fgets(str, 5, file); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -189,7 +193,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestPageBEventSubscriber::TestPost(const std::string funName) { APP_LOGI("KitTestPageBEventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_service_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_service_b.cpp index 438db44dcbef83ec7a8da81836eff73d75ee8921..a7001d80017feded2fd9ae91f13f0a13b5fedfd3 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_service_b.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_service_b.cpp @@ -26,6 +26,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_SERVICE_CODE = 320; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -34,6 +35,8 @@ static const std::string OPERATOR_QUERY = "Query"; static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; static const std::string OPERATOR_OPENFILE = "OpenFile"; static const std::string OPERATOR_GETTYPE = "GetType"; +constexpr int charCnt = 5; +} bool AmsStKitDataAbilityServiceB::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -70,7 +73,7 @@ AmsStKitDataAbilityServiceB::~AmsStKitDataAbilityServiceB() void AmsStKitDataAbilityServiceB::SubscribeEvent(const Want &want) { - Want mwant{want}; + Want mwant {want}; std::vector eventList = { "event_data_test_action", }; @@ -159,7 +162,7 @@ void AmsStKitDataAbilityServiceB::OnDisconnect(const Want &want) void AmsStKitDataAbilityServiceB::GetWantInfo(const Want &want) { Want mWant(want); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; std::vector vectorOperator = mWant.GetStringArrayParam("operator"); STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator); @@ -176,7 +179,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt AmsStKitDataAbilityServiceB *mainAbility, Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -201,9 +204,10 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; - if (!feof(file)) - fgets(str, 5, file); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -215,7 +219,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestServiceBEventSubscriber::TestPost(const std::string funName) { APP_LOGI("KitTestServiceAEventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/ability_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/ability_ability.h index f44e0b2f3da20ae0c371d5f7751ff5528c591fbf..718947b23185185e16edccb4cb22e552b489e69e 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/ability_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/ability_ability.h @@ -87,7 +87,8 @@ public: bool SubscribeEvent(); void DoTestCase(); void StopSelfAbility(); - + void caseIndexOne(); + void caseIndexTwo(); protected: virtual void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/life_cycle_call_backs_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/life_cycle_call_backs_ability.h index 066c3eb55bd293fc92c93c75b476955daba8f827..73bd3364feef69df4a5cad290b3f8a9a910faab7 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/life_cycle_call_backs_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/life_cycle_call_backs_ability.h @@ -23,7 +23,6 @@ namespace OHOS { namespace AppExecFwk { - class ServiceLifecycleCallbacks : public AbilityLifecycleCallbacks { public: ServiceLifecycleCallbacks() = default; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_ability.cpp index 0060598daaf505785786a261d9e5cc0399dc428d..f08aeff55b00611e962d1a36d3cde6f40980dc7d 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_ability.cpp @@ -709,6 +709,28 @@ void AbilityAbility::TestAbilityGetLifecycle() } } +void AbilityAbility::caseIndexOne() { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); +} + +void AbilityAbility::caseIndexTwo() { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); + +} + void AbilityAbility::TestAbilityDisconnectAbility() { APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", @@ -717,23 +739,10 @@ void AbilityAbility::TestAbilityDisconnectAbility() switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { case CaseIndex::ONE: { - stub_ = new (std::nothrow) AbilityConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = ConnectAbility(want_, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); - sleep(1); - DisconnectAbility(connCallback_); + caseIndexOne(); } break; case CaseIndex::TWO: { - MAP_STR_STR params; - Want want = - TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); - stub_ = new (std::nothrow) AbilityConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = ConnectAbility(want, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); - sleep(1); - DisconnectAbility(connCallback_); + caseIndexTwo(); } break; case CaseIndex::THREE: { MAP_STR_STR params; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_life_cycle_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_life_cycle_ability.cpp index 08ef9ee33f6c7062c3dd4ed8948a80f9e7b0fe77..c2552fa710c22685e4eb5522b129f6a26d306081 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_life_cycle_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_life_cycle_ability.cpp @@ -21,6 +21,9 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; +namespace { +constexpr int loopCnt = 3; +} // namespace AbilityLifeCycleAbility::~AbilityLifeCycleAbility() { @@ -228,7 +231,7 @@ void AbilityLifeCycleAbility::TestStopAbility() TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); } break; case CaseIndex::FOUR: { - for (int i = 0; i < 3; i++) { + for (int i = 0; i < loopCnt; i++) { bool ret = BaseAbility::GetContext()->StopAbility(want_); TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/life_cycle_observer_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/life_cycle_observer_ability.cpp index 4653d6331658f05a5129de9aa650f8bde6772b8f..5ae57412319b7807964d5405c0d3e27c6077a904 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/life_cycle_observer_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/life_cycle_observer_ability.cpp @@ -21,7 +21,9 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; - +namespace { +constexpr int loopCnt = 100; +} void LifecycleObserverLifecycleObserver::DoTask() { switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { @@ -492,7 +494,7 @@ void LifeCycleObserverAbility::TestLifeCycleGetLifecycle() TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); } break; case CaseIndex::TWO: { - for (int i = 0; i < 100; i++) { + for (int i = 0; i < loopCnt; i++) { auto lifecycle = GetLifecycle(); } TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_ability.h index 17c36f5b4ffd1112102dec0663e63381323918e7..ef28fca50f763afcf800619f687b6aa6b2d984d6 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_ability.h @@ -83,7 +83,12 @@ public: void TestAbilityDisconnectAbility(); void DoTestCase(); - + void CaseIndexOne(); + void CaseIndexTwo(); + void DisconnectCaseIndexOne(); + void DisconnectCaseIndexTwo(); + void AbilityDisconnectCaseIndexOne(); + void AbilityDisconnectCaseIndexTwo(); protected: void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) override; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_connection_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_connection_ability.h index ca235dbdb8c4003374fb490dd3581e4b75207ec4..e094e4e8de820cde094d854c6f0bf8aa958ff391 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_connection_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_connection_ability.h @@ -80,6 +80,10 @@ public: void TestDisconnectAbility(); void TestStartAbility(); void TestTerminateAbility(); + void DisconnectCaseIndexOne(); + void DisconnectCaseIndexTwo(); + void ConnectCaseIndexOne(); + void ConnectCaseIndexTwo(); protected: void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, @@ -97,9 +101,9 @@ protected: bool SubscribeEvent(); private: - Want want_{}; - sptr stub_{}; - sptr connCallback_{}; + Want want_ {}; + sptr stub_ {}; + sptr connCallback_ {}; std::shared_ptr subscriber_ = {}; }; std::string AbilityConnectionAbility::sequenceNumber_ = "0"; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_context_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_context_ability.h index c2b76b14efc988ff420094b82f52544adeb0d6bd..95242ba347f1be9ed20933f0cd0c2d457839f4cf 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_context_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_context_ability.h @@ -90,11 +90,14 @@ protected: virtual void OnDisconnect(const Want &want) override; bool SubscribeEvent(); - + void ConnectCaseIndexOne(); + void ConnectCaseIndexTwo(); + void DisconnectCaseIndexOne(); + void DisconnectCaseIndexTwo(); private: - Want want_{}; - sptr stub_{}; - sptr connCallback_{}; + Want want_ {}; + sptr stub_ {}; + sptr connCallback_ {}; std::shared_ptr subscriber_ = {}; }; int AbilityContextAbility::sequenceNumber_ = 0; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_life_cycle_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_life_cycle_ability.h index 3adcabb8db4d64832bfe72f1115abea51b151bcb..c52ea2d40fb21a629e02b4fe8b74c2109d575e1a 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_life_cycle_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_life_cycle_ability.h @@ -113,11 +113,11 @@ protected: virtual void OnDisconnect(const Want &want) override; bool SubscribeEvent(); - + void GetLifecycleStateCaseOne(); private: - Want want_{}; - sptr stub_{}; - sptr connCallback_{}; + Want want_ {}; + sptr stub_ {}; + sptr connCallback_ {}; std::shared_ptr subscriber_ = {}; }; int AbilityLifeCycleAbility::sequenceNumber_ = 0; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/life_cycle_call_backs_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/life_cycle_call_backs_ability.h index 0da1ab05da2138a591f56d048161a79f2ee1e8fa..25b50672cc6ccd0204e7778a4a3b9143926d6f86 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/life_cycle_call_backs_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/life_cycle_call_backs_ability.h @@ -23,7 +23,6 @@ namespace OHOS { namespace AppExecFwk { - class ServiceLifecycleCallbacks : public AbilityLifecycleCallbacks { public: ServiceLifecycleCallbacks() = default; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_ability.cpp index 282f42fe45e218f19a4991b215f1e308d294083c..f0756aa5f352d2b5d723138a2694d3077f136eef 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_ability.cpp @@ -20,6 +20,10 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; +namespace { +constexpr int SLEEP_SECOND = 2; +constexpr int loopCnt = 3; +} AbilityAbility::~AbilityAbility() { @@ -174,6 +178,27 @@ void AbilityAbility::OnNewWant(const Want &want) DoTestCase(); } +void AbilityAbility::CaseIndexOne() { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(SLEEP_SECOND); + DisconnectAbility(connCallback_); +} + +void AbilityAbility::CaseIndexTwo() { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(SLEEP_SECOND); + DisconnectAbility(connCallback_); +} + void AbilityAbility::TestConnectAbility() { APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", @@ -182,23 +207,10 @@ void AbilityAbility::TestConnectAbility() switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { case CaseIndex::ONE: { - stub_ = new (std::nothrow) AbilityConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = ConnectAbility(want_, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); - sleep(2); - DisconnectAbility(connCallback_); + CaseIndexOne(); } break; case CaseIndex::TWO: { - stub_ = new (std::nothrow) AbilityConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - MAP_STR_STR params; - Want want = - TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); - bool ret = ConnectAbility(want, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); - sleep(2); - DisconnectAbility(connCallback_); + CaseIndexTwo(); } break; case CaseIndex::THREE: { stub_ = new (std::nothrow) AbilityConnectCallback(); @@ -207,7 +219,7 @@ void AbilityAbility::TestConnectAbility() Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); bool ret = ConnectAbility(want, connCallback_); TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); - sleep(2); + sleep(SLEEP_SECOND); DisconnectAbility(connCallback_); } break; case CaseIndex::FOUR: { @@ -216,7 +228,7 @@ void AbilityAbility::TestConnectAbility() connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); bool ret = ConnectAbility(want_, connCallback_); TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); - sleep(2); + sleep(SLEEP_SECOND); DisconnectAbility(connCallback_); } } break; @@ -225,7 +237,7 @@ void AbilityAbility::TestConnectAbility() sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); bool ret = ConnectAbility(want_, connCallback); TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); - sleep(2); + sleep(SLEEP_SECOND); DisconnectAbility(connCallback); } break; default: @@ -258,7 +270,7 @@ void AbilityAbility::TestStopAbility() TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestStopAbility"); } break; case CaseIndex::FOUR: { - for (int i = 0; i < 3; i++) { + for (int i = 0; i < loopCnt; i++) { bool ret = StopAbility(want_); TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestStopAbility"); } @@ -275,6 +287,25 @@ void AbilityAbility::TestStopAbility() } } +void AbilityAbility::DisconnectCaseIndexOne() { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + DisconnectAbility(connCallback_); +} + +void AbilityAbility::DisconnectCaseIndexTwo() { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + DisconnectAbility(connCallback_); +} + void AbilityAbility::TestDisconnectAbility() { APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", @@ -283,21 +314,10 @@ void AbilityAbility::TestDisconnectAbility() switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { case CaseIndex::ONE: { - stub_ = new (std::nothrow) AbilityConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = ConnectAbility(want_, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); - DisconnectAbility(connCallback_); + DisconnectCaseIndexOne(); } break; case CaseIndex::TWO: { - MAP_STR_STR params; - Want want = - TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); - stub_ = new (std::nothrow) AbilityConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = ConnectAbility(want, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); - DisconnectAbility(connCallback_); + DisconnectCaseIndexTwo(); } break; case CaseIndex::THREE: { MAP_STR_STR params; @@ -309,7 +329,7 @@ void AbilityAbility::TestDisconnectAbility() DisconnectAbility(connCallback_); } break; case CaseIndex::FOUR: { - for (int i = 0; i < 3; i++) { + for (int i = 0; i < loopCnt; i++) { stub_ = new (std::nothrow) AbilityConnectCallback(); connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); bool ret = ConnectAbility(want_, connCallback_); @@ -391,7 +411,7 @@ void AbilityAbility::TestTerminateAbility() TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); StartAbility(want, 0); TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestTerminateAbility"); - sleep(2); + sleep(SLEEP_SECOND); StopAbility(want); TerminateAbility(); } break; @@ -400,7 +420,7 @@ void AbilityAbility::TestTerminateAbility() Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); StartAbility(want, 0); TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestTerminateAbility"); - sleep(2); + sleep(SLEEP_SECOND); StopAbility(want); TerminateAbility(); } break; @@ -415,7 +435,7 @@ void AbilityAbility::TestTerminateAbility() Want want = TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); StartAbility(want, 0); - sleep(2); + sleep(SLEEP_SECOND); TerminateAbility(); TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestTerminateAbility"); } break; @@ -491,7 +511,7 @@ void AbilityAbility::TestAbilityConnectAbility() TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); bool ret = ConnectAbility(want, connCallback_); TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityConnectAbility"); - sleep(2); + sleep(SLEEP_SECOND); DisconnectAbility(connCallback_); } break; case CaseIndex::THREE: { @@ -501,7 +521,7 @@ void AbilityAbility::TestAbilityConnectAbility() Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); bool ret = ConnectAbility(want, connCallback_); TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityConnectAbility"); - sleep(2); + sleep(SLEEP_SECOND); DisconnectAbility(connCallback_); } break; case CaseIndex::FOUR: { @@ -612,6 +632,27 @@ void AbilityAbility::TestAbilityGetLifecycle() } } +void AbilityAbility::AbilityDisconnectCaseIndexOne() { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); +} + +void AbilityAbility::AbilityDisconnectCaseIndexTwo() { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); +} + void AbilityAbility::TestAbilityDisconnectAbility() { APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", @@ -620,23 +661,10 @@ void AbilityAbility::TestAbilityDisconnectAbility() switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { case CaseIndex::ONE: { - stub_ = new (std::nothrow) AbilityConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = ConnectAbility(want_, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); - sleep(1); - DisconnectAbility(connCallback_); + AbilityDisconnectCaseIndexOne(); } break; case CaseIndex::TWO: { - MAP_STR_STR params; - Want want = - TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); - stub_ = new (std::nothrow) AbilityConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = ConnectAbility(want, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); - sleep(1); - DisconnectAbility(connCallback_); + AbilityDisconnectCaseIndexTwo(); } break; case CaseIndex::THREE: { MAP_STR_STR params; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_connection_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_connection_ability.cpp index 054b04669acaa7d7c808ca49da9d3704de411e18..3f9ec8825d16e5390731a75cc128e40867229178 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_connection_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_connection_ability.cpp @@ -126,27 +126,35 @@ void AbilityConnectionAbility::OnDisconnect(const Want &want) APP_ABILITY_CONNECTION_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); } +void AbilityConnectionAbility::ConnectCaseIndexOne() { + stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + +void AbilityConnectionAbility::ConnectCaseIndexTwo() { + stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + void AbilityConnectionAbility::TestConnectAbility() { switch ((CaseIndex)std::stoi(AbilityConnectionAbility::sequenceNumber_)) { case CaseIndex::ONE: { - stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestConnectAbility"); - sleep(1); - BaseAbility::GetContext()->DisconnectAbility(connCallback_); + ConnectCaseIndexOne(); } break; case CaseIndex::TWO: { - stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - MAP_STR_STR params; - Want want = - TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); - bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestConnectAbility"); - sleep(1); - BaseAbility::GetContext()->DisconnectAbility(connCallback_); + ConnectCaseIndexTwo(); } break; case CaseIndex::THREE: { stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); @@ -219,27 +227,35 @@ void AbilityConnectionAbility::TestStopAbility() } } +void AbilityConnectionAbility::DisconnectCaseIndexOne() { + stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + +void AbilityConnectionAbility::DisconnectCaseIndexTwo() { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + void AbilityConnectionAbility::TestDisconnectAbility() { switch ((CaseIndex)std::stoi(AbilityConnectionAbility::sequenceNumber_)) { case CaseIndex::ONE: { - stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); - sleep(1); - BaseAbility::GetContext()->DisconnectAbility(connCallback_); + DisconnectCaseIndexOne(); } break; case CaseIndex::TWO: { - MAP_STR_STR params; - Want want = - TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); - stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); - sleep(1); - BaseAbility::GetContext()->DisconnectAbility(connCallback_); + DisconnectCaseIndexTwo(); } break; case CaseIndex::THREE: { MAP_STR_STR params; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_context_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_context_ability.cpp index a8155eda53fa557102b5fafde57d0a89a26506d7..9f53b7f6cbb8f674077bc3026df7a992d2affacb 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_context_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_context_ability.cpp @@ -21,6 +21,9 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; +namespace { +constexpr int SLEEP_SECOND = 2; +} AbilityContextAbility::~AbilityContextAbility() { @@ -127,27 +130,35 @@ void AbilityContextAbility::OnDisconnect(const Want &want) APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); } +void AbilityContextAbility::ConnectCaseIndexOne() { + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(SLEEP_SECOND); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + +void AbilityContextAbility::ConnectCaseIndexTwo() { + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + void AbilityContextAbility::TestConnectAbility() { switch ((CaseIndex)AbilityContextAbility::sequenceNumber_) { case CaseIndex::ONE: { - stub_ = new (std::nothrow) AbilityContextConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); - sleep(2); - BaseAbility::GetContext()->DisconnectAbility(connCallback_); + ConnectCaseIndexOne(); } break; case CaseIndex::TWO: { - stub_ = new (std::nothrow) AbilityContextConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - MAP_STR_STR params; - Want want = - TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); - bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); - sleep(1); - BaseAbility::GetContext()->DisconnectAbility(connCallback_); + ConnectCaseIndexTwo(); } break; case CaseIndex::THREE: { stub_ = new (std::nothrow) AbilityContextConnectCallback(); @@ -220,26 +231,34 @@ void AbilityContextAbility::TestStopAbility() } } +void AbilityContextAbility::DisconnectCaseIndexOne() { + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + +void AbilityContextAbility::DisconnectCaseIndexTwo() { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + sleep(SLEEP_SECOND); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + void AbilityContextAbility::TestDisconnectAbility() { switch ((CaseIndex)AbilityContextAbility::sequenceNumber_) { case CaseIndex::ONE: { - stub_ = new (std::nothrow) AbilityContextConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); - BaseAbility::GetContext()->DisconnectAbility(connCallback_); + DisconnectCaseIndexOne(); } break; case CaseIndex::TWO: { - MAP_STR_STR params; - Want want = - TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); - stub_ = new (std::nothrow) AbilityContextConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); - sleep(2); - BaseAbility::GetContext()->DisconnectAbility(connCallback_); + DisconnectCaseIndexTwo(); } break; case CaseIndex::THREE: { MAP_STR_STR params; @@ -248,7 +267,7 @@ void AbilityContextAbility::TestDisconnectAbility() connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); - sleep(2); + sleep(SLEEP_SECOND); BaseAbility::GetContext()->DisconnectAbility(connCallback_); } break; case CaseIndex::FOUR: { @@ -288,7 +307,7 @@ void AbilityContextAbility::TestStartAbility() TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); BaseAbility::GetContext()->StartAbility(want, 0); TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestStartAbility"); - sleep(2); + sleep(SLEEP_SECOND); BaseAbility::GetContext()->StopAbility(want); } break; case CaseIndex::THREE: { @@ -296,7 +315,7 @@ void AbilityContextAbility::TestStartAbility() Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); BaseAbility::GetContext()->StartAbility(want, 0); TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestStartAbility"); - sleep(2); + sleep(SLEEP_SECOND); BaseAbility::GetContext()->StopAbility(want); } break; case CaseIndex::FOUR: { @@ -330,7 +349,7 @@ void AbilityContextAbility::TestTerminateAbility() TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); BaseAbility::GetContext()->StartAbility(want, 0); TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestTerminateAbility"); - sleep(2); + sleep(SLEEP_SECOND); BaseAbility::GetContext()->StopAbility(want); BaseAbility::GetContext()->TerminateAbility(); } break; @@ -339,7 +358,7 @@ void AbilityContextAbility::TestTerminateAbility() Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); BaseAbility::GetContext()->StartAbility(want, 0); TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestTerminateAbility"); - sleep(2); + sleep(SLEEP_SECOND); BaseAbility::GetContext()->StopAbility(want); BaseAbility::GetContext()->TerminateAbility(); } break; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_life_cycle_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_life_cycle_ability.cpp index 2ccf0e524b6942032336966c424453110b96db11..03392a73520f1f13c2aafdfd5921a519a9e37cb6 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_life_cycle_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_life_cycle_ability.cpp @@ -21,7 +21,9 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; - +namespace { +constexpr int loopCnt = 3; +} AbilityLifeCycleAbility::~AbilityLifeCycleAbility() { CommonEventManager::UnSubscribeCommonEvent(subscriber_); @@ -234,7 +236,7 @@ void AbilityLifeCycleAbility::TestStopAbility() TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, ret, "TestStopAbility"); } break; case CaseIndex::FOUR: { - for (int i = 0; i < 3; i++) { + for (int i = 0; i < loopCnt; i++) { bool ret = BaseAbility::GetContext()->StopAbility(want_); TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, ret, "TestStopAbility"); } @@ -420,14 +422,18 @@ void AbilityLifeCycleAbility::TestLifeCycleGetLifecycle() } } +void AbilityLifeCycleAbility::GetLifecycleStateCaseOne() { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, + lifecycle->GetLifecycleState(), + "TestLifeCycleGetLifecycleState"); +} + void AbilityLifeCycleAbility::TestLifeCycleGetLifecycleState() { switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { case CaseIndex::ONE: { - auto lifecycle = GetLifecycle(); - TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, - lifecycle->GetLifecycleState(), - "TestLifeCycleGetLifecycleState"); + GetLifecycleStateCaseOne(); } break; case CaseIndex::TWO: { auto lifecycle = GetLifecycle(); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/life_cycle_observer_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/life_cycle_observer_ability.cpp index 4a61746250ba165767f53646d896a910b1ce877a..a5559b0e1be5f0e2a32352b3690bb12496a31ea3 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/life_cycle_observer_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/life_cycle_observer_ability.cpp @@ -21,7 +21,9 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; - +namespace { +constexpr int loopCnt = 100; +} void LifecycleObserverLifecycleObserver::DoTask() { switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { @@ -491,7 +493,7 @@ void LifeCycleObserverAbility::TestLifeCycleGetLifecycle() TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); } break; case CaseIndex::TWO: { - for (int i = 0; i < 100; i++) { + for (int i = 0; i < loopCnt; i++) { auto lifecycle = GetLifecycle(); } TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr2.cpp index 1d8adb99f27e3a6905e5e98e42811ade74e6ea27..75ee4caf3814631de34dbb08c63dbaf3f6fd4de0 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr2.cpp @@ -17,6 +17,9 @@ namespace OHOS { namespace AppExecFwk { +namespace { +constexpr uint32_t multiple = 100; +} void AmsStAbilityR2::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) @@ -98,7 +101,7 @@ void AmsStAbilityR2::OnBackground() { APP_LOGI("AmsStAbilityR2::OnBackground"); Ability::OnBackground(); - std::this_thread::sleep_for(std::chrono::milliseconds(STEventName::BACKGROUND_TIMEOUT * 100)); + std::this_thread::sleep_for(std::chrono::milliseconds(STEventName::BACKGROUND_TIMEOUT * multiple)); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr3.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr3.cpp index 32c656679b2e74f040336318f217a332dbc0eede..f8c1476c1f0dde14e73b3e2965135e2c0cd9992f 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr3.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr3.cpp @@ -17,6 +17,9 @@ namespace OHOS { namespace AppExecFwk { +namespace { +constexpr uint32_t timeoutAdd = 5000; +} void AmsStAbilityR3::OnStart(const Want &want) { GetWantInfo(want); @@ -88,7 +91,7 @@ void AmsStAbilityR3::OnBackground() { APP_LOGI("AmsStAbilityR3::OnBackground"); Ability::OnBackground(); - std::this_thread::sleep_for(std::chrono::milliseconds(STEventName::TERMINATE_TIMEOUT + 5000)); + std::this_thread::sleep_for(std::chrono::milliseconds(STEventName::TERMINATE_TIMEOUT + timeoutAdd)); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); } diff --git a/test/resource/amssystemtestability/abilitySrc/common/ability_append_test_info.h b/test/resource/amssystemtestability/abilitySrc/common/ability_append_test_info.h index 6d178531b3ffbf888714b699a546b15798338de7..939b33dde92eb9900f3276b75ce9245fcfa44d9e 100644 --- a/test/resource/amssystemtestability/abilitySrc/common/ability_append_test_info.h +++ b/test/resource/amssystemtestability/abilitySrc/common/ability_append_test_info.h @@ -102,7 +102,6 @@ enum class TestAbilityState { OnRestoreAbilityState, End }; - } // namespace AppExecFwk } // namespace OHOS #endif // ABILITY_APPEND_TEST_INFO_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/common/kit_test_common_info.h b/test/resource/amssystemtestability/abilitySrc/common/kit_test_common_info.h index ab1dc4dc870e2d7fea5386e9d8d5068865e196b3..c6c6a41b6da9ff4523451eb9f2c11ce93e5583ef 100644 --- a/test/resource/amssystemtestability/abilitySrc/common/kit_test_common_info.h +++ b/test/resource/amssystemtestability/abilitySrc/common/kit_test_common_info.h @@ -423,7 +423,6 @@ enum class WantParamsApi { SetParam, End, }; - } // namespace AppExecFwk } // namespace OHOS #endif // KIT_TEST_COMMON_INFO_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/include/test_utils.h index e32f3c5521a3b852d7224e2e63db851c71226d23..f0ffaa195385b9f13d7fb5035a070d365485fe00 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/include/test_utils.h +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/include/test_utils.h @@ -19,7 +19,6 @@ namespace OHOS { namespace AppExecFwk { - class TestUtils { public: TestUtils() = default; diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/main_ability.cpp index cd1ad9aae0224f465a5bfd66f992b5a8092284da..af5f914a38845d242af4ba3e827e95d9a2afe44a 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/main_ability.cpp @@ -27,7 +27,7 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; using namespace OHOS::STtools; - +namespace { int terminated_task_num = 0; std::condition_variable cv; std::mutex cv_mutex; @@ -48,6 +48,11 @@ std::string innerDelimiter = "-"; std::string task_execution_sequence = delimiter; std::vector> allDispatchers; std::mutex dispatcher_mutex; +constexpr int numZero = 0; +constexpr int numOne = 1; +constexpr int numTwo = 2; +constexpr int numThree = 3; +} bool Wait(const int task_num) { @@ -360,14 +365,11 @@ void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo.size()=%{public}zu", caseInfo.size()); - if (caseInfo.size() < 3) { + if (caseInfo.size() < numThree) { return; } - APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo[0]=%{public}s", caseInfo[0].c_str()); - APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo[1]=%{public}s", caseInfo[1].c_str()); - APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo[2]=%{public}s", caseInfo[2].c_str()); - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } @@ -383,72 +385,41 @@ void MainAbility::TestDispatcher(int apiIndex, int caseIndex, int code) } } -int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) -{ - APP_LOGI("-- -- -- -- -- --MainAbility::Dispatch begin"); - std::string outerName = "outerDispatcher"; - std::string innerName = "innerDispatcher"; +void SetInnerTask(TaskList innerDispatcher, TestSetting innerSetting, std::string outerTaskId, int innerTaskSeq) { + std::string innerTaskId = outerTaskId + innerDelimiter + std::to_string(innerTaskSeq); + auto innerTask = std::make_shared([=]() { TestTask(innerTaskId); }); + innerDispatcher.addOperation(innerSetting.op); + if (innerSetting.op == TestOperation::APPLY && innerSetting.apply > 0) { + innerDispatcher.addApply(innerSetting.apply); + } + if (innerSetting.op == TestOperation::DELAY && innerSetting.delay > 0) { + innerDispatcher.addDelay(innerSetting.delay); + } + innerDispatcher.addFunc(innerTask); +} - std::string outerTaskId; - auto context = GetContext(); - TaskList outerDispatcher{outerSetting.dispatcher, context, outerName}; - if (outerSetting.create_group) { - outerDispatcher.addOperation(TestOperation::CREATE_GROUP); +void SetInnerTaskOther(TaskList innerDispatcher, TestSetting innerSetting, int outerTaskSeq) { + if (innerSetting.sync_barrier) { + std::string taskId = innerSyncBarrierId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); } - for (int i = 0; i < testTaskCount; i++) { - outerTaskId = std::to_string(i); - auto outerTask = std::make_shared([=]() { - auto context = this->GetContext(); - TaskList innerDispatcher{innerSetting.dispatcher, context, innerName + std::to_string(i)}; - if (innerSetting.create_group) { - innerDispatcher.addOperation(TestOperation::CREATE_GROUP); - } - for (int j = 0; j < testTaskCount; j++) { - std::string innerTaskId = outerTaskId + innerDelimiter + std::to_string(j); - auto innerTask = std::make_shared([=]() { TestTask(innerTaskId); }); - innerDispatcher.addOperation(innerSetting.op); - if (innerSetting.op == TestOperation::APPLY && innerSetting.apply > 0) { - innerDispatcher.addApply(innerSetting.apply); - } - if (innerSetting.op == TestOperation::DELAY && innerSetting.delay > 0) { - innerDispatcher.addDelay(innerSetting.delay); - } - innerDispatcher.addFunc(innerTask); - } - if (innerSetting.sync_barrier) { - std::string taskId = innerSyncBarrierId + std::to_string(i); - auto task = std::make_shared([=]() { TestTask(taskId); }); - innerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); - } - if (innerSetting.async_barrier) { - std::string taskId = innerAsyncBarrierId + std::to_string(i); - auto task = std::make_shared([=]() { TestTask(taskId); }); - innerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); - } - if (innerSetting.group_wait) { - innerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(innerSetting.group_timeout); - } - if (innerSetting.group_notify) { - std::string taskId = innerGroupNotifyId + std::to_string(i); - auto task = std::make_shared([=]() { TestTask(taskId); }); - innerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); - } - innerDispatcher.executedTask(); - { - std::lock_guard lock(dispatcher_mutex); - allDispatchers.push_back(innerDispatcher.getDispatcher()); - } - TestTask(outerTaskId); - }); - outerDispatcher.addOperation(outerSetting.op); - if (outerSetting.op == TestOperation::APPLY && outerSetting.apply > 0) { - outerDispatcher.addApply(outerSetting.apply); - } - if (outerSetting.op == TestOperation::DELAY && outerSetting.delay > 0) { - outerDispatcher.addDelay(outerSetting.delay); - } - outerDispatcher.addFunc(outerTask); + if (innerSetting.async_barrier) { + std::string taskId = innerAsyncBarrierId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); } + if (innerSetting.group_wait) { + innerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(innerSetting.group_timeout); + } + if (innerSetting.group_notify) { + std::string taskId = innerGroupNotifyId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); + } +} + +void SetOuterTaskOther(TaskList outerDispatcher, TestSetting outerSetting) { if (outerSetting.sync_barrier) { auto task = std::make_shared([=]() { TestTask(outerSyncBarrierId); }); outerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); @@ -464,11 +435,9 @@ int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) auto task = std::make_shared([=]() { TestTask(outerGroupNotifyId); }); outerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); } - outerDispatcher.executedTask(); - { - std::lock_guard lock(dispatcher_mutex); - allDispatchers.push_back(outerDispatcher.getDispatcher()); - } +} + +int CountTask(TestSetting outerSetting, TestSetting innerSetting) { int taskCount = 0; taskCount = (innerSetting.op == TestOperation::APPLY) ? (innerSetting.apply * testTaskCount) : testTaskCount; if (innerSetting.sync_barrier) { @@ -492,7 +461,54 @@ int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) if (outerSetting.group_notify) { taskCount++; } - APP_LOGI("-- -- -- -- -- --MainAbility::Dispatch end taskCount:%{public}d", taskCount); + return taskCount; +} + +int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) +{ + std::string outerName = "outerDispatcher"; + std::string innerName = "innerDispatcher"; + std::string outerTaskId; + auto context = GetContext(); + TaskList outerDispatcher {outerSetting.dispatcher, context, outerName}; + if (outerSetting.create_group) { + outerDispatcher.addOperation(TestOperation::CREATE_GROUP); + } + for (int i = 0; i < testTaskCount; i++) { + outerTaskId = std::to_string(i); + auto outerTask = std::make_shared([=]() { + auto context = this->GetContext(); + TaskList innerDispatcher {innerSetting.dispatcher, context, innerName + std::to_string(i)}; + if (innerSetting.create_group) { + innerDispatcher.addOperation(TestOperation::CREATE_GROUP); + } + for (int j = 0; j < testTaskCount; j++) { + SetInnerTask(innerDispatcher, innerSetting, outerTaskId, j); + } + SetInnerTaskOther(innerDispatcher, innerSetting, i); + innerDispatcher.executedTask(); + { + std::lock_guard lock(dispatcher_mutex); + allDispatchers.push_back(innerDispatcher.getDispatcher()); + } + TestTask(outerTaskId); + }); + outerDispatcher.addOperation(outerSetting.op); + if (outerSetting.op == TestOperation::APPLY && outerSetting.apply > 0) { + outerDispatcher.addApply(outerSetting.apply); + } + if (outerSetting.op == TestOperation::DELAY && outerSetting.delay > 0) { + outerDispatcher.addDelay(outerSetting.delay); + } + outerDispatcher.addFunc(outerTask); + } + SetOuterTaskOther(outerDispatcher, outerSetting); + outerDispatcher.executedTask(); + { + std::lock_guard lock(dispatcher_mutex); + allDispatchers.push_back(outerDispatcher.getDispatcher()); + } + int taskCount = CountTask(outerSetting, innerSetting); return taskCount; } @@ -1820,7 +1836,6 @@ void MainAbility::GlobalCase50(int code) // level1:global, group level2:serial, delay void MainAbility::GlobalCase51(int code) { - APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); TestSetting outerSetting; @@ -8973,7 +8988,7 @@ void MainAbility::HybridCase1(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; std::vector operationList = { TestOperation::SYNC, TestOperation::ASYNC, @@ -9003,7 +9018,7 @@ void MainAbility::HybridCase2(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::PARALLEL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::PARALLEL, context, "parallel"}; std::vector operationList = { TestOperation::SYNC, TestOperation::ASYNC, @@ -9037,7 +9052,7 @@ void MainAbility::HybridCase3(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList serialDispatcher = TaskList{TestDispatcher::SERIAL, context, "serial"}; + TaskList serialDispatcher = TaskList {TestDispatcher::SERIAL, context, "serial"}; std::vector operationList = { TestOperation::SYNC, TestOperation::ASYNC, @@ -9064,7 +9079,7 @@ void MainAbility::HybridCase4(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; std::vector operationList = { TestOperation::SYNC, TestOperation::ASYNC, @@ -9091,12 +9106,12 @@ void MainAbility::HybridCase5(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; globalDispatcher.addOperation(TestOperation::SYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) @@ -9137,12 +9152,12 @@ void MainAbility::HybridCase6(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; globalDispatcher.addOperation(TestOperation::ASYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) @@ -9183,12 +9198,12 @@ void MainAbility::HybridCase7(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; const long delay = 10; globalDispatcher.addOperation(TestOperation::DELAY) @@ -9236,12 +9251,12 @@ void MainAbility::HybridCase8(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; globalDispatcher.addOperation(TestOperation::CREATE_GROUP) .addOperation(TestOperation::ASYNC_GROUP) @@ -9285,12 +9300,12 @@ void MainAbility::HybridCase9(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; globalDispatcher.addOperation(TestOperation::CREATE_GROUP) .addOperation(TestOperation::ASYNC_GROUP) @@ -9334,12 +9349,12 @@ void MainAbility::HybridCase10(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; const long delay = 10; globalDispatcher.addOperation(TestOperation::CREATE_GROUP) @@ -9387,12 +9402,12 @@ void MainAbility::HybridCase11(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; globalDispatcher.addOperation(TestOperation::CREATE_GROUP) .addOperation(TestOperation::ASYNC_GROUP) @@ -9400,21 +9415,21 @@ void MainAbility::HybridCase11(int code) .addOperation(TestOperation::GROUP_NOTIFY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); - taskId += 2; + taskId += numTwo; parallelDispatcher1.addOperation(TestOperation::CREATE_GROUP) .addOperation(TestOperation::ASYNC_GROUP) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .addOperation(TestOperation::GROUP_NOTIFY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); - taskId += 2; + taskId += numTwo; parallelDispatcher2.addOperation(TestOperation::CREATE_GROUP) .addOperation(TestOperation::ASYNC_GROUP) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .addOperation(TestOperation::GROUP_NOTIFY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); - taskId += 2; + taskId += numTwo; serialDispatcher1.addOperation(TestOperation::ASYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .executedTask(); @@ -9442,12 +9457,12 @@ void MainAbility::HybridCase12(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9502,12 +9517,12 @@ void MainAbility::HybridCase13(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 1; @@ -9559,12 +9574,12 @@ void MainAbility::HybridCase14(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9618,12 +9633,12 @@ void MainAbility::HybridCase15(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9635,7 +9650,7 @@ void MainAbility::HybridCase15(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; parallelDispatcher1.addOperation(TestOperation::SYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .executedTask(); @@ -9679,12 +9694,12 @@ void MainAbility::HybridCase16(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9707,7 +9722,7 @@ void MainAbility::HybridCase16(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; serialDispatcher1.addOperation(TestOperation::ASYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .executedTask(); @@ -9740,12 +9755,12 @@ void MainAbility::HybridCase17(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9795,12 +9810,12 @@ void MainAbility::HybridCase18(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9852,12 +9867,12 @@ void MainAbility::HybridCase19(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9910,12 +9925,12 @@ void MainAbility::HybridCase20(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9938,7 +9953,7 @@ void MainAbility::HybridCase20(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; serialDispatcher1.addOperation(TestOperation::DELAY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .addDelay(delay) @@ -9971,12 +9986,12 @@ void MainAbility::HybridCase21(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9988,7 +10003,7 @@ void MainAbility::HybridCase21(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; parallelDispatcher1.addOperation(TestOperation::ASYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .executedTask(); @@ -10031,12 +10046,12 @@ void MainAbility::HybridCase22(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -10091,12 +10106,12 @@ void MainAbility::HybridCase23(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -10120,7 +10135,7 @@ void MainAbility::HybridCase23(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; serialDispatcher1.addOperation(TestOperation::APPLY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .executedTask(); @@ -10153,12 +10168,12 @@ void MainAbility::HybridCase24(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const long apply = 2; @@ -10169,8 +10184,8 @@ void MainAbility::HybridCase24(int code) .addOperation(TestOperation::GROUP_NOTIFY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); - taskId += 2; - taskCount += 2; + taskId += numTwo; + taskCount += numTwo; parallelDispatcher1.addOperation(TestOperation::DELAY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .addDelay(delay) @@ -10219,12 +10234,12 @@ void MainAbility::HybridCase25(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; globalDispatcher.addOperation(TestOperation::ASYNC) @@ -10245,7 +10260,7 @@ void MainAbility::HybridCase25(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; serialDispatcher1.addOperation(TestOperation::ASYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .executedTask(); @@ -10276,12 +10291,12 @@ void MainAbility::HybridCase26(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -10332,12 +10347,12 @@ void MainAbility::HybridCase27(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -10354,7 +10369,7 @@ void MainAbility::HybridCase27(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; parallelDispatcher2.addOperation(TestOperation::APPLY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .addApply(apply) @@ -10395,7 +10410,7 @@ void MainAbility::MultiAppCase1(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -10427,7 +10442,7 @@ void MainAbility::MultiAppCase2(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::PARALLEL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::PARALLEL, context, "parallel"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -10459,7 +10474,7 @@ void MainAbility::MultiAppCase3(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList serialDispatcher = TaskList{TestDispatcher::SERIAL, context, "serial"}; + TaskList serialDispatcher = TaskList {TestDispatcher::SERIAL, context, "serial"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -10491,7 +10506,7 @@ void MainAbility::MultiAppCase4(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -10524,17 +10539,17 @@ void MainAbility::ExtraCase1(int code) Reset(); auto context = GetContext(); int taskId = 0; - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; bool result = globalDispatcher.addOperation(TestOperation::SYNC) - .addFunc(std::make_shared([=]() { - std::string targetBundleName = "com.ohos.TaskDispatcherA"; - std::string targetAbility = "SecondAbility"; - Want want; - want.SetElementName(targetBundleName, targetAbility); - StartAbility(want); - TestTask(std::to_string(taskId)); - })) - .executedTask(); + .addFunc(std::make_shared([=]() { + std::string targetBundleName = "com.ohos.TaskDispatcherA"; + std::string targetAbility = "SecondAbility"; + Want want; + want.SetElementName(targetBundleName, targetAbility); + StartAbility(want); + TestTask(std::to_string(taskId)); + })) + .executedTask(); taskId++; Wait(taskId); result = task_execution_sequence.size() > 1; @@ -10547,7 +10562,7 @@ void MainAbility::FillInDispathcer() const int fullThreadNum = 32; const int waitTime = 2; auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::PARALLEL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::PARALLEL, context, "parallel"}; parallelDispatcher.setTaskPriority(AppExecFwk::TaskPriority::HIGH); parallelDispatcher.addOperation(TestOperation::ASYNC).addFunc(std::make_shared([=]() { sleep(waitTime - 1); @@ -10565,9 +10580,9 @@ void MainAbility::PriorityCase1(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList globalDispatcherLow = TaskList{TestDispatcher::GLOBAL, context, "globalLow"}; - TaskList globalDispatcherDefault = TaskList{TestDispatcher::GLOBAL, context, "globalDefault"}; - TaskList globalDispatcherHigh = TaskList{TestDispatcher::GLOBAL, context, "globalHigh"}; + TaskList globalDispatcherLow = TaskList {TestDispatcher::GLOBAL, context, "globalLow"}; + TaskList globalDispatcherDefault = TaskList {TestDispatcher::GLOBAL, context, "globalDefault"}; + TaskList globalDispatcherHigh = TaskList {TestDispatcher::GLOBAL, context, "globalHigh"}; int taskId = 0; globalDispatcherLow.setTaskPriority(AppExecFwk::TaskPriority::LOW) .addOperation(TestOperation::ASYNC) @@ -10592,7 +10607,7 @@ void MainAbility::PriorityCase1(int code) for (auto index : outerTaskIndex) { result = result && (index != std::string::npos); } - result = result && (outerTaskIndex[0] > outerTaskIndex[1]) && (outerTaskIndex[1] > outerTaskIndex[2]); + result = result && (outerTaskIndex[numZero] > outerTaskIndex[numOne]) && (outerTaskIndex[numOne] > outerTaskIndex[numTwo]); TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); } void MainAbility::PriorityCase2(int code) @@ -10601,9 +10616,9 @@ void MainAbility::PriorityCase2(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList parallelDispatcherLow = TaskList{TestDispatcher::PARALLEL, context, "parallelLow"}; - TaskList parallelDispatcherDefault = TaskList{TestDispatcher::PARALLEL, context, "parallelDefault"}; - TaskList parallelDispatcherHigh = TaskList{TestDispatcher::PARALLEL, context, "parallelHigh"}; + TaskList parallelDispatcherLow = TaskList {TestDispatcher::PARALLEL, context, "parallelLow"}; + TaskList parallelDispatcherDefault = TaskList {TestDispatcher::PARALLEL, context, "parallelDefault"}; + TaskList parallelDispatcherHigh = TaskList {TestDispatcher::PARALLEL, context, "parallelHigh"}; int taskId = 0; parallelDispatcherLow.setTaskPriority(AppExecFwk::TaskPriority::LOW) .addOperation(TestOperation::ASYNC) @@ -10628,7 +10643,7 @@ void MainAbility::PriorityCase2(int code) for (auto index : outerTaskIndex) { result = result && (index != std::string::npos); } - result = result && (outerTaskIndex[0] > outerTaskIndex[1]) && (outerTaskIndex[1] > outerTaskIndex[2]); + result = result && (outerTaskIndex[numZero] > outerTaskIndex[numOne]) && (outerTaskIndex[numOne] > outerTaskIndex[numTwo]); TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); } void MainAbility::PriorityCase3(int code) @@ -10637,9 +10652,9 @@ void MainAbility::PriorityCase3(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList serialDispatcherLow = TaskList{TestDispatcher::SERIAL, context, "serialLow"}; - TaskList serialDispatcherDefault = TaskList{TestDispatcher::SERIAL, context, "serialDefault"}; - TaskList serialDispatcherHigh = TaskList{TestDispatcher::SERIAL, context, "serialHigh"}; + TaskList serialDispatcherLow = TaskList {TestDispatcher::SERIAL, context, "serialLow"}; + TaskList serialDispatcherDefault = TaskList {TestDispatcher::SERIAL, context, "serialDefault"}; + TaskList serialDispatcherHigh = TaskList {TestDispatcher::SERIAL, context, "serialHigh"}; int taskId = 0; serialDispatcherLow.setTaskPriority(AppExecFwk::TaskPriority::LOW) .addOperation(TestOperation::ASYNC) @@ -10664,7 +10679,7 @@ void MainAbility::PriorityCase3(int code) for (auto index : outerTaskIndex) { result = result && (index != std::string::npos); } - result = result && (outerTaskIndex[0] > outerTaskIndex[1]) && (outerTaskIndex[1] > outerTaskIndex[2]); + result = result && (outerTaskIndex[numZero] > outerTaskIndex[numOne]) && (outerTaskIndex[numOne] > outerTaskIndex[numTwo]); TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); } void MainAbility::PriorityCase4(int code) @@ -10673,9 +10688,9 @@ void MainAbility::PriorityCase4(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList parallelDispatcherLow = TaskList{TestDispatcher::PARALLEL, context, "parallelLow"}; - TaskList parallelDispatcherDefault = TaskList{TestDispatcher::PARALLEL, context, "parallelDefault"}; - TaskList mainDispatcherHigh = TaskList{TestDispatcher::MAIN, context, "mainHigh"}; + TaskList parallelDispatcherLow = TaskList {TestDispatcher::PARALLEL, context, "parallelLow"}; + TaskList parallelDispatcherDefault = TaskList {TestDispatcher::PARALLEL, context, "parallelDefault"}; + TaskList mainDispatcherHigh = TaskList {TestDispatcher::MAIN, context, "mainHigh"}; int taskId = 0; parallelDispatcherLow.setTaskPriority(AppExecFwk::TaskPriority::LOW) .addOperation(TestOperation::ASYNC) @@ -10699,7 +10714,7 @@ void MainAbility::PriorityCase4(int code) for (auto index : outerTaskIndex) { result = result && (index != std::string::npos); } - result = result && (outerTaskIndex[0] > outerTaskIndex[1]) && (outerTaskIndex[1] > outerTaskIndex[2]); + result = result && (outerTaskIndex[numZero] > outerTaskIndex[numOne]) && (outerTaskIndex[numOne] > outerTaskIndex[numTwo]); TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); } void MainAbility::PriorityCase5(int code) @@ -10708,9 +10723,9 @@ void MainAbility::PriorityCase5(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList globalDispatcherLow = TaskList{TestDispatcher::GLOBAL, context, "globallLow"}; - TaskList parallelDispatcherDefault = TaskList{TestDispatcher::PARALLEL, context, "parallelDefault"}; - TaskList globalDispatcherHigh = TaskList{TestDispatcher::GLOBAL, context, "globalHigh"}; + TaskList globalDispatcherLow = TaskList {TestDispatcher::GLOBAL, context, "globallLow"}; + TaskList parallelDispatcherDefault = TaskList {TestDispatcher::PARALLEL, context, "parallelDefault"}; + TaskList globalDispatcherHigh = TaskList {TestDispatcher::GLOBAL, context, "globalHigh"}; int taskId = 0; globalDispatcherLow.setTaskPriority(AppExecFwk::TaskPriority::LOW) .addOperation(TestOperation::ASYNC) @@ -10735,7 +10750,7 @@ void MainAbility::PriorityCase5(int code) for (auto index : outerTaskIndex) { result = result && (index != std::string::npos); } - result = result && (outerTaskIndex[0] > outerTaskIndex[1]) && (outerTaskIndex[1] > outerTaskIndex[2]); + result = result && (outerTaskIndex[numZero] > outerTaskIndex[numOne]) && (outerTaskIndex[numOne] > outerTaskIndex[numTwo]); TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); } void MainAbility::RevokeCase1(int code) @@ -10744,13 +10759,13 @@ void MainAbility::RevokeCase1(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::GLOBAL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; int taskId = 0; bool result = parallelDispatcher.addOperation(TestOperation::ASYNC) - .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) - .addOperation(TestOperation::REVOCABLE) - .addRevokeTask(1) - .executedTask(); + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::REVOCABLE) + .addRevokeTask(1) + .executedTask(); taskId++; result = !result || Wait(taskId); result = result || task_execution_sequence.size() > 1; @@ -10762,11 +10777,11 @@ void MainAbility::RevokeCase2(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::GLOBAL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; int taskId = 0; bool result = parallelDispatcher.addOperation(TestOperation::ASYNC) - .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) - .executedTask(); + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); taskId++; result = result && Wait(taskId); result = result && !parallelDispatcher.addOperation(TestOperation::REVOCABLE).addRevokeTask(1).executedTask(); @@ -10779,14 +10794,14 @@ void MainAbility::RevokeCase3(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::GLOBAL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; int taskId = 0; bool result = parallelDispatcher.addOperation(TestOperation::DELAY) - .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) - .addDelay(delayMs) - .addOperation(TestOperation::REVOCABLE) - .addRevokeTask(1) - .executedTask(); + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delayMs) + .addOperation(TestOperation::REVOCABLE) + .addRevokeTask(1) + .executedTask(); taskId++; result = !result || Wait(taskId); result = result || task_execution_sequence.size() > 1; @@ -10798,12 +10813,12 @@ void MainAbility::RevokeCase4(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::GLOBAL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; int taskId = 0; bool result = parallelDispatcher.addOperation(TestOperation::DELAY) - .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) - .addDelay(delayMs) - .executedTask(); + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delayMs) + .executedTask(); taskId++; result = result && Wait(taskId); result = result && !parallelDispatcher.addOperation(TestOperation::REVOCABLE).addRevokeTask(1).executedTask(); @@ -10817,14 +10832,14 @@ void MainAbility::RevokeCase5(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::GLOBAL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; int taskId = 0; bool result = parallelDispatcher.addOperation(TestOperation::CREATE_GROUP) - .addOperation(TestOperation::ASYNC_GROUP) - .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) - .addOperation(TestOperation::REVOCABLE) - .addRevokeTask(1) - .executedTask(); + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::REVOCABLE) + .addRevokeTask(1) + .executedTask(); taskId++; result = !result || Wait(taskId); result = result || task_execution_sequence.size() > 1; @@ -10836,12 +10851,12 @@ void MainAbility::RevokeCase6(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::GLOBAL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; int taskId = 0; bool result = parallelDispatcher.addOperation(TestOperation::CREATE_GROUP) - .addOperation(TestOperation::ASYNC_GROUP) - .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) - .executedTask(); + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); taskId++; result = result && Wait(taskId); result = result && !parallelDispatcher.addOperation(TestOperation::REVOCABLE).addRevokeTask(1).executedTask(); diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/second_ability.cpp index 74b750fe7fa5a49e9051fd2107ca246fe119859a..57b1eff8c0d1ff2185e6f19582328e6236511c28 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/second_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/second_ability.cpp @@ -20,6 +20,14 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; +namespace +{ +constexpr int numZero = 0; +constexpr int numOne = 1; +constexpr int numTwo = 2; +constexpr int numThree = 3; +} // namespace + void SecondAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -109,11 +117,11 @@ void SecondEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (std::strcmp(eventName.c_str(), g_EVENT_REQU_SECOND.c_str()) == 0) { auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); - if (caseInfo.size() < 3) { + if (caseInfo.size() < numThree) { return; } - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/test_utils.cpp index 07ebf00c47128276f0e83d0aa5783fec0a417147..3e75bdf815379f71af430ad9d5c979da62400675 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/test_utils.cpp +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/test_utils.cpp @@ -47,9 +47,10 @@ Want TestUtils::MakeWant( std::vector TestUtils::split(const std::string &in, const std::string &delim) { - std::regex reg{delim}; - return std::vector{ - std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator()}; + std::regex reg {delim}; + return std::vector { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() + }; } } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/include/test_utils.h index e32f3c5521a3b852d7224e2e63db851c71226d23..f0ffaa195385b9f13d7fb5035a070d365485fe00 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/include/test_utils.h +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/include/test_utils.h @@ -19,7 +19,6 @@ namespace OHOS { namespace AppExecFwk { - class TestUtils { public: TestUtils() = default; diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/main_ability.cpp index e80ab723aa4c01b840b256cef11908d2e0fa9606..5d6ca2081673da539f3284424e640e990472d4f8 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/main_ability.cpp @@ -25,7 +25,7 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; using namespace OHOS::STtools; - +namespace { int terminated_task_num = 0; std::condition_variable cv; std::mutex cv_mutex; @@ -38,17 +38,28 @@ std::string outerSyncBarrierId = "outerSyncBarrierId"; std::string outerAsyncBarrierId = "outerAsyncBarrierId"; std::string outerGroupWaitId = "outerGroupWaitId"; std::string outerGroupNotifyId = "outerGroupNotifyId"; - std::string delimiter = "_"; std::string innerDelimiter = "-"; std::string task_execution_sequence = delimiter; +std::vector> allDispatchers; +std::mutex dispatcher_mutex; +constexpr int numZero = 0; +constexpr int numOne = 1; +constexpr int numTwo = 2; +constexpr int numThree = 3; +} bool Wait(const int task_num) { APP_LOGI("-- -- -- -- -- --MainAbility::Wait"); std::unique_lock ulock(cv_mutex); using namespace std::chrono_literals; - return cv.wait_for(ulock, 5000ms, [task_num] { return terminated_task_num == task_num; }); + bool result = cv.wait_for(ulock, 5000ms, [task_num] { return terminated_task_num == task_num; }); + if (result) { + allDispatchers.clear(); + } + APP_LOGI("-- -- -- -- -- --MainAbility::Wait result:%{public}d", result); + return result; } void TestTask(const std::string &task_id) @@ -68,6 +79,7 @@ void Reset() APP_LOGI("-- -- -- -- -- --MainAbility::Reset"); terminated_task_num = 0; task_execution_sequence = delimiter; + allDispatchers.clear(); } bool IsAscend(const std::vector &vec) @@ -268,14 +280,11 @@ void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo.size()=%{public}zu", caseInfo.size()); - if (caseInfo.size() < 3) { + if (caseInfo.size() < numThree) { return; } - APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo[0]=%{public}s", caseInfo[0].c_str()); - APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo[1]=%{public}s", caseInfo[1].c_str()); - APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo[2]=%{public}s", caseInfo[2].c_str()); - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } @@ -291,15 +300,92 @@ void MainAbility::TestDispatcher(int apiIndex, int caseIndex, int code) } } +void SetInnerTask(TaskList innerDispatcher, TestSetting innerSetting, std::string outerTaskId, int innerTaskSeq) { + std::string innerTaskId = outerTaskId + innerDelimiter + std::to_string(innerTaskSeq); + auto innerTask = std::make_shared([=]() { TestTask(innerTaskId); }); + innerDispatcher.addOperation(innerSetting.op); + if (innerSetting.op == TestOperation::APPLY && innerSetting.apply > 0) { + innerDispatcher.addApply(innerSetting.apply); + } + if (innerSetting.op == TestOperation::DELAY && innerSetting.delay > 0) { + innerDispatcher.addDelay(innerSetting.delay); + } + innerDispatcher.addFunc(innerTask); +} + +void SetInnerTaskOther(TaskList innerDispatcher, TestSetting innerSetting, int outerTaskSeq) { + if (innerSetting.sync_barrier) { + std::string taskId = innerSyncBarrierId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); + } + if (innerSetting.async_barrier) { + std::string taskId = innerAsyncBarrierId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); + } + if (innerSetting.group_wait) { + innerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(innerSetting.group_timeout); + } + if (innerSetting.group_notify) { + std::string taskId = innerGroupNotifyId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); + } +} + +void SetOuterTaskOther(TaskList outerDispatcher, TestSetting outerSetting) { + if (outerSetting.sync_barrier) { + auto task = std::make_shared([=]() { TestTask(outerSyncBarrierId); }); + outerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); + } + if (outerSetting.async_barrier) { + auto task = std::make_shared([=]() { TestTask(outerAsyncBarrierId); }); + outerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); + } + if (outerSetting.group_wait) { + outerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(outerSetting.group_timeout); + } + if (outerSetting.group_notify) { + auto task = std::make_shared([=]() { TestTask(outerGroupNotifyId); }); + outerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); + } +} + +int CountTask(TestSetting outerSetting, TestSetting innerSetting) { + int taskCount = 0; + taskCount = (innerSetting.op == TestOperation::APPLY) ? (innerSetting.apply * testTaskCount) : testTaskCount; + if (innerSetting.sync_barrier) { + taskCount++; + } + if (innerSetting.async_barrier) { + taskCount++; + } + if (innerSetting.group_notify) { + taskCount++; + } + taskCount = (outerSetting.op == TestOperation::APPLY) + ? (outerSetting.apply * testTaskCount + outerSetting.apply * testTaskCount * taskCount) + : (testTaskCount + testTaskCount * taskCount); + if (outerSetting.sync_barrier) { + taskCount++; + } + if (outerSetting.async_barrier) { + taskCount++; + } + if (outerSetting.group_notify) { + taskCount++; + } + return taskCount; +} + int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) { - APP_LOGI("-- -- -- -- -- --MainAbility::Dispatch begin"); std::string outerName = "outerDispatcher"; std::string innerName = "innerDispatcher"; - std::string outerTaskId; auto context = GetContext(); - TaskList outerDispatcher{outerSetting.dispatcher, context, outerName}; + TaskList outerDispatcher {outerSetting.dispatcher, context, outerName}; if (outerSetting.create_group) { outerDispatcher.addOperation(TestOperation::CREATE_GROUP); } @@ -307,41 +393,19 @@ int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) outerTaskId = std::to_string(i); auto outerTask = std::make_shared([=]() { auto context = this->GetContext(); - TaskList innerDispatcher{innerSetting.dispatcher, context, innerName + std::to_string(i)}; + TaskList innerDispatcher {innerSetting.dispatcher, context, innerName + std::to_string(i)}; if (innerSetting.create_group) { innerDispatcher.addOperation(TestOperation::CREATE_GROUP); } for (int j = 0; j < testTaskCount; j++) { - std::string innerTaskId = outerTaskId + innerDelimiter + std::to_string(j); - auto innerTask = std::make_shared([=]() { TestTask(innerTaskId); }); - innerDispatcher.addOperation(innerSetting.op); - if (innerSetting.op == TestOperation::APPLY && innerSetting.apply > 0) { - innerDispatcher.addApply(innerSetting.apply); - } - if (innerSetting.op == TestOperation::DELAY && innerSetting.delay > 0) { - innerDispatcher.addDelay(innerSetting.delay); - } - innerDispatcher.addFunc(innerTask); - } - if (innerSetting.sync_barrier) { - std::string taskId = innerSyncBarrierId + std::to_string(i); - auto task = std::make_shared([=]() { TestTask(taskId); }); - innerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); - } - if (innerSetting.async_barrier) { - std::string taskId = innerAsyncBarrierId + std::to_string(i); - auto task = std::make_shared([=]() { TestTask(taskId); }); - innerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); - } - if (innerSetting.group_wait) { - innerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(innerSetting.group_timeout); - } - if (innerSetting.group_notify) { - std::string taskId = innerGroupNotifyId + std::to_string(i); - auto task = std::make_shared([=]() { TestTask(taskId); }); - innerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); + SetInnerTask(innerDispatcher, innerSetting, outerTaskId, j); } + SetInnerTaskOther(innerDispatcher, innerSetting, i); innerDispatcher.executedTask(); + { + std::lock_guard lock(dispatcher_mutex); + allDispatchers.push_back(innerDispatcher.getDispatcher()); + } TestTask(outerTaskId); }); outerDispatcher.addOperation(outerSetting.op); @@ -353,29 +417,13 @@ int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) } outerDispatcher.addFunc(outerTask); } - if (outerSetting.sync_barrier) { - auto task = std::make_shared([=]() { TestTask(outerSyncBarrierId); }); - outerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); - } - if (outerSetting.async_barrier) { - auto task = std::make_shared([=]() { TestTask(outerAsyncBarrierId); }); - outerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); - } - if (outerSetting.group_wait) { - outerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(outerSetting.group_timeout); - } - if (outerSetting.group_notify) { - auto task = std::make_shared([=]() { TestTask(outerGroupNotifyId); }); - outerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); - } + SetOuterTaskOther(outerDispatcher, outerSetting); outerDispatcher.executedTask(); - int taskCount = 0; - taskCount = (innerSetting.op == TestOperation::APPLY) ? (innerSetting.apply * testTaskCount) : testTaskCount; - taskCount = (outerSetting.op == TestOperation::APPLY) - ? (innerSetting.apply * testTaskCount + innerSetting.apply * testTaskCount * taskCount) - : (testTaskCount + testTaskCount * taskCount); - - APP_LOGI("-- -- -- -- -- --MainAbility::Dispatch end"); + { + std::lock_guard lock(dispatcher_mutex); + allDispatchers.push_back(outerDispatcher.getDispatcher()); + } + int taskCount = CountTask(outerSetting, innerSetting); return taskCount; } @@ -403,7 +451,7 @@ void MainAbility::MultiAppCase1(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -435,7 +483,7 @@ void MainAbility::MultiAppCase2(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::PARALLEL, context, "parallel"}; + TaskList globalDispatcher = TaskList {TestDispatcher::PARALLEL, context, "parallel"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -467,7 +515,7 @@ void MainAbility::MultiAppCase3(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::SERIAL, context, "serial"}; + TaskList globalDispatcher = TaskList {TestDispatcher::SERIAL, context, "serial"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -499,7 +547,7 @@ void MainAbility::MultiAppCase4(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/second_ability.cpp index 67a8ed8c7c7381c3e7297f5ad419e9dc0f3f95f3..9c770b1249159f651d0c48fcc98ac92003660c94 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/second_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/second_ability.cpp @@ -20,6 +20,12 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; +namespace { +constexpr int numZero = 0; +constexpr int numOne = 1; +constexpr int numTwo = 2; +constexpr int numThree = 3; +} void SecondAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -103,11 +109,11 @@ void SecondEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (std::strcmp(eventName.c_str(), g_EVENT_REQU_SECOND_B.c_str()) == 0) { auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); - if (caseInfo.size() < 3) { + if (caseInfo.size() < numThree) { return; } - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/test_utils.cpp index 07ebf00c47128276f0e83d0aa5783fec0a417147..3e75bdf815379f71af430ad9d5c979da62400675 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/test_utils.cpp +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/test_utils.cpp @@ -47,9 +47,10 @@ Want TestUtils::MakeWant( std::vector TestUtils::split(const std::string &in, const std::string &delim) { - std::regex reg{delim}; - return std::vector{ - std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator()}; + std::regex reg {delim}; + return std::vector { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() + }; } } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/tools/include/event.h b/test/resource/amssystemtestability/abilitySrc/tools/include/event.h index 00ced741999b3e91b6f639acf99a7753263b6e04..4e659a7bd700b404d249954636828c6c3b3100d5 100644 --- a/test/resource/amssystemtestability/abilitySrc/tools/include/event.h +++ b/test/resource/amssystemtestability/abilitySrc/tools/include/event.h @@ -18,7 +18,6 @@ #include namespace STtools { - class Event { public: Event(); @@ -38,5 +37,4 @@ private: int WaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout = 60); void Completed(Event &event, const std::string &eventName, const int code); void CleanMsg(Event &event); - } // namespace STtools \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/tools/include/stoperator.h b/test/resource/amssystemtestability/abilitySrc/tools/include/stoperator.h index c0683c1ae47c2b17ca607c8ff6a5448b7271722b..f7a8f367f01b3302b96144dfc2050e7bc2b07c21 100644 --- a/test/resource/amssystemtestability/abilitySrc/tools/include/stoperator.h +++ b/test/resource/amssystemtestability/abilitySrc/tools/include/stoperator.h @@ -20,11 +20,8 @@ namespace STtools { using std::string; class StOperator; - std::vector SerializationStOperatorToVector(StOperator &ParentOperator); - void DeserializationStOperatorFromVector(StOperator &ParentOperator, std::vector &vectorOperator); - class StOperator { private: std::vector> g_childOperator; @@ -57,5 +54,4 @@ public: std::vector> GetChildOperator(); std::vector> PopChildOperator(); }; - } // namespace STtools diff --git a/test/resource/amssystemtestability/abilitySrc/tools/include/stpageabilityevent.h b/test/resource/amssystemtestability/abilitySrc/tools/include/stpageabilityevent.h index 0ac76a4b9f5284961ae275fdef5935d2f101d38e..7c441e4f4dcf660e0f1f64ce5e8043175e17c3f7 100644 --- a/test/resource/amssystemtestability/abilitySrc/tools/include/stpageabilityevent.h +++ b/test/resource/amssystemtestability/abilitySrc/tools/include/stpageabilityevent.h @@ -27,7 +27,6 @@ namespace OHOS { namespace AppExecFwk { - namespace STEventName { const std::string g_eventName = "resp_st_page_ability_callback"; const std::string g_eventNameProcessMemory = "resp_st_process_memory_info"; @@ -129,8 +128,6 @@ private: std::string callBackPath_; std::string abilityStatus_; }; - } // namespace AppExecFwk } // namespace OHOS - -#endif //_AMS_ST_PAGE_ABILITY_EVENT_H_ \ No newline at end of file +#endif // _AMS_ST_PAGE_ABILITY_EVENT_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/tools/src/event.cpp b/test/resource/amssystemtestability/abilitySrc/tools/src/event.cpp index a51291b4b24bf14bfd45d1c6b27f4e390d2443e9..933a13149cedd0306a45973a8d488359257eb0c8 100644 --- a/test/resource/amssystemtestability/abilitySrc/tools/src/event.cpp +++ b/test/resource/amssystemtestability/abilitySrc/tools/src/event.cpp @@ -17,7 +17,6 @@ #include namespace STtools { - int WaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout) { return event.WaitingMessage(std::to_string(code) + eventName, timeout, false); @@ -98,5 +97,4 @@ void Event::Clean() waiting_message_ = ""; complete_message_.clear(); } - } // namespace STtools \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/tools/src/stoperator.cpp b/test/resource/amssystemtestability/abilitySrc/tools/src/stoperator.cpp index 2c7ea20bc5fc7992fa9217e857611dfc0c303532..c441c6cedf8da2677a28bd6d63054022b3f9b581 100644 --- a/test/resource/amssystemtestability/abilitySrc/tools/src/stoperator.cpp +++ b/test/resource/amssystemtestability/abilitySrc/tools/src/stoperator.cpp @@ -75,7 +75,8 @@ void DeserializationStOperatorFromVector(StOperator &ParentOperator, std::vector int StOperator::countChild = 0; StOperator::StOperator() - : g_parentOperator(nullptr), g_abilityType("0"), g_bundleName(""), g_abilityName(""), g_operatorName(""), g_message("") + : g_parentOperator(nullptr), g_abilityType("0"), + g_bundleName(""), g_abilityName(""), g_operatorName(""), g_message("") { g_childOperator.clear(); StOperator::countChild++; diff --git a/test/resource/amssystemtestability/abilitySrc/tools/src/stpageabilityevent.cpp b/test/resource/amssystemtestability/abilitySrc/tools/src/stpageabilityevent.cpp index 92e46f510c87a214497cb3ac4a7d16c8acdb935c..f13a7db485f029b3c0cf0c7a1b68f2d85d2bd663 100644 --- a/test/resource/amssystemtestability/abilitySrc/tools/src/stpageabilityevent.cpp +++ b/test/resource/amssystemtestability/abilitySrc/tools/src/stpageabilityevent.cpp @@ -17,7 +17,6 @@ namespace OHOS { namespace AppExecFwk { - using namespace OHOS::EventFwk; STPageAbilityEvent::STPageAbilityEvent(const std::string &className) @@ -189,6 +188,5 @@ bool STPageAbilityEventSubscriber::PublishEvent(const std::string &eventName, co commonData.SetData(data); return CommonEventManager::PublishCommonEvent(commonData); } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo1/src/pageAbilityDemo.cpp b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo1/src/pageAbilityDemo.cpp index 00a3c081aefd04e4aa4c3afbfaae471d3b9ef312..b834cac390814cf09d24de1aa7bb36033bfe2a48 100644 --- a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo1/src/pageAbilityDemo.cpp +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo1/src/pageAbilityDemo.cpp @@ -67,24 +67,12 @@ void PageAbilityDemo::OnBackground() void PageAbilityDemo::CreateFile(const std::string &path) const { - if (path.size() > PATH_MAX) { - APP_LOGE("CreateFile the length of path is too long"); - return; - } - - std::string realPath; - realPath.reserve(PATH_MAX); - realPath.resize(PATH_MAX - 1); - - if (realpath(path.c_str(), &(realPath[0])) == nullptr) { - APP_LOGW("CreateFile-translate:%{public}s not exist path", realPath.c_str()); - } std::ofstream file(path); file.close(); - if (access(realPath.c_str(), F_OK) != 0) { - APP_LOGE("CreateFile-checkFile:%{public}s not exist", realPath.c_str()); + if (access(path.c_str(), F_OK) != 0) { + APP_LOGE("CreateFile-checkFile:%{public}s not exist", path.c_str()); } } diff --git a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/src/pageAbilityDemo.cpp b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/src/pageAbilityDemo.cpp index 64984a03bebbd337590c56977cdaa20d1202a318..2ed39e4dc00aba02cd7e2f7b0b18483f6aecc0de 100644 --- a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/src/pageAbilityDemo.cpp +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/src/pageAbilityDemo.cpp @@ -74,24 +74,12 @@ void PageAbilityDemo::OnBackground() void PageAbilityDemo::CreateFile(const std::string &path) const { - if (path.size() > PATH_MAX) { - APP_LOGE("CreateFile the length of path is too long"); - return; - } - - std::string realPath; - realPath.reserve(PATH_MAX); - realPath.resize(PATH_MAX - 1); - - if (realpath(path.c_str(), &(realPath[0])) == nullptr) { - APP_LOGW("CreateFile-translate:%{public}s not exist path", realPath.c_str()); - } std::ofstream file(path); file.close(); - if (access(realPath.c_str(), F_OK) != 0) { - APP_LOGE("CreateFile-checkFile:%{public}s not exist", realPath.c_str()); + if (access(path.c_str(), F_OK) != 0) { + APP_LOGE("CreateFile-checkFile:%{public}s not exist", path.c_str()); } } diff --git a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo4/src/pageAbilityDemo.cpp b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo4/src/pageAbilityDemo.cpp index afb14de6a493348b23a0ced32baf25d6222d9e81..c38274be98c5d14ba657fd61e82a7e899a065f5b 100644 --- a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo4/src/pageAbilityDemo.cpp +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo4/src/pageAbilityDemo.cpp @@ -72,24 +72,12 @@ void PageAbilityDemo::OnBackground() void PageAbilityDemo::CreateFile(const std::string &path) const { - if (path.size() > PATH_MAX) { - APP_LOGE("CreateFile the length of path is too long"); - return; - } - - std::string realPath; - realPath.reserve(PATH_MAX); - realPath.resize(PATH_MAX - 1); - - if (realpath(path.c_str(), &(realPath[0])) == nullptr) { - APP_LOGW("CreateFile-translate:%{public}s not exist path", realPath.c_str()); - } std::ofstream file(path); file.close(); - if (access(realPath.c_str(), F_OK) != 0) { - APP_LOGE("CreateFile-checkFile:%{public}s not exist", realPath.c_str()); + if (access(path.c_str(), F_OK) != 0) { + APP_LOGE("CreateFile-checkFile:%{public}s not exist", path.c_str()); } } diff --git a/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle5.hap b/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle5.hap index aa357ce2f235d6faded4c3ecdec8833aaff54547..a8a9f62cab39664b7b0bc17910861266eef19a37 100755 Binary files a/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle5.hap and b/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle5.hap differ diff --git a/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle24.hap b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle24.hap index 41142715b101b06f9b6b3be03c60c319b6c05895..09cc073f733ed49b115a788edc902eca410e50c4 100644 Binary files a/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle24.hap and b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle24.hap differ diff --git a/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle25.hap b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle25.hap index c7ec8bfd7f89debc0865b60f641c733f5765b694..97fcb8e788eb23ceb06dcd960947b3253dfedbeb 100644 Binary files a/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle25.hap and b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle25.hap differ diff --git a/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle41.hap b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle41.hap old mode 100755 new mode 100644 diff --git a/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle44.hap b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle44.hap index f0d31b0f7c15b20eb169c09f4f926a5a26d9a2b3..37a9ce79265e440f5bc98be1cb8ecb287b7e4a3c 100644 Binary files a/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle44.hap and b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle44.hap differ diff --git a/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle45.hap b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle45.hap index 3ff235b0601412ca8074fb38ab892df6f18c9da8..c7748a8f14a7d264b1f626a959c303a0a26b1be3 100644 Binary files a/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle45.hap and b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle45.hap differ diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/BUILD.gn b/test/resource/formsystemtestability/formSystemTestServiceA/BUILD.gn index a3b48e26782593bb028c22c004a8d63f3e1ca781..eb3960bf94b35bb13afda611eb4587d6383ff8f3 100644 --- a/test/resource/formsystemtestability/formSystemTestServiceA/BUILD.gn +++ b/test/resource/formsystemtestability/formSystemTestServiceA/BUILD.gn @@ -35,7 +35,7 @@ config("formSystemTestAConfig") { ] } ohos_shared_library("formSystemTestServiceA") { - sources = [ "${subdemosystem_path}/src/form_st_service_ability_a1.cpp" ] + sources = [ "${subdemosystem_path}/src/form_st_service_ability_A.cpp" ] configs = [ ":formSystemTestAConfig" ] deps = [ "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/config.json b/test/resource/formsystemtestability/formSystemTestServiceA/config.json index f88dbdcf504e1285e7835194c30ca94bb0391b35..c7baafed52bb0c88b550f74f77a16c0b154ad98f 100644 --- a/test/resource/formsystemtestability/formSystemTestServiceA/config.json +++ b/test/resource/formsystemtestability/formSystemTestServiceA/config.json @@ -1,87 +1,112 @@ -{ - "app": { - "bundleName": "com.provider.bundleName1", - "vendor": "ohos", - "version": { - "code": 1, - "name": "1.0" - }, - "apiVersion": { - "compatible": 3, - "target": 3 - } - }, - "deviceConfig": { - "default": { - } - }, - "module": { - "package": "com.provider.FormSystemTestServiceA.src", - "name": "moduleName11", - "deviceType": [ - "phone" - ], - "distro": { - "deliveryWithInstall": true, - "moduleName": "testability", - "moduleType": "entry" - }, - "abilities": [ - { - "name": "FormStServiceAbilityA1", - "icon": "$media:snowball", - "label": "FormStServiceAbilityA1 Ability", - "launchType": "standard", - "orientation": "unspecified", - "type": "service", - "visible": true, - "formsEnabled": true, - "forms": [ - { - "name": "formName111", - "description": "form_description", - "isDefault": true, - "type": "JS", - "colorMode": "auto", - "supportDimensions":[ "1*2", "2*2" ], - "defaultDimension": "1*2", - "landscapeLayouts": [""], - "portraitLayouts": [""], - "updateEnabled": true, - "scheduledUpateTime": "10:30", - "updateDuration": 1, - "deepLink": "", - "jsComponentName": "card", - "formVisibleNotify" : true, - "metaData": { - "customizeData": [ - { - "name": "originWidgetName", - "value": "myTest" - } - ] - } - } - ] - } - ], - "defPermissions": [ - { - "name": "com.permission.CAMERA", - "grantMode": "system_grant", - "availableScope": ["signature"], - "label": "CAMERA permission", - "description": "CAMERA permission in detail" - } - ], - "js": [ - { - "name": "card", - "pages": [ - "pages/index/index" - ], - "type": "form" - } - ] - } -} +{ + "app": { + "bundleName": "com.provider.bundleName1", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package": "com.provider.FormSystemTestServiceA.src", + "name": "moduleName11", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "moduleName11", + "moduleType": "entry" + }, + "abilities": [ + { + "name": "FormStServiceAbilityA", + "icon": "$media:snowball", + "label": "FormStServiceAbilityA Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true, + "formsEnabled": true, + "forms": [ + { + "name": "formName111", + "description": "form_description", + "isDefault": true, + "type": "JS", + "colorMode": "auto", + "supportDimensions":[ "1*2", "2*2" ], + "defaultDimension": "1*2", + "landscapeLayouts": [""], + "portraitLayouts": [""], + "updateEnabled": true, + "scheduledUpateTime": "0:0", + "updateDuration": 1, + "deepLink": "", + "jsComponentName": "card", + "formVisibleNotify" : true, + "metaData": { + "customizeData": [ + { + "name": "originWidgetName", + "value": "myTest" + } + ] + } + }, + { + "name": "formName112", + "description": "form_description", + "isDefault": true, + "type": "JS", + "colorMode": "auto", + "supportDimensions":[ "1*2", "2*2" ], + "defaultDimension": "1*2", + "landscapeLayouts": [""], + "portraitLayouts": [""], + "updateEnabled": true, + "scheduledUpateTime": "10:30", + "updateDuration": 0, + "deepLink": "", + "jsComponentName": "card", + "formVisibleNotify" : true, + "metaData": { + "customizeData": [ + { + "name": "originWidgetName", + "value": "myTest" + } + ] + } + } + ] + } + ], + "defPermissions": [ + { + "name": "com.permission.CAMERA", + "grantMode": "system_grant", + "availableScope": ["signature"], + "label": "CAMERA permission", + "description": "CAMERA permission in detail" + } + ], + "js": [ + { + "name": "card", + "pages": [ + "pages/index/index" + ], + "type": "form" + } + ] + } +} diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_A.h b/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_A.h new file mode 100755 index 0000000000000000000000000000000000000000..610caccc59c7c13bdcf5f2be0a3eabe5ea456860 --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_A.h @@ -0,0 +1,142 @@ +/* + * 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 FORM_ST_SERVICE_ABILITY_A_ +#define FORM_ST_SERVICE_ABILITY_A_ +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "form_provider_info.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; +const std::string APP_A_RESP_EVENT_NAME = "resp_com_ohos_formst_service_app_a"; +const std::string APP_A_REQ_EVENT_NAME = "req_com_ohos_formst_service_app_a"; +const std::string COMMON_EVENT_TEST_ACTION1 = "usual.event.test1"; +/** + * Form event trigger result + */ +typedef enum { + FORM_EVENT_TRIGGER_RESULT_NG = 0, + FORM_EVENT_TRIGGER_RESULT_OK = 1, +} FORM_EVENT_TRIGGER_RESULT; + +class FormStServiceAbilityA : public Ability { +public: + ~FormStServiceAbilityA(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + virtual FormProviderInfo OnCreate(const Want &want) override; + virtual void OnUpdate(const int64_t formId) override; + virtual void OnTriggerEvent(const int64_t formId, const std::string &message) override; + virtual void OnDelete(const int64_t formId) override; + virtual void OnCastTemptoNormal(const int64_t formId) override; + virtual void OnVisibilityChanged(const std::map &formEventsMap) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::vector Split(std::string str, const std::string &token); + bool SubscribeEvent(); + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + void StartOtherAbility(); + void ConnectOtherAbility(); + void DisConnectOtherAbility(); + void StopSelfAbility(); + + std::string shouldReturn_ = {}; + std::string targetBundle_ = {}; + std::string targetAbility_ = {}; + std::string nextTargetBundle_ = {}; + std::string nextTargetAbility_ = {}; + std::string targetBundleConn_ = {}; + std::string targetAbilityConn_ = {}; + std::string nextTargetBundleConn_ = {}; + std::string nextTargetAbilityConn_ = {}; + std::string zombie_ = {}; + + typedef void (FormStServiceAbilityA::*func)(); + static std::map funcMap_; + class AbilityConnectCallback; + sptr stub_ = {}; + sptr connCallback_ = {}; + class AppEventSubscriber; + std::shared_ptr subscriber_ = {}; + + class AbilityConnectCallback : public AbilityConnectionStub { + public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + PublishEvent(APP_A_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityConnectDone"); + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + PublishEvent(APP_A_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityDisconnectDone"); + } + } + + static int onAbilityConnectDoneCount; + }; + class AppEventSubscriber : public EventFwk::CommonEventSubscriber { + public: + AppEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + ~AppEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + FormStServiceAbilityA *mainAbility_ = nullptr; + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FORM_ST_SERVICE_ABILITY_A_ diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_a1.h b/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_a1.h old mode 100644 new mode 100755 index d50f4f3bc4da5b6309ef572c1c4b1be04333a10b..e5e30429343af0cdfe4aca95ac07ec9d7d07fd75 --- a/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_a1.h +++ b/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_a1.h @@ -46,7 +46,7 @@ protected: virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; virtual sptr OnConnect(const Want &want) override; virtual void OnDisconnect(const Want &want) override; - virtual FormProviderInfo OnCreateForm(const Want &want) override; + virtual FormProviderInfo OnCreate(const Want &want) override; private: void Clear(); diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_A.cpp b/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_A.cpp new file mode 100755 index 0000000000000000000000000000000000000000..e229ca09f08fa93e2f8f9cd9d08d5ca851d76f52 --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_A.cpp @@ -0,0 +1,370 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "form_st_service_ability_A.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "form_provider_client.h" + +using namespace OHOS::EventFwk; + +constexpr int64_t SEC_TO_MILLISEC = 1000; +constexpr int64_t MILLISEC_TO_NANOSEC = 1000000; + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; + +int FormStServiceAbilityA::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +std::map FormStServiceAbilityA::funcMap_ = { + {"StartOtherAbility", &FormStServiceAbilityA::StartOtherAbility}, + {"ConnectOtherAbility", &FormStServiceAbilityA::ConnectOtherAbility}, + {"DisConnectOtherAbility", &FormStServiceAbilityA::DisConnectOtherAbility}, + {"StopSelfAbility", &FormStServiceAbilityA::StopSelfAbility}, +}; + +FormStServiceAbilityA::~FormStServiceAbilityA() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +std::vector FormStServiceAbilityA::Split(std::string str, const std::string &token) +{ + APP_LOGI("FormStServiceAbilityA::Split"); + + std::vector splitString; + while (str.size()) { + size_t index = str.find(token); + if (index != std::string::npos) { + splitString.push_back(str.substr(0, index)); + str = str.substr(index + token.size()); + if (str.size() == 0) { + splitString.push_back(str); + } + } else { + splitString.push_back(str); + str = ""; + } + } + return splitString; +} +void FormStServiceAbilityA::StartOtherAbility() +{ + APP_LOGI("FormStServiceAbilityA::StartOtherAbility begin targetBundle=%{public}s, targetAbility=%{public}s", + targetBundle_.c_str(), + targetAbility_.c_str()); + APP_LOGI("FormStServiceAbilityA::StartOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + if (!targetBundle_.empty() && !targetAbility_.empty()) { + std::vector strtargetBundles = Split(targetBundle_, ","); + std::vector strTargetAbilitys = Split(targetAbility_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("targetBundleConn", nextTargetBundleConn_); + want.SetParam("targetAbilityConn", nextTargetAbilityConn_); + StartAbility(want); + sleep(1); + } + } +} +void FormStServiceAbilityA::ConnectOtherAbility() +{ + APP_LOGI( + "FormStServiceAbilityA::ConnectOtherAbility begin targetBundleConn=%{public}s, targetAbilityConn=%{public}s", + targetBundleConn_.c_str(), + targetAbilityConn_.c_str()); + APP_LOGI("FormStServiceAbilityA::ConnectOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + // connect service ability + if (!targetBundleConn_.empty() && !targetAbilityConn_.empty()) { + std::vector strtargetBundles = Split(targetBundleConn_, ","); + std::vector strTargetAbilitys = Split(targetAbilityConn_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("targetBundleConn", nextTargetBundleConn_); + want.SetParam("targetAbilityConn", nextTargetAbilityConn_); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + APP_LOGI("FormStServiceAbilityA::ConnectOtherAbility->ConnectAbility"); + bool ret = ConnectAbility(want, connCallback_); + sleep(1); + if (!ret) { + APP_LOGE("FormStServiceAbilityA::ConnectAbility failed!"); + } + } + } +} +void FormStServiceAbilityA::DisConnectOtherAbility() +{ + APP_LOGI("FormStServiceAbilityA::DisConnectOtherAbility begin"); + if (connCallback_ != nullptr) { + DisconnectAbility(connCallback_); + sleep(1); + } + APP_LOGI("FormStServiceAbilityA::DisConnectOtherAbility end"); +} + +void FormStServiceAbilityA::StopSelfAbility() +{ + APP_LOGI("FormStServiceAbilityA::StopSelfAbility"); + + TerminateAbility(); +} + +void FormStServiceAbilityA::OnStart(const Want &want) +{ + APP_LOGI("FormStServiceAbilityA::OnStart"); + + GetWantInfo(want); + Ability::OnStart(want); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); + SubscribeEvent(); + + // make exception for test + if (!zombie_.empty()) { + std::unique_ptr pWant = nullptr; + pWant->GetScheme(); + } +} +void FormStServiceAbilityA::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("FormStServiceAbilityA::OnCommand"); + + GetWantInfo(want); + Ability::OnCommand(want, restart, startId); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} +void FormStServiceAbilityA::OnNewWant(const Want &want) +{ + APP_LOGI("FormStServiceAbilityA::OnNewWant"); + + GetWantInfo(want); + Ability::OnNewWant(want); +} +void FormStServiceAbilityA::OnStop() +{ + APP_LOGI("FormStServiceAbilityA::OnStop"); + + Ability::OnStop(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); +} +void FormStServiceAbilityA::OnActive() +{ + APP_LOGI("FormStServiceAbilityA::OnActive"); + + Ability::OnActive(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} +void FormStServiceAbilityA::OnInactive() +{ + APP_LOGI("FormStServiceAbilityA::OnInactive"); + + Ability::OnInactive(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} +void FormStServiceAbilityA::OnBackground() +{ + APP_LOGI("FormStServiceAbilityA::OnBackground"); + + Ability::OnBackground(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); +} + +void FormStServiceAbilityA::Clear() +{ + shouldReturn_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; + targetBundleConn_ = ""; + targetAbilityConn_ = ""; + nextTargetBundle_ = ""; + nextTargetAbility_ = ""; + nextTargetBundleConn_ = ""; + nextTargetAbilityConn_ = ""; +} +void FormStServiceAbilityA::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn_ = mWant.GetStringParam("shouldReturn"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); + targetBundleConn_ = mWant.GetStringParam("targetBundleConn"); + targetAbilityConn_ = mWant.GetStringParam("targetAbilityConn"); + nextTargetBundle_ = mWant.GetStringParam("nextTargetBundle"); + nextTargetAbility_ = mWant.GetStringParam("nextTargetAbility"); + nextTargetBundleConn_ = mWant.GetStringParam("nextTargetBundleConn"); + nextTargetAbilityConn_ = mWant.GetStringParam("nextTargetAbilityConn"); + zombie_ = mWant.GetStringParam("zombie"); + FormStServiceAbilityA::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +bool FormStServiceAbilityA::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + APP_LOGI("FormStServiceAbilityA::PublishEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + code, + data.c_str()); + + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} +sptr FormStServiceAbilityA::OnConnect(const Want &want) +{ + APP_LOGI("FormStServiceAbilityA::OnConnect"); + + sptr formProviderClient = new (std::nothrow) FormProviderClient(); + std::shared_ptr thisAbility = this->shared_from_this(); + formProviderClient->SetOwner(thisAbility); + + return formProviderClient; +} +void FormStServiceAbilityA::OnDisconnect(const Want &want) +{ + APP_LOGI("FormStServiceAbilityA::OnDisconnect"); + + Ability::OnDisconnect(want); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); +} +bool FormStServiceAbilityA::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_A_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility_ = this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} +void FormStServiceAbilityA::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + auto dataContent = data.GetData(); + APP_LOGI("FormStServiceAbilityA::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + if (APP_A_REQ_EVENT_NAME.compare(eventName) == 0) { + if (funcMap_.find(dataContent) == funcMap_.end()) { + APP_LOGI( + "FormStServiceAbilityA::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + } else { + if (mainAbility_ != nullptr) { + (mainAbility_->*funcMap_[dataContent])(); + } + } + } +} + +FormProviderInfo FormStServiceAbilityA::OnCreate(const Want &want) +{ + APP_LOGI("%{public}s start", __func__); + FormProviderInfo formProviderInfo; + if(!want.HasParameter(Constants::PARAM_FORM_IDENTITY_KEY)) { + APP_LOGE("%{public}s, formId not exist", __func__); + return formProviderInfo; + } + std::string formId = want.GetStringParam(Constants::PARAM_FORM_IDENTITY_KEY); + std::string jsonData = std::string("{\"city\":\"beijingA\"}"); + FormProviderData formProviderData = FormProviderData(jsonData); + formProviderInfo.SetFormData(formProviderData); + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnCreate"); + APP_LOGI("%{public}s end, formId: %{public}s", __func__, formId.c_str()); + return formProviderInfo; +} + +void FormStServiceAbilityA::OnUpdate(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnUpdate"); + APP_LOGI("%{public}s end, formId: %{public}lld, current time: %{public}ld", __func__, formId, currentTime); +} + +void FormStServiceAbilityA::OnTriggerEvent(const int64_t formId, const std::string &message) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnTriggerEvent"); + APP_LOGI("%{public}s end, formId: %{public}lld, message: %{public}s, current time: %{public}ld", __func__, formId, message.c_str(), currentTime); +} + +void FormStServiceAbilityA::OnDelete(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnDelete"); + APP_LOGI("%{public}s end, formId: %{public}lld, current time: %{public}ld", __func__, formId, currentTime); +} + +void FormStServiceAbilityA::OnCastTemptoNormal(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnCastTemptoNormal"); + APP_LOGI("%{public}s end, formId: %{public}lld, current time: %{public}ld", __func__, formId, currentTime); +} + +void FormStServiceAbilityA::OnVisibilityChanged(const std::map &formEventsMap) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnVisibilityChanged"); + APP_LOGI("%{public}s end, current time: %{public}ld", __func__, currentTime); +} + +REGISTER_AA(FormStServiceAbilityA); +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_a1.cpp b/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_a1.cpp old mode 100644 new mode 100755 index dfe34180b5989830052433c54d296728e457686a..8a3d6e97ff72f23d2984f4ebc23169c90fef389e --- a/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_a1.cpp +++ b/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_a1.cpp @@ -287,7 +287,7 @@ void FormStServiceAbilityA1::AppEventSubscriber::OnReceiveEvent(const CommonEven } } -FormProviderInfo FormStServiceAbilityA1::OnCreateForm(const Want &want) +FormProviderInfo FormStServiceAbilityA1::OnCreate(const Want &want) { APP_LOGI("%{public}s start", __func__); FormProviderInfo formProviderInfo; diff --git a/test/resource/tools/ohos_test.xml b/test/resource/tools/ohos_test.xml index f9d16b228f692ae53b0ee19d0aed33f704929335..150b04469921247d4139b76c186d40d9bf690417 100644 --- a/test/resource/tools/ohos_test.xml +++ b/test/resource/tools/ohos_test.xml @@ -14,19 +14,19 @@ * limitations under the License. --> - + - + - +