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/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/threading/worker_pool.h b/interfaces/innerkits/task_dispatcher/include/threading/worker_pool.h index edf8a97adc088c81bcae6b0da232cf41d16ee3af..eee772130055a408da163b6e7be15d4d3cb2e53f 100644 --- a/interfaces/innerkits/task_dispatcher/include/threading/worker_pool.h +++ b/interfaces/innerkits/task_dispatcher/include/threading/worker_pool.h @@ -80,7 +80,7 @@ private: static bool IsRunning(int ctl); - static int GetStateFromControl(int ctl); + static int GetStateFromControl(unsigned int ctl); static int CombineToControl(unsigned int state, unsigned int count); diff --git a/interfaces/innerkits/task_dispatcher/src/threading/worker_pool.cpp b/interfaces/innerkits/task_dispatcher/src/threading/worker_pool.cpp index 137644970613b9da76e4abe79c47645dec7da7eb..957c392fbddd48a4255774edc539d49857bb38d5 100644 --- a/interfaces/innerkits/task_dispatcher/src/threading/worker_pool.cpp +++ b/interfaces/innerkits/task_dispatcher/src/threading/worker_pool.cpp @@ -237,44 +237,32 @@ bool WorkerPool::AddWorker(const std::shared_ptr &delegate, const std: return added; } std::unique_lock mLock(poolLock_); - std::shared_ptr newThread = nullptr; - - for (;;) { + std::shared_ptr workerThread = nullptr; + for(;;) { unsigned int value = control_.load(); int num = GetWorkingThreadNum(value); if (num >= thread_limit_) { - APP_LOGI("WorkerPool::AddWorker thread count exceed limits, num=%{public}d, limits=%{public}d", - num, - thread_limit_); + APP_LOGI("WorkerPool::AddWorker thread count exceed limits, num=%{public}d", num); break; } if (!IsRunning(value)) { - APP_LOGI("WorkerPool::AddWorker thread pool is not running. value=%{public}d, closing=%{public}d, " - "count_bits=%{public}d", + APP_LOGI("WorkerPool::AddWorker thread pool is not running. value=%{public}d, closing=%{public}d, ", value, - CLOSING, - COUNT_BITS); + CLOSING); break; } - if (CompareAndIncThreadNum(num)) { - newThread = std::make_shared(delegate, task, factory_); - if (newThread == nullptr) { + workerThread = std::make_shared(delegate, task, factory_); + if (workerThread == nullptr) { APP_LOGE("WorkerPool::AddWorker create thread fail"); break; } - - newThread->CreateThread(); - - APP_LOGI("WorkerPool::AddWorker create new thread"); - - pool_.emplace_back(newThread); + workerThread->CreateThread(); + pool_.emplace_back(workerThread); APP_LOGI("WorkerPool::AddWorker pool_ add thread ,POOL SIZE: %{public}zu", pool_.size()); - added = true; break; } - APP_LOGW("WorkerPool::AddWorker set thread state error. retry. "); } return added; @@ -319,7 +307,7 @@ bool WorkerPool::IsRunning(int ctl) return ctl < CLOSING; } -int WorkerPool::GetStateFromControl(int ctl) +int WorkerPool::GetStateFromControl(unsigned int ctl) { return ctl & ~CAPACITY; } @@ -327,7 +315,7 @@ int WorkerPool::GetStateFromControl(int ctl) void WorkerPool::AdvanceStateTo(unsigned int target) { APP_LOGI("WorkerPool::AdvanceStateTo begin"); - for (;;) { + for(;;) { unsigned int current = control_.load(); if ((current >= target) || CompareAndSet(control_, current, CombineToControl(target, GetWorkingThreadNum(current)))) { @@ -345,7 +333,7 @@ int WorkerPool::CombineToControl(unsigned int state, unsigned int count) bool WorkerPool::CompareAndIncThreadNum(int expect) { - int ctl = control_.load(); + unsigned int ctl = control_.load(); int state = GetStateFromControl(ctl); return CompareAndSet(control_, ctl, CombineToControl(state, expect + 1)); } @@ -367,7 +355,7 @@ bool WorkerPool::CompareAndDecThreadNum(int expect) bool WorkerPool::CompareAndDecNum(int expectCount) { - int curr = control_.load(); + unsigned int curr = control_.load(); int state = GetStateFromControl(curr); int expectControl = CombineToControl(state, expectCount); return CompareAndDecThreadNum(expectControl); diff --git a/interfaces/innerkits/test/moduletest/task_dispatcher/global_task_dispatcher_module_test/global_task_dispatcher_module_test.cpp b/interfaces/innerkits/test/moduletest/task_dispatcher/global_task_dispatcher_module_test/global_task_dispatcher_module_test.cpp index 6abe4204c16ef42f57e99d1b945f2e8798c004ca..b86f8b04693b658a729b98acb28c86a3a5bb83a3 100644 --- a/interfaces/innerkits/test/moduletest/task_dispatcher/global_task_dispatcher_module_test/global_task_dispatcher_module_test.cpp +++ b/interfaces/innerkits/test/moduletest/task_dispatcher/global_task_dispatcher_module_test/global_task_dispatcher_module_test.cpp @@ -55,7 +55,6 @@ void GlobalTaskDispatcherModuleTest::TearDown() std::shared_ptr GlobalTaskDispatcherModuleTest::GetMtGlobalTaskDispatcher(TaskPriority priority) const { - // TaskDispatcherContext context; std::shared_ptr ptrGlobalTaskDispatcher = context->GetGlobalTaskDispatcher(priority); return ptrGlobalTaskDispatcher; } 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..21e0da663c9fe20cc37ade115d4c89149b487bf0 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); @@ -203,6 +203,35 @@ HWTEST_F(SerialTaskDispatcherModuleTest, SerialTaskDispatcher_AsyncDispatchTest_ GTEST_LOG_(INFO) << name + " end"; } +void DelayDispatchTestWait (std::atomic &count){ + { + long wait = 100; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + } + { + long wait = 500; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 3); + } +} + /** * @tc.number: SerialTaskDispatcher_DelayDispatchTest_001 * @tc.name: DelayDispatch @@ -243,33 +272,7 @@ HWTEST_F(SerialTaskDispatcherModuleTest, SerialTaskDispatcher_DelayDispatchTest_ }), sleep3); EXPECT_TRUE(count.load() == 0); - - { - long wait = 100; - auto time = std::chrono::milliseconds(wait); - std::this_thread::sleep_for(time); - } - { - long wait = 1000; - GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); - auto time = std::chrono::milliseconds(wait); - std::this_thread::sleep_for(time); - EXPECT_TRUE(count.load() == 2); - } - { - long wait = 500; - GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); - auto time = std::chrono::milliseconds(wait); - std::this_thread::sleep_for(time); - EXPECT_TRUE(count.load() == 2); - } - { - long wait = 1000; - GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); - auto time = std::chrono::milliseconds(wait); - std::this_thread::sleep_for(time); - EXPECT_TRUE(count.load() == 3); - } + DelayDispatchTestWait(count); GTEST_LOG_(INFO) << name + " end"; } diff --git a/interfaces/innerkits/test/moduletest/task_dispatcher/spec_task_dispatcher_module_test/spec_task_dispatcher_module_test.cpp b/interfaces/innerkits/test/moduletest/task_dispatcher/spec_task_dispatcher_module_test/spec_task_dispatcher_module_test.cpp index d251f276ddc7fe8429f51db6ea7b744b7d33e7d6..ce6b5b3336e06a337b5b9118e45fab4778a90369 100644 --- a/interfaces/innerkits/test/moduletest/task_dispatcher/spec_task_dispatcher_module_test/spec_task_dispatcher_module_test.cpp +++ b/interfaces/innerkits/test/moduletest/task_dispatcher/spec_task_dispatcher_module_test/spec_task_dispatcher_module_test.cpp @@ -130,6 +130,35 @@ HWTEST_F(SpecTaskDispatcherModuleTest, SpecTaskDispatcher_AsyncDispatchTest_001, GTEST_LOG_(INFO) << name + " end"; } +void DelayDispatcherTestWait(std::atomic &count){ + { + long wait = 100; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + } + { + long wait = 500; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 3); + } +} + /** * @tc.number: SpecTaskDispatcher_DelayDispatchTest_001 * @tc.name: DelayDispatch @@ -170,33 +199,7 @@ HWTEST_F(SpecTaskDispatcherModuleTest, SpecTaskDispatcher_DelayDispatchTest_001, }), sleep3); EXPECT_TRUE(count.load() == 0); - - { - long wait = 100; - auto time = std::chrono::milliseconds(wait); - std::this_thread::sleep_for(time); - } - { - long wait = 1000; - GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); - auto time = std::chrono::milliseconds(wait); - std::this_thread::sleep_for(time); - EXPECT_TRUE(count.load() == 2); - } - { - long wait = 500; - GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); - auto time = std::chrono::milliseconds(wait); - std::this_thread::sleep_for(time); - EXPECT_TRUE(count.load() == 2); - } - { - long wait = 1000; - GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); - auto time = std::chrono::milliseconds(wait); - std::this_thread::sleep_for(time); - EXPECT_TRUE(count.load() == 3); - } + DelayDispatcherTestWait(count); GTEST_LOG_(INFO) << name + " end"; } diff --git a/kits/appkit/napi/bundlemgr/permission_callback.cpp b/kits/appkit/napi/bundlemgr/permission_callback.cpp index 3b8d3b4f955da7a232fdb9e40298ae000d538f51..57d65185bd703dcb5317f3eb5cb51111b9d3c1cc 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; } @@ -39,16 +38,23 @@ void PermissionCallback::OnChanged(const int32_t uid) napi_get_uv_event_loop(env_, &loop); #endif // NAPI_VERSION >= 2 - uv_work_t *work = new uv_work_t; - CallbackInfo *callbackInfo = new (std::nothrow) CallbackInfo{ + 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) {}, @@ -76,6 +82,13 @@ void PermissionCallback::OnChanged(const int32_t uid) delete event; delete work; }); - + 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/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/services/appmgr/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp b/services/appmgr/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp index 65fd2f308ab0de9b1989520ee00f3e5138ad7bce..2ef83591008e1ab45242096875fa7d6ea983b5e6 100644 --- a/services/appmgr/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp +++ b/services/appmgr/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp @@ -129,12 +129,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_001, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_001 end"); } @@ -171,13 +171,13 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_002, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); sptr token2 = GetMockToken(); @@ -195,10 +195,10 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_002, TestSize.Level1) const uint32_t EXPECT_MAP_SIZE = 2; EXPECT_EQ(recordMap.size(), EXPECT_MAP_SIZE); auto record2 = service_->GetAppRunningRecordByAppName(GetTestAppName() + "_1"); - ASSERT_NE(record2, nullptr); + EXPECT_NE(record2, nullptr); EXPECT_EQ(record2->GetState(), ApplicationState::APP_STATE_CREATE); auto abilityRecord2 = record2->GetAbilityRunningRecordByToken(token2); - ASSERT_NE(abilityRecord2, nullptr); + EXPECT_NE(abilityRecord2, nullptr); EXPECT_EQ(abilityRecord2->GetState(), AbilityState::ABILITY_STATE_CREATE); APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_002 end"); } @@ -348,12 +348,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_007, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); std::shared_ptr mockClientPtr = std::make_shared(); EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(0); @@ -394,12 +394,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_008, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); sptr token2 = new MockAbilityToken(); sptr preToken = token; @@ -418,7 +418,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_008, TestSize.Level1) const auto &abilityMap2 = record2->GetAbilities(); EXPECT_EQ(abilityMap2.size(), EXPECT_MAP_SIZE); auto abilityRecord2 = record2->GetAbilityRunningRecordByToken(token2); - ASSERT_NE(abilityRecord2, nullptr); + EXPECT_NE(abilityRecord2, nullptr); EXPECT_EQ(abilityRecord2->GetState(), AbilityState::ABILITY_STATE_CREATE); EXPECT_EQ(abilityRecord2->GetPreToken(), token); APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_008 end"); @@ -455,7 +455,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, RequestProcess_001, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); EXPECT_EQ(record->GetPriorityObject()->GetPid(), PID); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); APP_LOGI("AmsServiceLoadAbilityProcessTest RequestProcess_001 end"); @@ -582,12 +582,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LaunchMode_001, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); APP_LOGI("AmsServiceLoadAbilityProcessTest LaunchMode_001 end"); } @@ -619,12 +619,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LaunchMode_002, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); std::shared_ptr mockClientPtr = std::make_shared(); EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(0); @@ -666,12 +666,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_001, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); sptr token2 = new MockAbilityToken(); auto abilityInfo2 = std::make_shared(); @@ -690,7 +690,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_001, TestSize.Level1) const auto &abilityMap1 = record1->GetAbilities(); EXPECT_EQ(abilityMap1.size(), (uint32_t)2); auto abilityrecord1 = record1->GetAbilityRunningRecordByToken(token2); - ASSERT_NE(abilityrecord1, nullptr); + EXPECT_NE(abilityrecord1, nullptr); EXPECT_EQ(abilityrecord1->GetState(), AbilityState::ABILITY_STATE_READY); APP_LOGI("AmsServiceLoadAbilityProcessTest StartAbility_001 end"); } @@ -720,12 +720,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_002, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); sptr token2 = new MockAbilityToken(); auto abilityInfo2 = std::make_shared(); @@ -773,12 +773,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_003, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); sptr token2 = new MockAbilityToken(); @@ -825,12 +825,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_004, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); auto abilityInfo2 = std::make_shared(); abilityInfo2->name = GetTestAbilityName() + "_1"; @@ -876,12 +876,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_005, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); sptr token2 = new MockAbilityToken(); auto abilityInfo2 = std::make_shared(); @@ -898,7 +898,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_005, TestSize.Level1) const auto &abilityMap1 = record1->GetAbilities(); EXPECT_EQ(abilityMap1.size(), (uint32_t)2); auto abilityrecord1 = record1->GetAbilityRunningRecordByToken(token2); - ASSERT_NE(abilityrecord1, nullptr); + EXPECT_NE(abilityrecord1, nullptr); EXPECT_EQ(abilityrecord1->GetState(), AbilityState::ABILITY_STATE_READY); APP_LOGI("AmsServiceLoadAbilityProcessTest StartAbility_005 end"); } @@ -928,12 +928,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_006, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); auto abilityInfo2 = std::make_shared(); abilityInfo2->name = GetTestAbilityName() + "_1"; @@ -983,12 +983,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartProcess001, TestSize.Level1) EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record1 = service_->GetAppRunningRecordByAppName(GetTestAppName()); EXPECT_EQ(record1->GetPriorityObject()->GetPid(), PID); - ASSERT_NE(record1, nullptr); + EXPECT_NE(record1, nullptr); EXPECT_EQ(record1->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record1->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record1->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); APP_LOGI("AmsServiceLoadAbilityProcessTest StartProcess001 end"); } @@ -1019,7 +1019,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartProcess002, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record1 = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record1, nullptr); + EXPECT_NE(record1, nullptr); APP_LOGI("AmsServiceLoadAbilityProcessTest StartProcess002 end"); } @@ -1050,7 +1050,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartProcess003, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record1 = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record1, nullptr); + EXPECT_NE(record1, nullptr); APP_LOGI("AmsServiceLoadAbilityProcessTest StartProcess003 end"); } @@ -1083,7 +1083,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartProcess004, TestSize.Level1) .WillOnce(DoAll(SetArgReferee<1>(PID), Return(ERR_TIMED_OUT))); std::shared_ptr record = service_->GetOrCreateAppRunningRecord(token, appInfo, abilityInfo, GetTestAppName(), 0, result); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); service_->StartProcess(abilityInfo->applicationName, GetTestAppName(), record); auto record1 = service_->GetAppRunningRecordByAppRecordId(record->GetRecordId()); EXPECT_EQ(record1, nullptr); diff --git a/services/bundlemgr/include/bundle_data_storage.h b/services/bundlemgr/include/bundle_data_storage.h index 13a7cf551b4abbcacd7df0586b9ac899e3a5c968..22e46e9b4fee24bae61d7518a782a2489f3ae2e0 100644 --- a/services/bundlemgr/include/bundle_data_storage.h +++ b/services/bundlemgr/include/bundle_data_storage.h @@ -47,7 +47,11 @@ public: */ virtual bool DeleteStorageBundleInfo(const std::string &deviceId, const InnerBundleInfo &innerBundleInfo); - virtual bool ResetKvStore() { return true;} + virtual bool ResetKvStore() + { + return true; + } + private: bool KeyToDeviceAndName(const std::string &key, std::string &deviceId, std::string &bundleName) const; void DeviceAndNameToKey(const std::string &deviceId, const std::string &bundleName, std::string &key) const; diff --git a/services/bundlemgr/include/bundle_data_storage_database.h b/services/bundlemgr/include/bundle_data_storage_database.h index 201116725631f48771b7e3297ce1dd6098c91b78..221aad0eef91e7d0151a06d1cfb60e51ab4f9c75 100644 --- a/services/bundlemgr/include/bundle_data_storage_database.h +++ b/services/bundlemgr/include/bundle_data_storage_database.h @@ -69,7 +69,6 @@ private: void DeviceAndNameToKey(const std::string &deviceId, const std::string &bundleName, std::string &key) const; DistributedKv::DistributedKvDataManager dataManager_; std::unique_ptr kvStorePtr_; - // std::shared_ptr dataChangeListener_; mutable std::mutex kvStorePtrMutex_; }; diff --git a/services/bundlemgr/include/bundle_mgr_host_impl.h b/services/bundlemgr/include/bundle_mgr_host_impl.h index 8c2b84b3afd8a1186bf0dbaf85dffb197fb9bd91..6b2b02264247d793c0e8f3b68d8d98404341215a 100644 --- a/services/bundlemgr/include/bundle_mgr_host_impl.h +++ b/services/bundlemgr/include/bundle_mgr_host_impl.h @@ -364,13 +364,14 @@ public: * @return Returns true if GetShortcutInfos successfully; returns false otherwise. */ virtual bool GetShortcutInfos(const std::string &bundleName, std::vector &shortcutInfos) override; - /** + /** * @brief Get module usage record list in descending order of lastLaunchTime. * @param maxNum the return size of the records, must be in range of 1 to 1000. * @param moduleUsageRecords List of ModuleUsageRecord objects if obtained. * @return Returns true if this function is successfully called; returns false otherwise. */ - virtual bool GetModuleUsageRecords(const int32_t number, std::vector &moduleUsageRecords) override; + virtual bool GetModuleUsageRecords( + const int32_t number, std::vector &moduleUsageRecords) override; /** * @brief Notify a specified ability for activity. * @param bundleName Indicates the bundle name of the ability to activity. diff --git a/services/bundlemgr/include/bundle_permissions_changed_monitor.h b/services/bundlemgr/include/bundle_permissions_changed_monitor.h index ff4bb61f418f01566bfbbd5866f73c51ec9fd1aa..e3912891c06d71aba869bf9695e361ace4c9296a 100644 --- a/services/bundlemgr/include/bundle_permissions_changed_monitor.h +++ b/services/bundlemgr/include/bundle_permissions_changed_monitor.h @@ -28,7 +28,6 @@ #include "json_serializer.h" #include "app_log_wrapper.h" - #include "bundle_parser.h" #include "installd_client.h" #include "bundle_permission_mgr.h" @@ -37,13 +36,15 @@ namespace OHOS { namespace AppExecFwk { class BundlePermissionsChangedMonitor : public EventFwk::CommonEventSubscriber { public: - BundlePermissionsChangedMonitor(const std::shared_ptr &dataMgr, - const EventFwk::CommonEventSubscribeInfo& sp):CommonEventSubscriber(sp) + BundlePermissionsChangedMonitor( + const std::shared_ptr &dataMgr, const EventFwk::CommonEventSubscribeInfo &sp) + : CommonEventSubscriber(sp) { dataMgr_ = dataMgr; } - ~BundlePermissionsChangedMonitor(){ - if(!dataMgr_){ + ~BundlePermissionsChangedMonitor() + { + if (!dataMgr_) { dataMgr_.reset(); } } @@ -52,10 +53,11 @@ public: OHOS::AAFwk::Want want = data.GetWant(); std::string action = want.GetAction(); int32_t uid = data.GetCode(); - if ( dataMgr_ != nullptr && uid >=0 ) { + if (dataMgr_ != nullptr && uid >= 0) { dataMgr_->NotifyPermissionsChanged(uid); } } + private: std::shared_ptr dataMgr_; }; 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..838a37b8dda544c155a8b724b747aeff94771b9d 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; diff --git a/services/bundlemgr/include/kvstore_death_recipient_callback.h b/services/bundlemgr/include/kvstore_death_recipient_callback.h index 9b575b3ac24d183a2273de3e7ea9ce6d8b6009c1..83e5b287f184c5e94aff0b508ffbfacbb1a4b7d0 100644 --- a/services/bundlemgr/include/kvstore_death_recipient_callback.h +++ b/services/bundlemgr/include/kvstore_death_recipient_callback.h @@ -27,9 +27,8 @@ public: virtual ~KvStoreDeathRecipientCallback(); virtual void OnRemoteDied() override; - }; -} // namespace AppExecFwk -} // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_KVSTORE_DEATH_RECIPIENT_CALLBACK_H \ No newline at end of file +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_KVSTORE_DEATH_RECIPIENT_CALLBACK_H \ No newline at end of file diff --git a/services/bundlemgr/include/module_usage_data_storage.h b/services/bundlemgr/include/module_usage_data_storage.h index d8c7e6a1598341f67666e3f1f25c441a5d32181b..d9259a57a0b604b646356d9f922f05954407ccb9 100644 --- a/services/bundlemgr/include/module_usage_data_storage.h +++ b/services/bundlemgr/include/module_usage_data_storage.h @@ -25,7 +25,6 @@ #include "distributed_kv_data_manager.h" #include "inner_bundle_info.h" - namespace OHOS { namespace AppExecFwk { class DataMgr; @@ -36,36 +35,36 @@ public: virtual ~ModuleUsageRecordStorage(); // add&update - bool AddOrUpdateRecord(ModuleUsageRecord& data, const std::string& deviceId, int32_t userId); + bool AddOrUpdateRecord(ModuleUsageRecord &data, const std::string &deviceId, int32_t userId); bool DeleteRecordByUserId(int32_t userId); - bool DeleteUsageRecord(const InnerBundleInfo& data, int32_t userId); + bool DeleteUsageRecord(const InnerBundleInfo &data, int32_t userId); bool MarkUsageRecordRemoved(const InnerBundleInfo &data, int32_t userId); - bool QueryRecordByNum(int32_t maxNum, std::vector& records, int32_t userId); - void SetDataMgr(const std::weak_ptr& dataMgr) const; + bool QueryRecordByNum(int32_t maxNum, std::vector &records, int32_t userId); + void SetDataMgr(const std::weak_ptr &dataMgr) const; void OnKvStoreDeath(); void RegisterKvStoreDeathListener(); -private: - bool DeleteRecordByKeys(const std::string& bundleName, std::vector& keys); - bool QueryRecordByCondition(DistributedKv::DataQuery& query, std::vector& records); - void AbilityRecordToKey(const std::string& userId, const std::string& deviceId, - const std::string& bundleName, const std::string& moduleName, std::string& key) const; - void InnerBundleInfoToKeys(const InnerBundleInfo& data, int32_t userId, - std::vector& keys) const; - void FillDataStorageKeys(const std::string& userId, const std::string& bundleName, - const std::string& moduleName, std::vector& keys) const; - bool ParseKey(const std::string& key, ModuleUsageRecord& record) const; - void UpdateUsageRecord(const std::string& jsonString, ModuleUsageRecord& data); - void SaveEntries(const std::vector& allEntries, - std::vector& records) const; - void TryTwice(const std::function& func) const; +private: + bool DeleteRecordByKeys(const std::string &bundleName, std::vector &keys); + bool QueryRecordByCondition(DistributedKv::DataQuery &query, std::vector &records); + void AbilityRecordToKey(const std::string &userId, const std::string &deviceId, const std::string &bundleName, + const std::string &moduleName, std::string &key) const; + void InnerBundleInfoToKeys( + const InnerBundleInfo &data, int32_t userId, std::vector &keys) const; + void FillDataStorageKeys(const std::string &userId, const std::string &bundleName, const std::string &moduleName, + std::vector &keys) const; + bool ParseKey(const std::string &key, ModuleUsageRecord &record) const; + void UpdateUsageRecord(const std::string &jsonString, ModuleUsageRecord &data); + void SaveEntries( + const std::vector &allEntries, std::vector &records) const; + void TryTwice(const std::function &func) const; bool CheckKvStore(); DistributedKv::Status GetKvStore(); bool ResetKvStore(); private: - const DistributedKv::AppId appId_ { Constants::APP_ID }; - const DistributedKv::StoreId storeId_ { Constants::ABILITY_USAGE_STORE_ID }; + const DistributedKv::AppId appId_{Constants::APP_ID}; + const DistributedKv::StoreId storeId_{Constants::ABILITY_USAGE_STORE_ID}; DistributedKv::DistributedKvDataManager dataManager_; std::unique_ptr kvStorePtr_; mutable std::mutex kvStorePtrMutex_; @@ -78,6 +77,6 @@ private: }; }; -} // namespace AppExecFwk -} // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_MODULE_USAGE_DATA_STORAGE_H \ No newline at end of file +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_MODULE_USAGE_DATA_STORAGE_H \ No newline at end of file diff --git a/services/bundlemgr/include/permission_changed_death_recipient.h b/services/bundlemgr/include/permission_changed_death_recipient.h index 1f4e04072fbf3be8a4ceebf133acdeeab898a291..8c9b0aab416eb39b527f7f7252485cba68e7dc7f 100644 --- a/services/bundlemgr/include/permission_changed_death_recipient.h +++ b/services/bundlemgr/include/permission_changed_death_recipient.h @@ -26,9 +26,9 @@ namespace AppExecFwk { class PermissionChangedDeathRecipient : public IRemoteObject::DeathRecipient { public: - virtual void OnRemoteDied(const wptr& object) override; + virtual void OnRemoteDied(const wptr &object) override; }; -} // namespace AppExecFwk -} // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_PERMISSION_CHANGED_DEATH_RECIPIENT_H \ No newline at end of file +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_PERMISSION_CHANGED_DEATH_RECIPIENT_H \ No newline at end of file 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_data_mgr.cpp b/services/bundlemgr/src/bundle_data_mgr.cpp index 1c61ef23952b1c590e001b34c1031709b134bf85..4b210e214c53acdf0f21eb13a4bbed666e82a1b6 100755 --- a/services/bundlemgr/src/bundle_data_mgr.cpp +++ b/services/bundlemgr/src/bundle_data_mgr.cpp @@ -1620,7 +1620,8 @@ bool BundleDataMgr::UnregisterPermissionsChanged(const sptr lock(allPermissionsChangedLock_); - for (auto allPermissionsItem = allPermissionsCallbacks_.begin(); allPermissionsItem != allPermissionsCallbacks_.end();) { + for (auto allPermissionsItem = allPermissionsCallbacks_.begin(); + allPermissionsItem != allPermissionsCallbacks_.end();) { if ((*allPermissionsItem)->AsObject() == callback->AsObject()) { allPermissionsItem = allPermissionsCallbacks_.erase(allPermissionsItem); APP_LOGI("unregister from all permissions callbacks success!"); diff --git a/services/bundlemgr/src/bundle_mgr_host_impl.cpp b/services/bundlemgr/src/bundle_mgr_host_impl.cpp index a68c60b46b0c5566af8bd5f4734690e4605c7627..03c8fed2c3cc9f33bea72200778eb9621db9807f 100755 --- a/services/bundlemgr/src/bundle_mgr_host_impl.cpp +++ b/services/bundlemgr/src/bundle_mgr_host_impl.cpp @@ -486,8 +486,8 @@ bool BundleMgrHostImpl::RequestPermissionFromUser( APP_LOGI("send Permissions Changed event"); BundleInfo info; bool ret_getInfo = GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, info); - APP_LOGI("ret_getInfo = %{public}d",ret_getInfo); - if ( ret && ret_getInfo) { + APP_LOGI("ret_getInfo = %{public}d", ret_getInfo); + if (ret && ret_getInfo) { Want want; want.SetAction("PERMISSIONS_CHANGED_EVENT"); EventFwk::CommonEventData commonData; @@ -516,7 +516,7 @@ bool BundleMgrHostImpl::RegisterPermissionsChanged( APP_LOGE("DataMgr is nullptr"); return false; } - return dataMgr->RegisterPermissionsChanged(uids,callback); + return dataMgr->RegisterPermissionsChanged(uids, callback); } bool BundleMgrHostImpl::UnregisterPermissionsChanged(const sptr &callback) diff --git a/services/bundlemgr/src/bundle_permission_mgr.cpp b/services/bundlemgr/src/bundle_permission_mgr.cpp index 91a84da1179df22393513352609afd6987dfe6ab..524d2e9bb3cecd62010fb8ac1e185670e8916db7 100644 --- a/services/bundlemgr/src/bundle_permission_mgr.cpp +++ b/services/bundlemgr/src/bundle_permission_mgr.cpp @@ -59,15 +59,15 @@ bool ConvertPermissionDef( permDef.availableScope = [&defPermission]() -> int { unsigned flag = 0; if (std::find(defPermission.availableScope.begin(), - defPermission.availableScope.end(), - ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_AVAILABLESCOPE_SIGNATURE) != - defPermission.availableScope.end()) { + defPermission.availableScope.end(), + ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_AVAILABLESCOPE_SIGNATURE) != + defPermission.availableScope.end()) { flag |= Permission::AvailableScope::AVAILABLE_SCOPE_SIGNATURE; } if (std::find(defPermission.availableScope.begin(), - defPermission.availableScope.end(), - ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_AVAILABLESCOPE_RESTRICTED) != - defPermission.availableScope.end()) { + defPermission.availableScope.end(), + ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_AVAILABLESCOPE_RESTRICTED) != + defPermission.availableScope.end()) { flag |= Permission::AvailableScope::AVAILABLE_SCOPE_RESTRICTED; } if (flag == 0) { @@ -300,8 +300,8 @@ bool BundlePermissionMgr::CheckCallingPermission(const std::string &permissionNa APP_LOGI( "get app bundleName %{public}s and permissionName %{public}s", bundleName.c_str(), permissionName.c_str()); ApplicationInfo appInfo; - bool ret = dataMgr->GetApplicationInfo(bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, - Constants::DEFAULT_USERID, appInfo); + bool ret = dataMgr->GetApplicationInfo( + bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, Constants::DEFAULT_USERID, appInfo); if (ret && appInfo.isLauncherApp && (permissionName == Constants::PERMISSION_INSTALL_BUNDLE)) { APP_LOGE("launcher app %{public}s pass through", bundleName.c_str()); return true; diff --git a/services/bundlemgr/src/bundle_profile.cpp b/services/bundlemgr/src/bundle_profile.cpp index 1f53df16c4e44d21b56a543c6c2798e029306fab..9986fc133fcc78c924588b10dd71104528833939 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) @@ -1675,11 +1684,11 @@ bool CheckBundleNameIsValid(const std::string &bundleName) return false; } char head = bundleName.at(0); - if (head < 'A' || ('Z' < head && head < 'a') || head > 'z') { + if (head < 'A' || (head > 'Z' && head < 'a') || head > 'z') { return false; } for (const auto &c : bundleName) { - if (c < '.' || c == '/' || ('9' < c && c < 'A') || ('Z' < c && c < '_') || c == '`' || c > 'z') { + if (c < '.' || c == '/' || (c > '9' && c < 'A') || (c > 'Z' && c < '_') || c == '`' || c > 'z') { return false; } } @@ -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/bundle_util.cpp b/services/bundlemgr/src/bundle_util.cpp index 9dd08b4590d02aa9e53fd805bb1831cd5b0d32cc..c6500946ff128a758644479c90d0c1b5f4db4f72 100644 --- a/services/bundlemgr/src/bundle_util.cpp +++ b/services/bundlemgr/src/bundle_util.cpp @@ -44,7 +44,7 @@ ErrCode BundleUtil::CheckFilePath(const std::string &bundlePath, std::string &re APP_LOGE("can not access the bundle file path: %{private}s", realPath.c_str()); return ERR_APPEXECFWK_INSTALL_INVALID_BUNDLE_FILE; } - if(!CheckFileSize(realPath, Constants::MAX_HAP_SIZE)) { + if (!CheckFileSize(realPath, Constants::MAX_HAP_SIZE)) { APP_LOGE("file size is larger than max size Max size is: %{public}d", Constants::MAX_HAP_SIZE); return ERR_APPEXECFWK_INSTALL_INVALID_HAP_SIZE; } @@ -83,11 +83,11 @@ bool BundleUtil::CheckFileName(const std::string &fileName) bool BundleUtil::CheckFileSize(const std::string &bundlePath, const int32_t fileSize) { - struct stat fileInfo = { 0 }; - if (stat(bundlePath.c_str(), &fileInfo) != 0) { + struct stat fileInfo = {0}; + if (stat(bundlePath.c_str(), &fileInfo) != 0) { APP_LOGE("call stat error"); - return false; - } + return false; + } if (fileInfo.st_size > fileSize) { return false; } diff --git a/services/bundlemgr/src/inner_bundle_info.cpp b/services/bundlemgr/src/inner_bundle_info.cpp index 5e6bd27c983e003a1b7329b67f26637f19e349e1..fe8119bca3ade73a9f6ce9720e70d85152b9f851 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,48 +74,40 @@ InnerBundleInfo::~InnerBundleInfo() void to_json(nlohmann::json &jsonObject, const Distro &distro) { - jsonObject = nlohmann::json{ - {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DELIVERY_WITH_INSTALL, distro.deliveryWithInstall}, + 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}, - {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_MODULE_INSTALLATION_FREE, distro.installationFree} - }; + {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_MODULE_INSTALLATION_FREE, distro.installationFree}}; } void to_json(nlohmann::json &jsonObject, const UsedScene &usedScene) { - jsonObject = nlohmann::json{ - {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_ABILITY, usedScene.ability}, - {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_WHEN, usedScene.when} - }; + jsonObject = nlohmann::json{{ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_ABILITY, usedScene.ability}, + {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_WHEN, usedScene.when}}; } void to_json(nlohmann::json &jsonObject, const ReqPermission &reqPermission) { - jsonObject = nlohmann::json{ - {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_NAME, reqPermission.name}, + 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} - }; + {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_USEDSCENE, reqPermission.usedScene}}; } void to_json(nlohmann::json &jsonObject, const DefPermission &defPermission) { - jsonObject = nlohmann::json{ - {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_NAME, defPermission.name}, + 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}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_LABEL, defPermission.label}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_LABEL_ID, defPermission.labelId}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_DESCRIPTION, defPermission.description}, - {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_DESCRIPTION_ID, defPermission.descriptionId} - }; + {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_DESCRIPTION_ID, defPermission.descriptionId}}; } void to_json(nlohmann::json &jsonObject, const InnerModuleInfo &info) { - jsonObject = nlohmann::json{ - {MODULE_PACKAGE, info.modulePackage}, + jsonObject = nlohmann::json{{MODULE_PACKAGE, info.modulePackage}, {MODULE_NAME, info.moduleName}, {MODULE_PATH, info.modulePath}, {MODULE_DATA_DIR, info.moduleDataDir}, @@ -132,28 +125,24 @@ 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{ - {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_SCHEME, uri.scheme}, + 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}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_PATH, uri.path}, - {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_TYPE, uri.type} - }; + {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_TYPE, uri.type}}; } void to_json(nlohmann::json &jsonObject, const Skill &skill) { - jsonObject = nlohmann::json{ - {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_ACTIONS, skill.actions}, + 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} - }; + {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_URIS, skill.uris}}; } void InnerBundleInfo::ToJson(nlohmann::json &jsonObject) const @@ -174,7 +163,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 +275,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, @@ -581,22 +578,10 @@ int32_t InnerBundleInfo::FromJson(const nlohmann::json &jsonObject) true, ProfileReader::parseResult, ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - UID, - uid_, - JsonType::NUMBER, - true, - ProfileReader::parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - GID, - gid_, - JsonType::NUMBER, - true, - ProfileReader::parseResult, - ArrayType::NOT_ARRAY); + GetValueIfFindKey( + jsonObject, jsonObjectEnd, UID, uid_, JsonType::NUMBER, true, ProfileReader::parseResult, ArrayType::NOT_ARRAY); + GetValueIfFindKey( + jsonObject, jsonObjectEnd, GID, gid_, JsonType::NUMBER, true, ProfileReader::parseResult, ArrayType::NOT_ARRAY); GetValueIfFindKey(jsonObject, jsonObjectEnd, BASE_DATA_DIR, @@ -685,15 +670,15 @@ int32_t InnerBundleInfo::FromJson(const nlohmann::json &jsonObject) true, ProfileReader::parseResult, ArrayType::NOT_ARRAY); - GetValueIfFindKey>>(jsonObject, - jsonObjectEnd, - MODULE_FORMS, - formInfos_, - JsonType::OBJECT, - true, - ProfileReader::parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey>(jsonObject, + GetValueIfFindKey>>(jsonObject, + jsonObjectEnd, + MODULE_FORMS, + formInfos_, + JsonType::OBJECT, + true, + ProfileReader::parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey>(jsonObject, jsonObjectEnd, MODULE_SHORTCUT, shortcutInfos_, @@ -725,7 +710,7 @@ std::optional> InnerBundleInfo::FindSkills(const std::string if (skills.empty()) { return std::nullopt; } - return std::optional> {skills}; + return std::optional>{skills}; } std::optional InnerBundleInfo::FindHapModuleInfo(const std::string &modulePackage) const @@ -742,6 +727,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) { @@ -948,10 +934,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) { + APP_LOGE("can not find hapmoduleinfo %{public}s", info.second.moduleName.c_str()); + } else { + 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); + } if (info.second.isEntry) { bundleInfo.mainEntry = info.second.modulePackage; bundleInfo.entryModuleName = info.second.moduleName; @@ -982,29 +974,29 @@ 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); + } } std::optional InnerBundleInfo::GetInnerModuleInfoByModuleName(const std::string &moduleName) const diff --git a/services/bundlemgr/src/installd/installd_host_impl.cpp b/services/bundlemgr/src/installd/installd_host_impl.cpp index b850b712abb444dd6dc3fe21a55ee7c6a67f4e13..e12775312a225d0ea23a30a1f9e025c44bdbb0e7 100644 --- a/services/bundlemgr/src/installd/installd_host_impl.cpp +++ b/services/bundlemgr/src/installd/installd_host_impl.cpp @@ -173,24 +173,15 @@ ErrCode InstalldHostImpl::CreateModuleDataDir( for (auto &abilityDir : abilityDirs) { if (!InstalldOperator::MkOwnerDir( - createDir + abilityDir + Constants::PATH_SEPARATOR + Constants::DATA_DIR, - true, - uid, - gid)) { + createDir + abilityDir + Constants::PATH_SEPARATOR + Constants::DATA_DIR, true, uid, gid)) { return ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED; } if (!InstalldOperator::MkOwnerDir( - createDir + abilityDir + Constants::PATH_SEPARATOR + Constants::CACHE_DIR, - true, - uid, - gid)) { + createDir + abilityDir + Constants::PATH_SEPARATOR + Constants::CACHE_DIR, true, uid, gid)) { return ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED; } if (!InstalldOperator::MkOwnerDir( - createDir + abilityDir + Constants::PATH_SEPARATOR + Constants::DATA_BASE_DIR, - true, - uid, - gid)) { + createDir + abilityDir + Constants::PATH_SEPARATOR + Constants::DATA_BASE_DIR, true, uid, gid)) { return ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED; } if (!InstalldOperator::MkOwnerDir( diff --git a/services/bundlemgr/src/kvstore_death_recipient_callback.cpp b/services/bundlemgr/src/kvstore_death_recipient_callback.cpp index 3b1eb834f4b88b23da6b25156fb37dd1cb254896..f44f619917be036ad5330d5100f97369217997ac 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,7 +63,7 @@ void KvStoreDeathRecipientCallback::OnRemoteDied() // init kvStore. if (dataStorage && dataStorage->ResetKvStore()) { // register data change listener again. - //dataStorage->RegisterChangeListener(); + // dataStorage->RegisterChangeListener(); APP_LOGI("current times is %{public}d", times); // auto service = DelayedSingleton::GetInstance(); // std::shared_ptr handler = service->GetEventHandler(); @@ -79,5 +79,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..049dd08db23344be1b2c22204a416a6c5dc3cb94 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 = "#"; @@ -321,8 +320,8 @@ Status ModuleUsageRecordStorage::GetKvStore() { Status status; Options options = { - .createIfMissing = true, .encrypt = false, .autoSync = true, .kvStoreType = KvStoreType::SINGLE_VERSION}; - + .createIfMissing = true, .encrypt = false, .autoSync = true, .kvStoreType = KvStoreType::SINGLE_VERSION + }; options.schema = SCHEMA_DEFINE; dataManager_.GetSingleKvStore( options, appId_, storeId_, [this, &status](Status paramStatus, std::unique_ptr singleKvStore) { diff --git a/services/bundlemgr/test/mock/include/json_constants.h b/services/bundlemgr/test/mock/include/json_constants.h index 7019d89acf34eeadbbb7e47eef3e63608ee9cbdf..6a9af870d25d68086af83d49be976c3a7d7475b2 100644 --- a/services/bundlemgr/test/mock/include/json_constants.h +++ b/services/bundlemgr/test/mock/include/json_constants.h @@ -21,7 +21,6 @@ namespace OHOS { namespace AppExecFwk { namespace JsonConstants { - const nlohmann::json NOT_STRING_TYPE = R"( { "number": 234, @@ -65,7 +64,6 @@ const nlohmann::json NOT_ARRAY_TYPE = R"( "object": {} } )"_json; - } // namespace JsonConstants } // namespace AppExecFwk } // namespace OHOS diff --git a/services/bundlemgr/test/mock/include/mock_ability_mgr_host.h b/services/bundlemgr/test/mock/include/mock_ability_mgr_host.h index df955fb47263a5e3626369d68303e92d2459305a..e4fe336ac08f2251b91eb8d6d08a96829a26b0cc 100644 --- a/services/bundlemgr/test/mock/include/mock_ability_mgr_host.h +++ b/services/bundlemgr/test/mock/include/mock_ability_mgr_host.h @@ -180,7 +180,7 @@ public: } int SetMissionDescriptionInfo( - const sptr &token, const MissionDescriptionInfo &missionDescriptionInfo) override + const sptr &token, const MissionDescriptionInfo &missionDescInfo) override { return 0; } diff --git a/services/bundlemgr/test/mock/include/mock_bundle_status.h b/services/bundlemgr/test/mock/include/mock_bundle_status.h index fb7057b08b99e9fd06bc48b6587bd7d76adc7d86..4ee00dce9985d236233cb0f781244d0e761a5c3f 100644 --- a/services/bundlemgr/test/mock/include/mock_bundle_status.h +++ b/services/bundlemgr/test/mock/include/mock_bundle_status.h @@ -24,7 +24,6 @@ namespace OHOS { namespace AppExecFwk { - class MockBundleStatus : public IBundleStatusCallback { public: MockBundleStatus() = default; @@ -32,9 +31,9 @@ public: virtual void OnBundleStateChanged(const uint8_t installType, const int32_t resultCode, const std::string &resultMsg, const std::string &bundleName) override; - virtual void OnBundleAdded(const std::string &bundleName, const int userId) override {}; - virtual void OnBundleUpdated(const std::string &bundleName, const int userId) override {}; - virtual void OnBundleRemoved(const std::string &bundleName, const int userId) override {}; + virtual void OnBundleAdded(const std::string &bundleName, const int userId) override{}; + virtual void OnBundleUpdated(const std::string &bundleName, const int userId) override{}; + virtual void OnBundleRemoved(const std::string &bundleName, const int userId) override{}; virtual sptr AsObject() override; int32_t GetResultCode(); @@ -43,7 +42,6 @@ private: DISALLOW_COPY_AND_MOVE(MockBundleStatus); }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_TEST_MOCK_INCLUDE_MOCK_BUNDLE_STATUS_H \ No newline at end of file diff --git a/services/bundlemgr/test/mock/include/mock_clean_cache.h b/services/bundlemgr/test/mock/include/mock_clean_cache.h index 9dfa562afa0f86dbc0b5793518be6ebb4dfb4887..337513455db62d023951b5fb782fbc660dce0a5e 100644 --- a/services/bundlemgr/test/mock/include/mock_clean_cache.h +++ b/services/bundlemgr/test/mock/include/mock_clean_cache.h @@ -24,7 +24,6 @@ namespace OHOS { namespace AppExecFwk { - class MockCleanCache : public ICleanCacheCallback { public: MockCleanCache() = default; @@ -39,7 +38,6 @@ private: DISALLOW_COPY_AND_MOVE(MockCleanCache); }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_TEST_MOCK_INCLUDE_MOCK_CLEAN_CACHE_H \ No newline at end of file diff --git a/services/bundlemgr/test/mock/include/mock_status_receiver.h b/services/bundlemgr/test/mock/include/mock_status_receiver.h index 1085c272fc78175113298703d2dc084f5d958179..2eaceceed38ab6fc83e5d404c723cb959224103a 100644 --- a/services/bundlemgr/test/mock/include/mock_status_receiver.h +++ b/services/bundlemgr/test/mock/include/mock_status_receiver.h @@ -24,7 +24,6 @@ namespace OHOS { namespace AppExecFwk { - class MockStatusReceiver : public IStatusReceiver { public: MockStatusReceiver() = default; @@ -40,7 +39,6 @@ private: DISALLOW_COPY_AND_MOVE(MockStatusReceiver); }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_TEST_MOCK_INCLUDE_MOCK_STATUS_RECEIVER_H \ No newline at end of file diff --git a/services/bundlemgr/test/mock/src/mock_bundle_status.cpp b/services/bundlemgr/test/mock/src/mock_bundle_status.cpp index 6797ae08162a9b590a27ef7b70588a399e9ece1e..f9c356db8a633307e9d453dbc27c986c3790cc5a 100644 --- a/services/bundlemgr/test/mock/src/mock_bundle_status.cpp +++ b/services/bundlemgr/test/mock/src/mock_bundle_status.cpp @@ -17,7 +17,6 @@ namespace OHOS { namespace AppExecFwk { - void MockBundleStatus::OnBundleStateChanged( const uint8_t installType, const int32_t resultCode, const std::string &resultMsg, const std::string &bundleName) { @@ -39,6 +38,5 @@ int32_t MockBundleStatus::GetResultCode() return future.get(); } } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/bundlemgr/test/mock/src/mock_clean_cache.cpp b/services/bundlemgr/test/mock/src/mock_clean_cache.cpp index 4440d44bea95179a6ba355d45dd4797f2448872f..374009c4d0d7632e7a1e31885d373970f2ecd181 100644 --- a/services/bundlemgr/test/mock/src/mock_clean_cache.cpp +++ b/services/bundlemgr/test/mock/src/mock_clean_cache.cpp @@ -17,7 +17,6 @@ namespace OHOS { namespace AppExecFwk { - void MockCleanCache::OnCleanCacheFinished(bool succeeded) { signal_.set_value(succeeded); @@ -34,6 +33,5 @@ bool MockCleanCache::GetResultCode() future.wait(); return future.get(); } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/bundlemgr/test/mock/src/mock_status_receiver.cpp b/services/bundlemgr/test/mock/src/mock_status_receiver.cpp index cd8b57538f6d9e8c6ed6f7b61ceffd5616c5f161..3e843a6d68b2d55760ce6f2f1c75df6b64cecf97 100644 --- a/services/bundlemgr/test/mock/src/mock_status_receiver.cpp +++ b/services/bundlemgr/test/mock/src/mock_status_receiver.cpp @@ -17,7 +17,6 @@ namespace OHOS { namespace AppExecFwk { - void MockStatusReceiver::OnFinished(const int32_t resultCode, [[maybe_unused]] const std::string &resultMsg) { signal_.set_value(resultCode); @@ -39,6 +38,5 @@ int32_t MockStatusReceiver::GetResultCode() future.wait(); return future.get(); } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/bundlemgr/test/mock/src/system_ability_helper.cpp b/services/bundlemgr/test/mock/src/system_ability_helper.cpp index 92c65c289034cb8f3a72484530e1c67dc7241b79..87df614aeaf2c37c07da4c365e8898b49962beea 100644 --- a/services/bundlemgr/test/mock/src/system_ability_helper.cpp +++ b/services/bundlemgr/test/mock/src/system_ability_helper.cpp @@ -24,9 +24,7 @@ namespace OHOS { namespace AppExecFwk { namespace { - std::map> g_abilities; - } // namespace sptr SystemAbilityHelper::GetSystemAbility(const int32_t systemAbilityId) @@ -62,6 +60,5 @@ bool SystemAbilityHelper::RemoveSystemAbility(const int32_t systemAbilityId) // mock helper always return true. return true; } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/bundlemgr/test/unittest/bms_bundle_installer_test/bms_bundle_installer_test.cpp b/services/bundlemgr/test/unittest/bms_bundle_installer_test/bms_bundle_installer_test.cpp index 58cc1e42ef71fd48cabd3cb30dd563c1e83620aa..34eaf96110272c5598ef500ab0375d54800d278a 100755 --- a/services/bundlemgr/test/unittest/bms_bundle_installer_test/bms_bundle_installer_test.cpp +++ b/services/bundlemgr/test/unittest/bms_bundle_installer_test/bms_bundle_installer_test.cpp @@ -42,7 +42,6 @@ using namespace OHOS; using OHOS::DelayedSingleton; namespace { - const std::string BUNDLE_NAME = "com.example.l3jsdemo"; const std::string RESOURCE_ROOT_PATH = "/data/test/resource/bms/install_bundle/"; const std::string INVALID_PATH = "/install_bundle/"; @@ -57,7 +56,6 @@ const std::string ROOT_DIR = "/data/accounts"; const int32_t ROOT_UID = 0; const int32_t USERID = 0; const std::string INSTALL_THREAD = "TestInstall"; - } // namespace class BmsBundleInstallerTest : public testing::Test { diff --git a/services/bundlemgr/test/unittest/bms_bundle_parser_test/bms_bundle_parser_test.cpp b/services/bundlemgr/test/unittest/bms_bundle_parser_test/bms_bundle_parser_test.cpp index 8f1aa7514c2417f95768b403b00701f92cf7daca..b2bab7ae5b1e8b713459a87b52a5c6a360bc6288 100755 --- a/services/bundlemgr/test/unittest/bms_bundle_parser_test/bms_bundle_parser_test.cpp +++ b/services/bundlemgr/test/unittest/bms_bundle_parser_test/bms_bundle_parser_test.cpp @@ -32,7 +32,6 @@ using namespace OHOS::AppExecFwk::Constants; using namespace OHOS::AppExecFwk::ProfileReader; namespace { - const std::string RESOURCE_ROOT_PATH = "/data/test/resource/bms/parse_bundle/"; const std::string NEW_APP = "new"; const std::string BREAK_ZIP = "break_zip"; @@ -191,7 +190,6 @@ const nlohmann::json CONFIG_JSON = R"( } } )"_json; - } // namespace class BmsBundleParserTest : public testing::Test { @@ -209,6 +207,7 @@ protected: void CheckProfilePermission(const nlohmann::json &checkedProfileJson) const; void CheckProfileForms(const nlohmann::json &checkedProfileJson) const; void CheckProfileShortcut(const nlohmann::json &checkedProfileJson) const; + protected: std::ostringstream pathStream_; }; @@ -894,7 +893,7 @@ HWTEST_F(BmsBundleParserTest, TestParse_2300, Function | SmallTest | Level1) HWTEST_F(BmsBundleParserTest, TestParse_2400, Function | SmallTest | Level1) { nlohmann::json errorFormsJson = CONFIG_JSON; - errorFormsJson[BUNDLE_PROFILE_KEY_MODULE][BUNDLE_MODULE_PROFILE_KEY_ABILITIES]= R"( + errorFormsJson[BUNDLE_PROFILE_KEY_MODULE][BUNDLE_MODULE_PROFILE_KEY_ABILITIES] = R"( [{ "skills": [ { diff --git a/services/bundlemgr/test/unittest/bms_bundle_permission_test/bms_bundle_permission_test.cpp b/services/bundlemgr/test/unittest/bms_bundle_permission_test/bms_bundle_permission_test.cpp index a0046249e04518656f44d2538c757eae24b102ba..fa94fae3617236c8a4bc4fa4d55bbc2c7e8fc995 100644 --- a/services/bundlemgr/test/unittest/bms_bundle_permission_test/bms_bundle_permission_test.cpp +++ b/services/bundlemgr/test/unittest/bms_bundle_permission_test/bms_bundle_permission_test.cpp @@ -93,78 +93,62 @@ const std::string DEFPERMISSION_NAME18 = "com.myability.permission.MYPERMISSION1 const std::string DEF_LABEL1 = "MockDefPermissionBundleSystemGrant"; const std::string DEF_LABEL2 = "MockDefPermissionBundleUserGrant"; const std::string DEF_LABEL3 = "MockSameDefPermissionNameBundleSystemGrant"; -const DefPermission DEFPERMISSION_SYSTEM1 = { - .name = DEFPERMISSION_NAME1, +const DefPermission DEFPERMISSION_SYSTEM1 = {.name = DEFPERMISSION_NAME1, .grantMode = "system_grant", .availableScope = {"signature"}, .label = DEF_LABEL1, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1 -}; -const DefPermission DEFPERMISSION_SYSTEM2 = { - .name = DEFPERMISSION_NAME2, + .descriptionId = 1}; +const DefPermission DEFPERMISSION_SYSTEM2 = {.name = DEFPERMISSION_NAME2, .grantMode = "system_grant", .availableScope = {"signature"}, .label = DEF_LABEL1, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1 -}; -const DefPermission DEFPERMISSION_SYSTEM3 = { - .name = DEFPERMISSION_NAME3, + .descriptionId = 1}; +const DefPermission DEFPERMISSION_SYSTEM3 = {.name = DEFPERMISSION_NAME3, .grantMode = "system_grant", .availableScope = {"signature"}, .label = DEF_LABEL1, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1 -}; -const DefPermission DEFPERMISSION_UPDATE1 = { - .name = DEFPERMISSION_NAME1, + .descriptionId = 1}; +const DefPermission DEFPERMISSION_UPDATE1 = {.name = DEFPERMISSION_NAME1, .grantMode = "user_grant", .availableScope = {"signature"}, .label = DEF_LABEL2, .labelId = 10, .description = DEF_LABEL2, - .descriptionId = 10 -}; -const DefPermission DEFPERMISSION_UPDATE2 = { - .name = DEFPERMISSION_NAME2, + .descriptionId = 10}; +const DefPermission DEFPERMISSION_UPDATE2 = {.name = DEFPERMISSION_NAME2, .grantMode = "user_grant", .availableScope = {"signature"}, .label = DEF_LABEL2, .labelId = 10, .description = DEF_LABEL2, - .descriptionId = 10 -}; -const DefPermission DEFPERMISSION_UPDATE3 = { - .name = DEFPERMISSION_NAME3, + .descriptionId = 10}; +const DefPermission DEFPERMISSION_UPDATE3 = {.name = DEFPERMISSION_NAME3, .grantMode = "user_grant", .availableScope = {"signature"}, .label = DEF_LABEL2, .labelId = 10, .description = DEF_LABEL2, - .descriptionId = 10 -}; -const DefPermission DEFPERMISSION_EMAIL = { - .name = DEFPERMISSION_NAME_EMAIL, + .descriptionId = 10}; +const DefPermission DEFPERMISSION_EMAIL = {.name = DEFPERMISSION_NAME_EMAIL, .grantMode = "system_grant", .availableScope = {""}, .label = DEF_LABEL1, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1 -}; -const DefPermission DEFPERMISSION_MUSIC = { - .name = DEFPERMISSION_NAME_MUSIC, + .descriptionId = 1}; +const DefPermission DEFPERMISSION_MUSIC = {.name = DEFPERMISSION_NAME_MUSIC, .grantMode = "system_grant", .availableScope = {""}, .label = DEF_LABEL1, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1 -}; + .descriptionId = 1}; const DefPermission DEFPERMISSION_APP = {.name = DEFPERMISSION_NAME_APP, .grantMode = "system_grant", .availableScope = {""}, @@ -172,173 +156,119 @@ const DefPermission DEFPERMISSION_APP = {.name = DEFPERMISSION_NAME_APP, .labelId = 1, .description = DEF_LABEL1, .descriptionId = 1}; -const DefPermission DEFPERMISSION_WECHAT = { - .name = DEFPERMISSION_NAME_WECHAT, +const DefPermission DEFPERMISSION_WECHAT = {.name = DEFPERMISSION_NAME_WECHAT, .grantMode = "system_grant", .availableScope = {""}, .label = DEF_LABEL1, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1 -}; -const DefPermission DEFPERMISSION_NOAVAILIAVLE1 = { - .name = DEFPERMISSION_NAME4, + .descriptionId = 1}; +const DefPermission DEFPERMISSION_NOAVAILIAVLE1 = {.name = DEFPERMISSION_NAME4, .grantMode = "system_grant", .availableScope = {""}, .label = DEF_LABEL1, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1 -}; -const DefPermission DEFPERMISSION_NOAVAILIAVLE2 = { - .name = DEFPERMISSION_NAME5, + .descriptionId = 1}; +const DefPermission DEFPERMISSION_NOAVAILIAVLE2 = {.name = DEFPERMISSION_NAME5, .grantMode = "system_grant", .availableScope = {""}, .label = DEF_LABEL1, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1 -}; -const DefPermission DEFPERMISSION_NOAVAILIAVLE3 = { - .name = DEFPERMISSION_NAME6, + .descriptionId = 1}; +const DefPermission DEFPERMISSION_NOAVAILIAVLE3 = {.name = DEFPERMISSION_NAME6, .grantMode = "system_grant", .availableScope = {""}, .label = DEF_LABEL1, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1 -}; -const DefPermission DEFPERMISSION_USERGRANT1 = { - .name = DEFPERMISSION_NAME10, + .descriptionId = 1}; +const DefPermission DEFPERMISSION_USERGRANT1 = {.name = DEFPERMISSION_NAME10, .grantMode = "user_grant", .availableScope = {"signature"}, .label = DEF_LABEL2, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1 -}; -const DefPermission DEFPERMISSION_USERGRANT2 = { - .name = DEFPERMISSION_NAME11, + .descriptionId = 1}; +const DefPermission DEFPERMISSION_USERGRANT2 = {.name = DEFPERMISSION_NAME11, .grantMode = "user_grant", .availableScope = {"signature"}, .label = DEF_LABEL2, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1 -}; -const DefPermission DEFPERMISSION_USERGRANT3 = { - .name = DEFPERMISSION_NAME12, + .descriptionId = 1}; +const DefPermission DEFPERMISSION_USERGRANT3 = {.name = DEFPERMISSION_NAME12, .grantMode = "user_grant", .availableScope = {"signature"}, .label = DEF_LABEL2, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1 -}; -const DefPermission DEFPERMISSION_USERGRANT4 = { - .name = DEFPERMISSION_NAME13, + .descriptionId = 1}; +const DefPermission DEFPERMISSION_USERGRANT4 = {.name = DEFPERMISSION_NAME13, .grantMode = "user_grant", .availableScope = {"signature"}, .label = DEF_LABEL2, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1 -}; -const DefPermission DEFPERMISSION_USERGRANT5 = { - .name = DEFPERMISSION_NAME14, + .descriptionId = 1}; +const DefPermission DEFPERMISSION_USERGRANT5 = {.name = DEFPERMISSION_NAME14, .grantMode = "user_grant", .availableScope = {"signature"}, .label = DEF_LABEL2, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1 -}; -const DefPermission DEFPERMISSION_USERGRANT6 = { - .name = DEFPERMISSION_NAME15, + .descriptionId = 1}; +const DefPermission DEFPERMISSION_USERGRANT6 = {.name = DEFPERMISSION_NAME15, .grantMode = "user_grant", .availableScope = {"signature"}, .label = DEF_LABEL2, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1 -}; -const DefPermission DEFPERMISSION_SAMENAME1 = { - .name = DEFPERMISSION_NAME10, + .descriptionId = 1}; +const DefPermission DEFPERMISSION_SAMENAME1 = {.name = DEFPERMISSION_NAME10, .grantMode = "system_grant", .availableScope = {"signature"}, .label = DEF_LABEL3, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1 -}; -const DefPermission DEFPERMISSION_SAMENAME2 = { - .name = DEFPERMISSION_NAME11, + .descriptionId = 1}; +const DefPermission DEFPERMISSION_SAMENAME2 = {.name = DEFPERMISSION_NAME11, .grantMode = "system_grant", .availableScope = {"signature"}, .label = DEF_LABEL3, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1 -}; -const DefPermission DEFPERMISSION_SAME2 = { - .name = DEFPERMISSION_NAME17, + .descriptionId = 1}; +const DefPermission DEFPERMISSION_SAME2 = {.name = DEFPERMISSION_NAME17, .grantMode = "system_grant", .availableScope = {"signature"}, .label = DEF_LABEL3, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1 -}; -const DefPermission DEFPERMISSION_SAME1 = { - .name = DEFPERMISSION_NAME16, + .descriptionId = 1}; +const DefPermission DEFPERMISSION_SAME1 = {.name = DEFPERMISSION_NAME16, .grantMode = "system_grant", .availableScope = {"signature"}, .label = DEF_LABEL3, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1 -}; -const DefPermission DEFPERMISSION_SAME3 = { - .name = DEFPERMISSION_NAME18, + .descriptionId = 1}; +const DefPermission DEFPERMISSION_SAME3 = {.name = DEFPERMISSION_NAME18, .grantMode = "system_grant", .availableScope = {"signature"}, .label = DEF_LABEL3, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1 -}; + .descriptionId = 1}; const ReqPermission REQPERMISSION1 = { - .name = DEFPERMISSION_NAME_EMAIL, - .reason = "reason", - .usedScene = { - .ability = {"ability"}, - .when = "when" - } -}; + .name = DEFPERMISSION_NAME_EMAIL, .reason = "reason", .usedScene = {.ability = {"ability"}, .when = "when"}}; const ReqPermission REQPERMISSION2 = { - .name = DEFPERMISSION_NAME_WECHAT, - .reason = "reason", - .usedScene = { - .ability = {"ability"}, - .when = "when" - } -}; + .name = DEFPERMISSION_NAME_WECHAT, .reason = "reason", .usedScene = {.ability = {"ability"}, .when = "when"}}; const ReqPermission REQPERMISSION3 = { - .name = DEFPERMISSION_NAME_APP, - .reason = "reason", - .usedScene = { - .ability = {"ability"}, - .when = "when" - } -}; + .name = DEFPERMISSION_NAME_APP, .reason = "reason", .usedScene = {.ability = {"ability"}, .when = "when"}}; const ReqPermission REQPERMISSION4 = { - .name = DEFPERMISSION_NAME_MUSIC, - .reason = "reason", - .usedScene = { - .ability = {"ability"}, - .when = "when" - } -}; + .name = DEFPERMISSION_NAME_MUSIC, .reason = "reason", .usedScene = {.ability = {"ability"}, .when = "when"}}; } // namespace class BmsBundlePermissionTest : public testing::Test { diff --git a/services/bundlemgr/test/unittest/bms_bundle_uninstaller_test/bms_bundle_uninstaller_test.cpp b/services/bundlemgr/test/unittest/bms_bundle_uninstaller_test/bms_bundle_uninstaller_test.cpp index 4de4e6cd5921e536244eccdee2d361815f515894..46e5dad9c0007fb8a9a88530f1881f4c42b0e485 100755 --- a/services/bundlemgr/test/unittest/bms_bundle_uninstaller_test/bms_bundle_uninstaller_test.cpp +++ b/services/bundlemgr/test/unittest/bms_bundle_uninstaller_test/bms_bundle_uninstaller_test.cpp @@ -38,7 +38,6 @@ using namespace OHOS; using namespace OHOS::AppExecFwk; namespace { - const std::string BUNDLE_NAME = "com.example.l3jsdemo"; const std::string MODULE_PACKAGE = "com.example.l3jsdemo"; const std::string MODULE_PACKAGE1 = "com.example.l3jsdemo1"; @@ -55,7 +54,6 @@ const std::string MODULE_CODE_DIR1 = "/data/accounts/account_0/applications/com. const std::string ROOT_DIR = "/data/accounts"; const std::string DB_FILE_PATH = "/data/bundlemgr"; const int32_t ROOT_UID = 0; - } // namespace class BmsBundleUninstallerTest : public testing::Test { @@ -85,6 +83,7 @@ public: const std::shared_ptr GetBundleMgrService() const; void ClearBundleInfoInDb(); void DeleteInstallFiles(); + private: std::shared_ptr installdService_ = std::make_unique(); std::shared_ptr bundleMgrService_ = DelayedSingleton::GetInstance(); @@ -296,11 +295,11 @@ void BmsBundleUninstallerTest::ClearBundleInfoInDb() return; } auto dataMgt = bundleMgrService_->GetDataMgr(); - if(dataMgt == nullptr) { + if (dataMgt == nullptr) { return; } auto dataStorage = dataMgt->GetDataStorage(); - if(dataStorage == nullptr) { + if (dataStorage == nullptr) { return; } InnerBundleInfo innerBundleInfo; diff --git a/services/bundlemgr/test/unittest/bms_bundle_updater_test/bms_bundle_updater_test.cpp b/services/bundlemgr/test/unittest/bms_bundle_updater_test/bms_bundle_updater_test.cpp index c305f3712c39bd35016e14abe7f70d4f75b3f619..9a17ea4f6fa5ec8449381f3afb3759f6e3b4e163 100755 --- a/services/bundlemgr/test/unittest/bms_bundle_updater_test/bms_bundle_updater_test.cpp +++ b/services/bundlemgr/test/unittest/bms_bundle_updater_test/bms_bundle_updater_test.cpp @@ -49,7 +49,7 @@ const std::string BUNDLE_CODE_DIR = "/data/accounts/account_0/applications/com.e const std::string ROOT_DIR = "/data/accounts"; const std::string PROFILE_FILE = "config.json"; const std::string SEPARATOR = "/"; -const std::chrono::seconds SLEEP_TIME {2}; +const std::chrono::seconds SLEEP_TIME{2}; const int32_t ROOT_UID = 0; const int32_t USERID = 0; const uint32_t VERSION_1 = 1; diff --git a/services/bundlemgr/test/unittest/bms_data_mgr_test/bms_data_mgr_test.cpp b/services/bundlemgr/test/unittest/bms_data_mgr_test/bms_data_mgr_test.cpp index f276ed52dc02fa2306074dac2da6d27263a9a043..7248511b66d4f0baef57a67dc015de997e8ccb66 100755 --- a/services/bundlemgr/test/unittest/bms_data_mgr_test/bms_data_mgr_test.cpp +++ b/services/bundlemgr/test/unittest/bms_data_mgr_test/bms_data_mgr_test.cpp @@ -30,7 +30,6 @@ using OHOS::Parcel; using OHOS::AAFwk::Want; namespace { - const std::string BUNDLE_NAME = "com.example.l3jsdemo"; const std::string APP_NAME = "com.example.l3jsdemo"; const std::string ABILITY_NAME = "com.example.l3jsdemo.MainAbility"; @@ -48,7 +47,6 @@ const std::string RESOURCE_PATH = "/data/accounts/account_/com.example.l3jsdemo" const std::string LIB_PATH = "/data/accounts/account_/com.example.l3jsdemo"; const bool VISIBLE = true; const int32_t USERID = 0; - } // namespace class BmsDataMgrTest : public testing::Test { diff --git a/services/bundlemgr/test/unittest/bms_install_daemon_test/bms_install_daemon_test.cpp b/services/bundlemgr/test/unittest/bms_install_daemon_test/bms_install_daemon_test.cpp index b8c87eb818c94cad76075914e36c464a78b5dd80..e13df47c01673eb239660ca17fabb9609cdc9ffc 100755 --- a/services/bundlemgr/test/unittest/bms_install_daemon_test/bms_install_daemon_test.cpp +++ b/services/bundlemgr/test/unittest/bms_install_daemon_test/bms_install_daemon_test.cpp @@ -27,7 +27,6 @@ using namespace OHOS::AppExecFwk; using namespace OHOS; namespace { - const std::string BUNDLE_FILE = "/data/test/resource/bms/install_daemon/right.hap"; const std::string SYSTEM_DIR = "/sys/com.example.l3jsdemo"; const std::string TEMP_DIR = "/data/accounts/account_0/applications/com.example.l3jsdemo/temp"; @@ -38,7 +37,6 @@ const std::string ROOT_DIR = "/data/accounts"; const int32_t ROOT_UID = 0; const int32_t UID = 1000; const int32_t GID = 1000; - } // namespace class BmsInstallDaemonTest : public testing::Test { diff --git a/services/bundlemgr/test/unittest/bms_service_bundle_scan_test/bms_service_bundle_scan_test.cpp b/services/bundlemgr/test/unittest/bms_service_bundle_scan_test/bms_service_bundle_scan_test.cpp index b7fbba7d28ce534b5282194dfd1949a21a122ed8..822bd0f0bd9a2e20a26399a5c18ddf00aac9e6f9 100755 --- a/services/bundlemgr/test/unittest/bms_service_bundle_scan_test/bms_service_bundle_scan_test.cpp +++ b/services/bundlemgr/test/unittest/bms_service_bundle_scan_test/bms_service_bundle_scan_test.cpp @@ -30,7 +30,6 @@ using namespace OHOS::AppExecFwk; using OHOS::DelayedSingleton; namespace { - const std::string TEST_DIR = "/data/test/resource"; const std::string BUNDLE_FILENAME_1 = "app1.hap"; const std::string BUNDLE_FILENAME_2 = "app2.hap"; @@ -38,7 +37,6 @@ const std::string BUNDLE_FILENAME_3 = "app3.hap"; const std::string BUNDLE_FILENAME_4 = "app1.ha"; const std::string BUNDLE_FILENAME_5 = "app2..ap"; const std::string BUNDLE_FILENAME_6 = "app3"; - } // namespace class BmsServiceBundleScanTest : public testing::Test { @@ -149,11 +147,11 @@ bool BmsServiceBundleScanTest::IsScanResultContain(const std::string name) const return true; } /** -* @tc.number: BundleScan_0100 -* @tc.name: Scan -* @tc.desc: 1. scan dir not exist -* 2. verify scan result file number is 0 -*/ + * @tc.number: BundleScan_0100 + * @tc.name: Scan + * @tc.desc: 1. scan dir not exist + * 2. verify scan result file number is 0 + */ HWTEST_F(BmsServiceBundleScanTest, BundleScan_0100, Function | SmallTest | Level0) { DeleteDir(TEST_DIR); @@ -161,22 +159,22 @@ HWTEST_F(BmsServiceBundleScanTest, BundleScan_0100, Function | SmallTest | Level EXPECT_EQ(0, number); } /** -* @tc.number: BundleScan_0200 -* @tc.name: Scan -* @tc.desc: 1. scan dir exist, no bundle file -* 2. verify scan result file number is 0 -*/ + * @tc.number: BundleScan_0200 + * @tc.name: Scan + * @tc.desc: 1. scan dir exist, no bundle file + * 2. verify scan result file number is 0 + */ HWTEST_F(BmsServiceBundleScanTest, BundleScan_0200, Function | SmallTest | Level0) { int number = static_cast(TriggerScan()); EXPECT_EQ(0, number); } /** -* @tc.number: BundleScan_0300 -* @tc.name: Scan -* @tc.desc: 1. scan dir exist, 3 legal file exist -* 2. verify scan result file number is 3 and file name correct -*/ + * @tc.number: BundleScan_0300 + * @tc.name: Scan + * @tc.desc: 1. scan dir exist, 3 legal file exist + * 2. verify scan result file number is 3 and file name correct + */ HWTEST_F(BmsServiceBundleScanTest, BundleScan_0300, Function | SmallTest | Level0) { CreateDir(TEST_DIR); @@ -199,11 +197,11 @@ HWTEST_F(BmsServiceBundleScanTest, BundleScan_0300, Function | SmallTest | Level DeleteFile(TEST_FILE_NAME_3); } /** -* @tc.number: BundleScan_0400 -* @tc.name: Scan -* @tc.desc: 1. scan dir exist, 3 illegal file exist -* 2. verify scan result file number is 0 -*/ + * @tc.number: BundleScan_0400 + * @tc.name: Scan + * @tc.desc: 1. scan dir exist, 3 illegal file exist + * 2. verify scan result file number is 0 + */ HWTEST_F(BmsServiceBundleScanTest, BundleScan_0400, Function | SmallTest | Level0) { const std::string TEST_FILE_NAME_4 = TEST_DIR + "/" + BUNDLE_FILENAME_4; @@ -222,11 +220,11 @@ HWTEST_F(BmsServiceBundleScanTest, BundleScan_0400, Function | SmallTest | Level DeleteFile(TEST_FILE_NAME_6); } /** -* @tc.number: BundleScan_0500 -* @tc.name: Scan -* @tc.desc: 1. scan dir exist, 3 illegal and 3 legal file exist -* 2. verify scan result file number is 3 and file name correct -*/ + * @tc.number: BundleScan_0500 + * @tc.name: Scan + * @tc.desc: 1. scan dir exist, 3 illegal and 3 legal file exist + * 2. verify scan result file number is 3 and file name correct + */ HWTEST_F(BmsServiceBundleScanTest, BundleScan_0500, Function | SmallTest | Level0) { const std::string TEST_FILE_NAME_1 = TEST_DIR + "/" + BUNDLE_FILENAME_1; diff --git a/services/bundlemgr/test/unittest/bms_service_startup_test/bms_service_startup_test.cpp b/services/bundlemgr/test/unittest/bms_service_startup_test/bms_service_startup_test.cpp index 5605132d410dc0c6433568a766684140db264aa3..9acf9200ec5c35dcee293bd54978095c6102a5a4 100755 --- a/services/bundlemgr/test/unittest/bms_service_startup_test/bms_service_startup_test.cpp +++ b/services/bundlemgr/test/unittest/bms_service_startup_test/bms_service_startup_test.cpp @@ -46,11 +46,11 @@ void BmsServiceStartupTest::TearDown() } /** -* @tc.number: Startup_0100 -* @tc.name: test the start function of the BMS service when service is not ready -* @tc.desc: 1. the service is not initialized -* 2. the non initialized BMS service can be started -*/ + * @tc.number: Startup_0100 + * @tc.name: test the start function of the BMS service when service is not ready + * @tc.desc: 1. the service is not initialized + * 2. the non initialized BMS service can be started + */ HWTEST_F(BmsServiceStartupTest, Startup_0100, Function | SmallTest | Level0) { std::shared_ptr bms = DelayedSingleton::GetInstance(); @@ -62,12 +62,12 @@ HWTEST_F(BmsServiceStartupTest, Startup_0100, Function | SmallTest | Level0) } /** -* @tc.number: Startup_0200 -* @tc.name: test the stop function of the BMS service when service is ready -* @tc.desc: 1. the service is already initialized -* 2. the initialized BMS service can be stopped -*/ -HWTEST_F(BmsServiceStartupTest, Startup_0200,Function | SmallTest | Level0) + * @tc.number: Startup_0200 + * @tc.name: test the stop function of the BMS service when service is ready + * @tc.desc: 1. the service is already initialized + * 2. the initialized BMS service can be stopped + */ +HWTEST_F(BmsServiceStartupTest, Startup_0200, Function | SmallTest | Level0) { std::shared_ptr bms = DelayedSingleton::GetInstance(); bms->OnStart(); @@ -79,12 +79,12 @@ HWTEST_F(BmsServiceStartupTest, Startup_0200,Function | SmallTest | Level0) } /** -* @tc.number: Startup_0300 -* @tc.name: test the restart function of the BMS service -* @tc.desc: 1. the service is already initialized -* 2. the stopped BMS service can be restarted -*/ -HWTEST_F(BmsServiceStartupTest, Startup_0300,Function | SmallTest | Level0) + * @tc.number: Startup_0300 + * @tc.name: test the restart function of the BMS service + * @tc.desc: 1. the service is already initialized + * 2. the stopped BMS service can be restarted + */ +HWTEST_F(BmsServiceStartupTest, Startup_0300, Function | SmallTest | Level0) { std::shared_ptr bms = DelayedSingleton::GetInstance(); bms->OnStart(); @@ -99,12 +99,12 @@ HWTEST_F(BmsServiceStartupTest, Startup_0300,Function | SmallTest | Level0) } /** -* @tc.number: Startup_0400 -* @tc.name: test the restart function of the BMS service which is already initialized -* @tc.desc: 1. the service is already initialized -* 2. the recall start function will not affect the initialized BMS service -*/ -HWTEST_F(BmsServiceStartupTest, Startup_0400,Function | SmallTest | Level0) + * @tc.number: Startup_0400 + * @tc.name: test the restart function of the BMS service which is already initialized + * @tc.desc: 1. the service is already initialized + * 2. the recall start function will not affect the initialized BMS service + */ +HWTEST_F(BmsServiceStartupTest, Startup_0400, Function | SmallTest | Level0) { std::shared_ptr bms = DelayedSingleton::GetInstance(); bms->OnStart(); @@ -116,12 +116,12 @@ HWTEST_F(BmsServiceStartupTest, Startup_0400,Function | SmallTest | Level0) } /** -* @tc.number: GetDataMgr_0100 -* @tc.name: test the dataMgr can be obtained -* @tc.desc: 1. the service is already initialized -* 2. the dataMgr can be obtained -*/ -HWTEST_F(BmsServiceStartupTest, GetDataMgr_0100,Function | SmallTest | Level0) + * @tc.number: GetDataMgr_0100 + * @tc.name: test the dataMgr can be obtained + * @tc.desc: 1. the service is already initialized + * 2. the dataMgr can be obtained + */ +HWTEST_F(BmsServiceStartupTest, GetDataMgr_0100, Function | SmallTest | Level0) { std::shared_ptr bms = DelayedSingleton::GetInstance(); bms->OnStart(); @@ -131,12 +131,12 @@ HWTEST_F(BmsServiceStartupTest, GetDataMgr_0100,Function | SmallTest | Level0) } /** -* @tc.number: GetBundleInstaller_0100 -* @tc.name: test the installer can be obtained -* @tc.desc: 1. the service is already initialized -* 2. the installer can be obtained -*/ -HWTEST_F(BmsServiceStartupTest, GetBundleInstaller_0100,Function | SmallTest | Level0) + * @tc.number: GetBundleInstaller_0100 + * @tc.name: test the installer can be obtained + * @tc.desc: 1. the service is already initialized + * 2. the installer can be obtained + */ +HWTEST_F(BmsServiceStartupTest, GetBundleInstaller_0100, Function | SmallTest | Level0) { std::shared_ptr bms = DelayedSingleton::GetInstance(); bms->OnStart(); 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/services/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp b/services/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp index 20e10a2cb4575781565d8d08b6368436d0ff6b70..cbfb126eddc819145cb5965dc30f4bbfdb3cc774 100755 --- a/services/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp +++ b/services/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp @@ -216,7 +216,7 @@ void AmsAppLifeCycleModuleTest::ChangeAbilityStateToForegroud(const sptrUpdateAbilityState(token, AbilityState::ABILITY_STATE_FOREGROUND); if (!isChange) { - ASSERT_NE(appRunningRecord, nullptr); + EXPECT_NE(appRunningRecord, nullptr); int32_t recordId = appRunningRecord->GetRecordId(); serviceInner_->ApplicationForegrounded(recordId); } @@ -235,7 +235,7 @@ void AmsAppLifeCycleModuleTest::ChangeAbilityStateToBackGroud(const sptrUpdateAbilityState(token, AbilityState::ABILITY_STATE_BACKGROUND); if (!isChange) { - ASSERT_NE(appRunningRecord, nullptr); + EXPECT_NE(appRunningRecord, nullptr); int32_t recordId = appRunningRecord->GetRecordId(); serviceInner_->ApplicationBackgrounded(recordId); } @@ -251,7 +251,7 @@ void AmsAppLifeCycleModuleTest::ChangeAppToTerminate(const sptrAbilityTerminated(token); - ASSERT_NE(appRunningRecord, nullptr); + EXPECT_NE(appRunningRecord, nullptr); int32_t recordId = appRunningRecord->GetRecordId(); serviceInner_->ApplicationTerminated(recordId); } else { @@ -269,11 +269,11 @@ void AmsAppLifeCycleModuleTest::ChangeAbilityStateToTerminate( void AmsAppLifeCycleModuleTest::CheckState(const std::shared_ptr &appRunningRecord, const sptr &token, const AbilityState abilityState, const ApplicationState appState) const { - ASSERT_NE(appRunningRecord, nullptr); + EXPECT_NE(appRunningRecord, nullptr); auto abilityRunningRecord = appRunningRecord->GetAbilityRunningRecordByToken(token); ApplicationState getAppState = appRunningRecord->GetState(); EXPECT_EQ(appState, getAppState); - ASSERT_NE(abilityRunningRecord, nullptr); + EXPECT_NE(abilityRunningRecord, nullptr); AbilityState getAbilityState = abilityRunningRecord->GetState(); EXPECT_EQ(abilityState, getAbilityState); } @@ -371,7 +371,7 @@ sptr AmsAppLifeCycleModuleTest::GetAbilityToken() */ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_001, TestSize.Level2) { - ASSERT_NE(serviceInner_, nullptr); + EXPECT_NE(serviceInner_, nullptr); pid_t pid = 1024; sptr token = GetAbilityToken(); auto abilityInfo = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.helloworld"); @@ -416,7 +416,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_001, TestSize.Level2) HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_002, TestSize.Level3) { pid_t pid = 1023; - ASSERT_NE(serviceInner_, nullptr); + EXPECT_NE(serviceInner_, nullptr); std::shared_ptr appRunningRecord = nullptr; std::vector> tokens; auto abilityInfo = std::make_shared(); @@ -525,7 +525,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_003, TestSize.Level3) */ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_004, TestSize.Level3) { - ASSERT_NE(serviceInner_, nullptr); + EXPECT_NE(serviceInner_, nullptr); pid_t pid = 1024; sptr token = GetAbilityToken(); auto abilityInfo = GetAbilityInfo("0", "MainAbility", "p3", "com.ohos.test.helloworld"); @@ -572,7 +572,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_004, TestSize.Level3) */ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_005, TestSize.Level2) { - ASSERT_NE(serviceInner_, nullptr); + EXPECT_NE(serviceInner_, nullptr); pid_t pid = 1024; sptr token0 = new (std::nothrow) MockAbilityToken(); @@ -635,7 +635,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_005, TestSize.Level2) */ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_006, TestSize.Level2) { - ASSERT_NE(serviceInner_, nullptr); + EXPECT_NE(serviceInner_, nullptr); pid_t pid = fork(); if (pid == 0) { @@ -692,7 +692,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_006, TestSize.Level2) */ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_007, TestSize.Level2) { - ASSERT_NE(serviceInner_, nullptr); + EXPECT_NE(serviceInner_, nullptr); pid_t pid = 1024; sptr token = GetAbilityToken(); auto abilityInfo = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.helloworld"); @@ -741,7 +741,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_007, TestSize.Level2) */ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_008, TestSize.Level2) { - ASSERT_NE(serviceInner_, nullptr); + EXPECT_NE(serviceInner_, nullptr); pid_t pid_0 = 1024; pid_t pid_1 = 2048; sptr token_0 = new (std::nothrow) MockAbilityToken(); @@ -811,7 +811,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_008, TestSize.Level2) HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_009, TestSize.Level3) { pid_t pid = 1025; - ASSERT_NE(serviceInner_, nullptr); + EXPECT_NE(serviceInner_, nullptr); std::shared_ptr appRunningRecord = nullptr; auto abilityInfo = std::make_shared(); auto appInfo = std::make_shared(); @@ -857,7 +857,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_009, TestSize.Level3) HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_010, TestSize.Level3) { pid_t pid = 1025; - ASSERT_NE(serviceInner_, nullptr); + EXPECT_NE(serviceInner_, nullptr); std::shared_ptr appRunningRecord = nullptr; int32_t recordId[APPLICATION_NUM]; sptr mockAppScheduler[APPLICATION_NUM]; @@ -979,7 +979,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_013, TestSize.Level3) EXPECT_CALL(*mockAppSpawnSocket, OpenAppSpawnConnection()).Times(1).WillOnce(Return(0)); int ret = serviceInner_->OpenAppSpawnConnection(); - ASSERT_EQ(ret, 0); + EXPECT_EQ(ret, 0); EXPECT_EQ(serviceInner_->QueryAppSpawnConnectionState(), SpawnConnectionState::STATE_CONNECTED); EXPECT_CALL(*mockAppSpawnSocket, CloseAppSpawnConnection()).Times(1); diff --git a/services/test/moduletest/common/ams/app_running_record_test/ams_app_running_record_module_test.cpp b/services/test/moduletest/common/ams/app_running_record_test/ams_app_running_record_module_test.cpp index f565d0ef49b9bb0e33115fc4c098be6f5d7ee4d2..e28e909dc3cbc56333e9cc6e897bbd4c2663593f 100644 --- a/services/test/moduletest/common/ams/app_running_record_test/ams_app_running_record_module_test.cpp +++ b/services/test/moduletest/common/ams/app_running_record_test/ams_app_running_record_module_test.cpp @@ -171,7 +171,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, ApplicationStart_001, TestSize.Level0) RecordQueryResult result; auto record = service_->GetOrCreateAppRunningRecord(GetMockToken(), appInfo, abilityInfo, processName, 0, result); EXPECT_TRUE(record != nullptr) << ",create apprunningrecord fail!"; - ASSERT_FALSE(result.appExists) << ",result is wrong!"; + EXPECT_FALSE(result.appExists) << ",result is wrong!"; // check apprunningrecord int32_t id = record->GetRecordId(); @@ -231,7 +231,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, MultiApplicationStart_002, TestSize.Leve auto record = service_->GetOrCreateAppRunningRecord(GetMockToken(), appInfo, abilityInfo, processName, 0, result); EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; - ASSERT_FALSE(result.appExists) << "result is wrong!"; + EXPECT_FALSE(result.appExists) << "result is wrong!"; // check abilityrunningrecord & apprunningrecord int32_t id = record->GetRecordId(); @@ -274,7 +274,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, ScheduleTrimMemory_003, TestSize.Level1) RecordQueryResult result; auto record = service_->GetOrCreateAppRunningRecord(GetMockToken(), appInfo, abilityInfo, processName, 0, result); EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; - ASSERT_FALSE(result.appExists) << "result is wrong!"; + EXPECT_FALSE(result.appExists) << "result is wrong!"; // LaunchApplication sptr mockApplication(new MockApplication()); @@ -322,7 +322,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, LowMemoryWarning_004, TestSize.Level1) RecordQueryResult result; auto record = service_->GetOrCreateAppRunningRecord(GetMockToken(), appInfo, abilityInfo, processName, 0, result); EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; - ASSERT_FALSE(result.appExists) << "result is wrong!"; + EXPECT_FALSE(result.appExists) << "result is wrong!"; // LaunchApplication sptr mockApplication(new MockApplication()); diff --git a/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp b/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp index 356d2ba86ee67b79c248a662f2c1dcfe69898e2c..7b1f332f9f666ce9f5cc22158fb0579e86b443af 100644 --- a/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp +++ b/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp @@ -265,7 +265,7 @@ HWTEST_F(AmsIpcAppSchedulerModuleTest, ExcuteApplicationIPCInterface_008, TestSi mockApplication->Wait(); bool isEqual = mockApplication->CompareAppLaunchData(launchData); - ASSERT_EQ(true, isEqual) << "excute fail, index is " << i; + EXPECT_EQ(true, isEqual) << "excute fail, index is " << i; } } diff --git a/services/test/moduletest/common/ams/service_app_spawn_client_test/ams_service_app_spawn_client_module_test.cpp b/services/test/moduletest/common/ams/service_app_spawn_client_test/ams_service_app_spawn_client_module_test.cpp index d50d759ce6af828b33b0fb0ccc08996f93330180..2080bbeb1fa54b50406ff1cbfee5201e4755b603 100644 --- a/services/test/moduletest/common/ams/service_app_spawn_client_test/ams_service_app_spawn_client_module_test.cpp +++ b/services/test/moduletest/common/ams/service_app_spawn_client_test/ams_service_app_spawn_client_module_test.cpp @@ -208,8 +208,8 @@ HWTEST_F(AmsServiceAppSpawnClientModuleTest, ConnectAppSpawnDaemon_001, TestSize for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); appMgrService->OnStart(); - ASSERT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); - ASSERT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); appMgrService->OnStop(); EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appMgrService->QueryServiceState().connectionState); EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, amsInner->QueryAppSpawnConnectionState()); @@ -243,8 +243,8 @@ HWTEST_F(AmsServiceAppSpawnClientModuleTest, ConnectAppSpawnDaemon_002, TestSize EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, amsInner->QueryAppSpawnConnectionState()); MockedAppSpawnSocket::gConnectSuccess_ = true; appMgrService->OnStart(); - ASSERT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); - ASSERT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); appMgrService->OnStop(); EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appMgrService->QueryServiceState().connectionState); EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, amsInner->QueryAppSpawnConnectionState()); @@ -270,8 +270,8 @@ HWTEST_F(AmsServiceAppSpawnClientModuleTest, ConnectAppSpawnDaemon_003, TestSize for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); appMgrService->OnStart(); - ASSERT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); - ASSERT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); appMgrService->OnStart(); EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/include/main_ability.h index fcbe2e0786af1dc0e02fe931e9f03b3027d7bc15..ec396c21dea02f6d24e14b6bd96c6200ebbb3545 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/include/main_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/include/main_ability.h @@ -47,35 +47,35 @@ public: { [this](int code) { OnSetCallerCase1(code); }, }}, - {(int)AppendApi::TerminateAndRemoveMisson, + {(int)AppendApi::TerminateAndRemoveMisson, { [this](int code) { TerminateAndRemoveMissonCase1(code); }, }}, - {(int)AppendApi::TerminateAbilityResult, + {(int)AppendApi::TerminateAbilityResult, { [this](int code) { TerminateAbilityResultCase1(code); }, }}, - {(int)AppendApi::GetDispalyOrientation, + {(int)AppendApi::GetDispalyOrientation, { [this](int code) { GetDispalyOrientationCase1(code); }, }}, - {(int)AppendApi::GetPreferencesDir, + {(int)AppendApi::GetPreferencesDir, { [this](int code) { GetPreferencesDirCase1(code); }, }}, - {(int)AppendApi::StartAbilities, + {(int)AppendApi::StartAbilities, { [this](int code) { StartAbilitiesCase1(code); }, }}, - {(int)AppendApi::GetColorMode, + {(int)AppendApi::GetColorMode, { [this](int code) { GetColorModeCase1(code); }, }}, - {(int)AppendApi::SetColorMode, + {(int)AppendApi::SetColorMode, { [this](int code) { SetColorModeCase1(code); }, }}, - {(int)AppendApi::IsFirstInMission, + {(int)AppendApi::IsFirstInMission, { [this](int code) { IsFirstInMissionCase1(code); }, }}, diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/main_ability.cpp index 0ee77556032cf9665bdb9fdb11d577b6b4a88e10..437d310c7b3b3ad0de7c19e9e7a21e310d4e81a0 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/main_ability.cpp @@ -20,6 +20,12 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; +namespace { +constexpr int paramCnt = 3; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +} // namespace void MainAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -110,11 +116,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() < paramCnt) { 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()); } @@ -160,11 +166,11 @@ void MainAbility::GetDispalyOrientationCase1(int code) void MainAbility::GetPreferencesDirCase1(int code) { - bool result = true; + unsigned int result = true; string preferencesDir = GetPreferencesDir(); result = !preferencesDir.empty(); - result = result & (bool)preferencesDir.find(this->GetBundleName()); - result = result & (bool)preferencesDir.find("com.ohos.amsst.AppAppendA/files/MainAbility/preferences"); + result = result & (unsigned int)preferencesDir.find(this->GetBundleName()); + result = result & (unsigned int)preferencesDir.find("com.ohos.amsst.AppAppendA/files/MainAbility/preferences"); TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/second_ability.cpp index 74d9768f8a42a4b3cc9f4e70f2cbcb85330f1a98..e34a7a3a6588cd90cf2ea233d96698b2f0ce8336 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/second_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/second_ability.cpp @@ -20,6 +20,12 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; +namespace { +constexpr int paramCnt = 3; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +} // namespace void SecondAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -127,11 +133,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() < paramCnt) { 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()); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/main_ability.cpp index db038f3117a282e90f5ef9b2e9c5681325531547..8cbcdfb0c3beb5a9bceb6867852a90be753cbcfa 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/main_ability.cpp @@ -20,6 +20,12 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; +namespace { +static const int paramCnt = 3; +static const int index_f = 0; +static const int index_s = 1; +static const int index_t = 2; +} // namespace void MainAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -103,11 +109,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() < paramCnt) { 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()); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/test_utils.cpp index 07ebf00c47128276f0e83d0aa5783fec0a417147..29dca59b94bd6f02146ee5b2944b1709b93f37fc 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/test_utils.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/test_utils.cpp @@ -47,7 +47,7 @@ Want TestUtils::MakeWant( std::vector TestUtils::split(const std::string &in, const std::string &delim) { - std::regex reg{delim}; + std::regex reg { delim}; return std::vector{ std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator()}; } 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..c71b154d3e2e8cf1aa89f62ee4fa6c13e3d69f5e 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 @@ -25,6 +25,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_DATA_A_CODE = 210; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -38,6 +39,8 @@ static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_SERVICE = "1"; static const std::string ABILITY_TYPE_DATA = "2"; +static const int charCnt = 5; +} // namespace bool AmsStDataAbilityDataA::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -187,9 +190,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); } 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..bc87bd356b17186c06017e7b0bb9c6768e4a4480 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 @@ -26,6 +26,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_PAGE_A_CODE = 110; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -33,6 +34,8 @@ static const std::string OPERATOR_UPDATE = "Update"; static const std::string OPERATOR_QUERY = "Query"; static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; static const std::string OPERATOR_OPENFILE = "OpenFile"; +static const int charCnt = 5; +} // namespace bool AmsStDataAbilityPageA::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -176,9 +179,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); } 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..42b50324f63fb2c653794a2ebf52140dbd2fd214 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 @@ -23,6 +23,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_DATA_B_CODE = 220; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -36,6 +37,8 @@ static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_SERVICE = "1"; static const std::string ABILITY_TYPE_DATA = "2"; +static const int charCnt = 5; +} // namespace bool AmsStDataAbilityDataB::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -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); } 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..4b883d863e73413e5d9d2ee110d85fcc21d9559b 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 @@ -26,6 +26,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_PAGE_B_CODE = 120; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -33,6 +34,8 @@ static const std::string OPERATOR_UPDATE = "Update"; static const std::string OPERATOR_QUERY = "Query"; static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; static const std::string OPERATOR_OPENFILE = "OpenFile"; +static const int charCnt = 5; +} // namespace bool AmsStDataAbilityPageB::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -176,9 +179,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); } 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..e661ad629278946bf36dcf721362476fdc95f42b 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 @@ -23,6 +23,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_DATA_C1_CODE = 230; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -37,6 +38,7 @@ static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_SERVICE = "1"; static const std::string ABILITY_TYPE_DATA = "2"; constexpr int charCnt = 5; +} // namespace bool AmsStDataAbilityDataC1::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -175,8 +177,9 @@ static void GetResult(std::shared_ptr child, std::shared_pt } result = std::to_string(fd); char str[charCnt]; - if (!feof(file)) + if (!feof(file)) { fgets(str, charCnt, file); + } result = str; fclose(file); } @@ -225,8 +228,9 @@ void DataTestDataC1EventSubscriber::GetResultBySelf( mainAbility_->PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, "OpenFile"); char str[charCnt]; - if (!feof(file)) + if (!feof(file)) { fgets(str, charCnt, file); + } result = str; fclose(file); } 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..deccd502079ed0e119a2e95463a45dbe39031fcf 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 @@ -23,6 +23,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_DATA_C2_CODE = 240; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -36,6 +37,8 @@ static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_SERVICE = "1"; static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} // namespace bool AmsStDataAbilityDataC2::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -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); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/include/kit_test_ability_manager_second.h b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/include/kit_test_ability_manager_second.h index b3f37084fe0d11d6749853837c52f7274051e9da..f6b888f665709c0fe09fe584605dcf8cd82e9420 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/include/kit_test_ability_manager_second.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/include/kit_test_ability_manager_second.h @@ -139,7 +139,6 @@ public: void KitTerminateAbility(); KitTestAbilityManagerSecond *kitTestAbility_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // _KIT_TEST_ABILITY_MANAGER_SECOND_H_ 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..62025acc4042004bdfc0f4c75a6be4830e98abc6 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) @@ -110,8 +112,7 @@ void KitTestAbilityManagerSecond::ProcessStateNotEqual( void KitTestAbilityManagerSecond::GetAllStackInfo(MissionStackInfo &missionStackInfo, int stackID) { - StackInfo stackInfo; - stackInfo = AbilityManager::GetInstance().GetAllStackInfo(); + StackInfo stackInfo = AbilityManager::GetInstance().GetAllStackInfo(); for (const auto &stackInfo : stackInfo.missionStackInfos) { if (stackInfo.id == stackID) { missionStackInfo = stackInfo; @@ -206,7 +207,7 @@ void KitTestAbilityManagerSecond::AbilityManagerGetAllStackInfoCase4(int code) GetAllStackInfo(missionStackInfo, 1); bool result = false; if (missionStackInfo.missionRecords.size() == 1) { - result = (missionStackInfo.missionRecords[0].abilityRecordInfos.size() == 2); + result = (missionStackInfo.missionRecords[0].abilityRecordInfos.size() == numTwo); } PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); } @@ -228,9 +229,9 @@ void KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCas { APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCase1"); std::vector info; - info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(3, RECENT_WITH_EXCLUDED); + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); bool result = false; - if (1 == info.size() && 2 == info[0].size) { + if (info.size() == 1 && info[0].size == numTwo) { if (info[0].baseAbility.GetBundleName() == bundleName) { result = true; } @@ -242,9 +243,9 @@ void KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCas { APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCase2"); std::vector info; - info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(3, RECENT_WITH_EXCLUDED); + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); bool result = false; - if (1 == info.size() && 2 == info[0].size) { + if (info.size() == 1 && info[0].size == numTwo) { result = true; } PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); @@ -254,9 +255,9 @@ void KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCas { APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCase3"); std::vector info; - info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(3, RECENT_WITH_EXCLUDED); + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); bool result = false; - if (1 == info.size() && 2 == info[0].size) { + if (info.size() == 1 && info[0].size == numTwo) { if (info[0].baseAbility.GetBundleName() == bundleName && info[0].baseAbility.GetAbilityName() == topAbilityName) { result = true; @@ -270,9 +271,9 @@ void KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCa { APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCase1"); std::vector info; - info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(3); + info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(numThree); bool result = false; - if (1 == info.size() && 2 == info[0].size) { + if (info.size() == 1 && info[0].size == numTwo) { if (info[0].baseAbility.GetBundleName() == bundleName) { result = true; } @@ -284,9 +285,9 @@ void KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCa { APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCase2"); std::vector info; - info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(3); + info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(numThree); bool result = false; - if (1 == info.size() && 2 == info[0].size) { + if (info.size() == 1 && info[0].size == numTwo) { result = true; } PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); @@ -296,9 +297,9 @@ void KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCa { APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCase3"); std::vector info; - info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(3); + info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(numThree); bool result = false; - if (1 == info.size() && 2 == info[0].size) { + if (info.size() == 1 && info[0].size == numTwo) { if (info[0].baseAbility.GetBundleName() == bundleName && info[0].baseAbility.GetAbilityName() == topAbilityName) { result = true; @@ -352,7 +353,7 @@ void KitTestAbilityManagerSecond::OnActive() { APP_LOGI("KitTestAbilityManagerSecond::OnActive"); Ability::OnActive(); - if (true == isMoveMissionToTop) { + if (isMoveMissionToTop == true) { PublishEvent(g_respPageManagerAbilityST, moveMissionToTopCode, "1"); isMoveMissionToTop = false; moveMissionToTopCode = -1; @@ -378,10 +379,10 @@ void KitTestAbilityManagerSecond::OnBackground() { APP_LOGI("KitTestAbilityManagerSecond::OnBackground"); Ability::OnBackground(); - if (true == isMoveMissionToTop) { + if (isMoveMissionToTop == true) { std::vector info; - info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(3, RECENT_WITH_EXCLUDED); - if (1 == info.size() && 2 == info[0].size) { + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); + if (info.size() == 1 && info[0].size == numTwo) { GetAbilityManager()->MoveMissionToTop(info[0].id); APP_LOGI("GetAbilityManager()->MoveMissionToTop(info[0].id);%{public}d", static_cast(info[0].id)); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fifth_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fifth_ability.h index 310b4dfb4c6cd2a114836d5bca7876128bd9d1e8..45ee85ed58563188e40a036a6e23baece5649037 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fifth_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fifth_ability.h @@ -239,7 +239,6 @@ public: FifthAbility *fifthAbility; std::unordered_map> mapTestFunc_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // _SECOND_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fourth_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fourth_ability.h index 903d71ac9a7c323868f181f79cf673d33d588536..c9b3d45e1e95ecbf90176b237e90caee0994aeb1 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fourth_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fourth_ability.h @@ -43,7 +43,7 @@ public: bool CompareType(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2); bool CompareWantParams(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2); bool CompareSkills(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2); - template + template void SkillsGetWantParams(M params, int code) { AAFwk::Skills skill; @@ -778,7 +778,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/include/kit_test_ability_manager.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/kit_test_ability_manager.h index 1bc3c529ed1d2eec1a368058024516d4802b4e4b..5bdd1a448951d3f760ee841c9ba504485ede99d8 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/kit_test_ability_manager.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/kit_test_ability_manager.h @@ -189,7 +189,6 @@ private: std::unordered_map> mapTestFunc_; KitTestAbilityManager *kitTestAbility_; }; - } // namespace AppExecFwk } // namespace OHOS -#endif //_KIT_TEST_ABILITY_MANAGER_H_ +#endif // _KIT_TEST_ABILITY_MANAGER_H_ 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/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..621ddef3b4703611779d11fdafeeda052f66b9ce 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; } @@ -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..9153f1ed291cdc3e66583ccaee2ad3cc980b670a 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; } @@ -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..4ba9c1f21c97c90d38ebe8595b1f13e2fa485589 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; } @@ -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..31fa67ba3c2ed5593fda35b756ea10bfb2de7a5f 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); @@ -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..a19b5908fb7a31265d424634204915982bedf2a3 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); @@ -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/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..0d7e1d4c45bcfdc34b4e36a9c2deec3b396f8cfb 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; } @@ -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..1dd6fd902512522d24a86eb2491f7e2a1eb663b5 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); @@ -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..3761d8412f1d8b6f4b1b557e4fa75fc3dce09585 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); @@ -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/serviceAbilityA/include/verify_act_first_ability.h b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/verify_act_first_ability.h index c13a82e29e87f954555119bb80dd24b3f8e70028..4f4926ec6edd4af63bb20633492e08f47b994fee 100644 --- a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/verify_act_first_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/verify_act_first_ability.h @@ -55,6 +55,7 @@ class AbilityContextStartAbilityTest : public EventFwk::CommonEventSubscriber { public: AbilityContextStartAbilityTest(const EventFwk::CommonEventSubscribeInfo &sp) : EventFwk::CommonEventSubscriber(sp){}; + virtual ~AbilityContextStartAbilityTest() = default; virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); }; class ConnectServiceAbilityTest : public EventFwk::CommonEventSubscriber { @@ -66,6 +67,7 @@ public: abilityContext_ = abilityContext; conne_ = conne; }; + virtual ~ConnectServiceAbilityTest() = default; virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; std::shared_ptr abilityContext_ = nullptr; 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..bce1ad6f00bfe8f77b723eebca2a8bdfd4ee7314 100644 --- a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/src/pageAbilityDemo.cpp +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/src/pageAbilityDemo.cpp @@ -19,6 +19,7 @@ namespace OHOS { namespace AppExecFwk { const std::string BUNDLE_DATA_ROOT_PATH = "/data/accounts/account_0/appdata/"; +const int DIR_DEPTH = 7; void PageAbilityDemo::OnStart(const Want &want) { APP_LOGI("PageAbilityDemo::onStart"); @@ -26,7 +27,7 @@ void PageAbilityDemo::OnStart(const Want &want) const std::string appName = "com.third.hiworld.example1"; std::string path = BUNDLE_DATA_ROOT_PATH + appName + "/cache/"; APP_LOGI("PageAbilityDemo::CreateDir"); - for (int i = 1; i < 7; i++) { + for (int i = 1; i < DIR_DEPTH; i++) { path += "dir" + std::to_string(i) + "/"; APP_LOGI("PageAbilityDemo::CreateDir %{public}s", path.c_str()); CreateDir(path); @@ -74,24 +75,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 index 05035ff2a8d5b96887346b15f6473e2f8e197b3f..6939058dc68e2c0bd987a944d293c410e6acae60 Binary files a/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle41.hap and b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle41.hap differ 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/systemtest/common/ams/ams_ability_visible_test/ams_ability_visible_test.cpp b/test/systemtest/common/ams/ams_ability_visible_test/ams_ability_visible_test.cpp index 22a703ffbda6faf040c4f745626acba83dd18eee..a5e0b79835adb858f54dfff248b545a0821e30eb 100644 --- a/test/systemtest/common/ams/ams_ability_visible_test/ams_ability_visible_test.cpp +++ b/test/systemtest/common/ams/ams_ability_visible_test/ams_ability_visible_test.cpp @@ -174,13 +174,11 @@ public: static sptr abilityMs_; static STtools::Event event_; static std::shared_ptr subscriber_; - static int *memTestValue_; }; sptr AmsAbilityVisibleTest::appMs_ = nullptr; sptr AmsAbilityVisibleTest::abilityMs_ = nullptr; STtools::Event AmsAbilityVisibleTest::event_ = STtools::Event(); -int *AmsAbilityVisibleTest::memTestValue_ = nullptr; std::shared_ptr AmsAbilityVisibleTest::subscriber_ = nullptr; size_t AmsAbilityVisibleTest::AbilityConnectCallback::onAbilityConnectDoneCount = 0; int AmsAbilityVisibleTest::AbilityConnectCallback::resultConnectCode = 0; @@ -217,10 +215,6 @@ void AmsAbilityVisibleTest::SetUp(void) void AmsAbilityVisibleTest::TearDown(void) { GTEST_LOG_(INFO) << "void AmsAbilityVisibleTest::TearDown(void)"; - if (memTestValue_) { - delete[] memTestValue_; - } - std::vector bundleNames = GetBundleNames(bundleNameBase, bundleNameSuffix); STAbilityUtil::UninstallBundle(bundleNames); diff --git a/test/systemtest/common/bms/acts_bms_kit_system_test/acts_bms_kit_system_test.cpp b/test/systemtest/common/bms/acts_bms_kit_system_test/acts_bms_kit_system_test.cpp index a7561ee6b6bc0c186ad33d508896e3ecd3c39f80..11805537bf3a3108a7d446a02de2551a39e7b10e 100644 --- a/test/systemtest/common/bms/acts_bms_kit_system_test/acts_bms_kit_system_test.cpp +++ b/test/systemtest/common/bms/acts_bms_kit_system_test/acts_bms_kit_system_test.cpp @@ -53,7 +53,6 @@ const int TARGETVERSION = 3; namespace OHOS { namespace AppExecFwk { - class BundleStatusCallbackImpl : public BundleStatusCallbackHost { public: BundleStatusCallbackImpl(); @@ -194,7 +193,6 @@ public: void CheckFileNonExist(const std::string &bundleName, const std::string &modulePackage) const; static StressTestLevel stLevel_; }; - StressTestLevel ActsBmsKitSystemTest::stLevel_{}; void ActsBmsKitSystemTest::SetUpTestCase() @@ -228,7 +226,7 @@ void ActsBmsKitSystemTest::Install( InstallParam installParam; installParam.installFlag = installFlag; installParam.userId = Constants::DEFAULT_USERID; - sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); + sptr statusReceiver = new (std::nothrow) StatusReceiverImpl(); EXPECT_NE(statusReceiver, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver); resvec.push_back(statusReceiver->GetResultMsg()); @@ -249,7 +247,7 @@ void ActsBmsKitSystemTest::Uninstall(const std::string &bundleName, std::vector< } else { InstallParam installParam; installParam.userId = Constants::DEFAULT_USERID; - sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); + sptr statusReceiver = new (std::nothrow) StatusReceiverImpl(); EXPECT_NE(statusReceiver, nullptr); installerProxy->Uninstall(bundleName, installParam, statusReceiver); resvec.push_back(statusReceiver->GetResultMsg()); @@ -272,7 +270,7 @@ void ActsBmsKitSystemTest::HapUninstall( } else { InstallParam installParam; installParam.userId = Constants::DEFAULT_USERID; - sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); + sptr statusReceiver = new (std::nothrow) StatusReceiverImpl(); EXPECT_NE(statusReceiver, nullptr); installerProxy->Uninstall(bundleName, modulePackage, installParam, statusReceiver); resvec.push_back(statusReceiver->GetResultMsg()); @@ -342,7 +340,6 @@ void ActsBmsKitSystemTest::CheckFileNonExist(const std::string &bundleName, cons void ActsBmsKitSystemTest::CheckBundleInfo(const uint32_t index, BundleInfo &bundleInfo) const { - CommonTool commonTool; EXPECT_EQ(bundleInfo.name, BASE_BUNDLE_NAME + std::to_string(index)); EXPECT_EQ(bundleInfo.minSdkVersion, 0); EXPECT_EQ(bundleInfo.maxSdkVersion, 0); @@ -353,22 +350,8 @@ void ActsBmsKitSystemTest::CheckBundleInfo(const uint32_t index, BundleInfo &bun std::string strVersion = std::to_string(index) + ".0"; EXPECT_EQ(bundleInfo.versionName, strVersion); EXPECT_EQ(bundleInfo.jointUserId, ""); - std::cout << "bundleInfo-appId:" << bundleInfo.appId << std::endl; - std::cout << "bundleInfo-entryModuleName:" << bundleInfo.entryModuleName << std::endl; EXPECT_EQ(bundleInfo.compatibleVersion, COMPATIBLEVERSION); EXPECT_EQ(bundleInfo.targetVersion, TARGETVERSION); - - EXPECT_EQ(bundleInfo.appId, ""); - std::cout << "bundleInfo-installTime:" << bundleInfo.installTime << std::endl; - std::cout << "bundleInfo-updateTime:" << bundleInfo.updateTime << std::endl; - std::cout << "bundleInfo-moduleDirs:" << commonTool.VectorToStr(bundleInfo.moduleDirs) << std::endl; - std::cout << "bundleInfo-moduleNames:" << commonTool.VectorToStr(bundleInfo.moduleNames) << std::endl; - std::cout << "bundleInfo-reqPermissions:" << commonTool.VectorToStr(bundleInfo.reqPermissions) << std::endl; - std::cout << "bundleInfo-defPermissions:" << commonTool.VectorToStr(bundleInfo.defPermissions) << std::endl; - std::cout << "bundleInfo-hapModuleNames:" << commonTool.VectorToStr(bundleInfo.hapModuleNames) << std::endl; - std::cout << "bundleInfo-modulePublicDirs:" << commonTool.VectorToStr(bundleInfo.modulePublicDirs) << std::endl; - std::cout << "bundleInfo-moduleResPaths:" << commonTool.VectorToStr(bundleInfo.moduleResPaths) << std::endl; - std::vector abilities = bundleInfo.abilityInfos; for (auto iter = abilities.begin(); iter != abilities.end(); iter++) { EXPECT_EQ(iter->bundleName, BASE_BUNDLE_NAME + std::to_string(index)); @@ -384,25 +367,11 @@ void ActsBmsKitSystemTest::CheckBundleInfo(const uint32_t index, BundleInfo &bun EXPECT_EQ(iOrientation, 0); int iType = (int)iter->type; EXPECT_EQ(iType, 1); - std::cout << "abilityInfo-type:" << iType << std::endl; - std::cout << "abilityInfo-process:" << iter->process << std::endl; - std::cout << "abilityInfo-permissions:" << commonTool.VectorToStr(iter->permissions) << std::endl; - std::cout << "abilityInfo-deviceTypes:" << commonTool.VectorToStr(iter->deviceTypes) << std::endl; - std::cout << "deviceCapabilities:" << commonTool.VectorToStr(iter->deviceCapabilities) << std::endl; } - ApplicationInfo applicationInfo = bundleInfo.applicationInfo; EXPECT_EQ(applicationInfo.name, (BASE_BUNDLE_NAME + std::to_string(index))); - std::cout << "applicationInfo-description:" << applicationInfo.description << std::endl; - std::cout << "applicationInfo-iconPath:" << applicationInfo.iconPath << std::endl; - std::cout << "applicationInfo-label:" << applicationInfo.label << std::endl; EXPECT_FALSE(applicationInfo.isSystemApp); EXPECT_EQ(applicationInfo.supportedModes, 0); - std::cout << "applicationInfo-supportedModes:" << applicationInfo.supportedModes << std::endl; - std::cout << "applicationInfo-process:" << applicationInfo.process << std::endl; - std::cout << "moduleSourceDirs:" << commonTool.VectorToStr(applicationInfo.moduleSourceDirs) << std::endl; - std::cout << "permissions:" << commonTool.VectorToStr(applicationInfo.permissions) << std::endl; - for (auto appModuleInfo : applicationInfo.moduleInfos) { std::cout << "applicationInfo-moduleName:" << appModuleInfo.moduleName << std::endl; std::cout << "applicationInfo-moduleSourceDir:" << appModuleInfo.moduleSourceDir << std::endl; @@ -2458,11 +2427,8 @@ HWTEST_F(ActsBmsKitSystemTest, GetHapModuleInfo_0200, Function | MediumTest | Le std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle2.hap"; std::string appName = BASE_BUNDLE_NAME + "1"; Install(bundleFilePath, InstallFlag::NORMAL, resvec); - CommonTool commonTool; - std::string installResult = commonTool.VectorToStr(resvec); - EXPECT_EQ(installResult, "Success") << "install fail!"; - + EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; AbilityInfo abilityInfo; abilityInfo.bundleName = appName; abilityInfo.package = BASE_BUNDLE_NAME + ".h1"; @@ -2491,8 +2457,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetHapModuleInfo_0200, Function | MediumTest | Le } resvec.clear(); Uninstall(appName, resvec); - std::string uninstallResult = commonTool.VectorToStr(resvec); - EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "uninstall fail!"; if (!queryResult) { APP_LOGI("GetHapModuleInfo_0200 failed - cycle count: %{public}d", i); @@ -2500,7 +2465,6 @@ HWTEST_F(ActsBmsKitSystemTest, GetHapModuleInfo_0200, Function | MediumTest | Le } result = true; } - if (result && stLevel_.BMSLevel > 1) { APP_LOGI("GetHapModuleInfo_0200 success - cycle count: %{public}d", stLevel_.BMSLevel); } @@ -3110,7 +3074,6 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0700, Function | MediumTest | Level1) std::string firstAppName = BASE_BUNDLE_NAME + "1"; std::string secondFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle7.hap"; std::string secondAppName = BASE_BUNDLE_NAME + "2"; - CommonTool commonTool; sptr firstBundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); EXPECT_NE(firstBundleStatusCallback, nullptr); @@ -3122,37 +3085,28 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0700, Function | MediumTest | Level1) } bundleMgrProxy->RegisterBundleStatusCallback(firstBundleStatusCallback); Install(firstFilePath, InstallFlag::NORMAL, resvec); - std::string firstinstallResult = commonTool.VectorToStr(resvec); - EXPECT_EQ(firstinstallResult, "Success") << "install fail!"; - + EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; resvec.clear(); sptr secondBundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); EXPECT_NE(secondBundleStatusCallback, nullptr); secondBundleStatusCallback->SetBundleName(secondAppName); bundleMgrProxy->RegisterBundleStatusCallback(secondBundleStatusCallback); Install(secondFilePath, InstallFlag::NORMAL, resvec); - std::string secondinstallResult = commonTool.VectorToStr(resvec); - EXPECT_EQ(secondinstallResult, "Success") << "install fail!"; - + EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; bool clearResult = bundleMgrProxy->ClearBundleStatusCallback(firstBundleStatusCallback); EXPECT_TRUE(clearResult); - std::vector resvec2; Uninstall(firstAppName, resvec2); - std::string uninstallResult = commonTool.VectorToStr(resvec2); - EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(commonTool.VectorToStr(resvec2), "Success") << "uninstall fail!"; resvec2.clear(); Uninstall(secondAppName, resvec2); - uninstallResult = commonTool.VectorToStr(resvec2); - EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; - + EXPECT_EQ(commonTool.VectorToStr(resvec2), "Success") << "uninstall fail!"; if (!clearResult) { APP_LOGI("Callback_0700 failed - cycle count: %{public}d", i); break; } result = true; } - if (result && stLevel_.BMSLevel > 1) { APP_LOGI("Callback_0700 success - cycle count: %{public}d", stLevel_.BMSLevel); } @@ -3181,7 +3135,6 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0800, Function | MediumTest | Level1) std::string firstAppName = BASE_BUNDLE_NAME + "1"; std::string secondFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle7.hap"; std::string secondAppName = BASE_BUNDLE_NAME + "2"; - CommonTool commonTool; sptr firstBundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); EXPECT_NE(firstBundleStatusCallback, nullptr); @@ -3195,7 +3148,6 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0800, Function | MediumTest | Level1) Install(firstFilePath, InstallFlag::NORMAL, resvec); std::string firstinstallResult = commonTool.VectorToStr(resvec); EXPECT_EQ(firstinstallResult, "Success") << "install fail!"; - resvec.clear(); sptr secondBundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); EXPECT_NE(secondBundleStatusCallback, nullptr); @@ -3204,26 +3156,20 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0800, Function | MediumTest | Level1) Install(secondFilePath, InstallFlag::NORMAL, resvec); std::string secondinstallResult = commonTool.VectorToStr(resvec); EXPECT_EQ(secondinstallResult, "Success") << "install fail!"; - bool clearResult = bundleMgrProxy->ClearBundleStatusCallback(secondBundleStatusCallback); EXPECT_TRUE(clearResult); - std::vector resvec2; Uninstall(firstAppName, resvec2); - std::string uninstallResult = commonTool.VectorToStr(resvec2); - EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(commonTool.VectorToStr(resvec2), "Success") << "uninstall fail!"; resvec2.clear(); Uninstall(secondAppName, resvec2); - uninstallResult = commonTool.VectorToStr(resvec2); - EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; - + EXPECT_EQ(commonTool.VectorToStr(resvec2), "Success") << "uninstall fail!"; if (!clearResult) { APP_LOGI("Callback_0800 failed - cycle count: %{public}d", i); break; } result = true; } - if (result && stLevel_.BMSLevel > 1) { APP_LOGI("Callback_0800 success - cycle count: %{public}d", stLevel_.BMSLevel); } @@ -3253,7 +3199,6 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0900, Function | MediumTest | Level1) std::string firstAppName = BASE_BUNDLE_NAME + "1"; std::string secondFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle7.hap"; std::string secondAppName = BASE_BUNDLE_NAME + "2"; - CommonTool commonTool; sptr firstBundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); EXPECT_NE(firstBundleStatusCallback, nullptr); @@ -3265,39 +3210,30 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0900, Function | MediumTest | Level1) } bundleMgrProxy->RegisterBundleStatusCallback(firstBundleStatusCallback); Install(firstFilePath, InstallFlag::NORMAL, resvec); - std::string firstinstallResult = commonTool.VectorToStr(resvec); - EXPECT_EQ(firstinstallResult, "Success") << "install fail!"; - + EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; resvec.clear(); sptr secondBundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); EXPECT_NE(secondBundleStatusCallback, nullptr); secondBundleStatusCallback->SetBundleName(secondAppName); bundleMgrProxy->RegisterBundleStatusCallback(secondBundleStatusCallback); Install(secondFilePath, InstallFlag::NORMAL, resvec); - std::string secondinstallResult = commonTool.VectorToStr(resvec); - EXPECT_EQ(secondinstallResult, "Success") << "install fail!"; - + EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; bool clearResult1 = bundleMgrProxy->ClearBundleStatusCallback(firstBundleStatusCallback); EXPECT_TRUE(clearResult1); bool clearResult2 = bundleMgrProxy->ClearBundleStatusCallback(secondBundleStatusCallback); EXPECT_TRUE(clearResult2); - std::vector resvec2; Uninstall(firstAppName, resvec2); - std::string uninstallResult = commonTool.VectorToStr(resvec2); - EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(commonTool.VectorToStr(resvec2), "Success") << "uninstall fail!"; resvec2.clear(); Uninstall(secondAppName, resvec2); - uninstallResult = commonTool.VectorToStr(resvec2); - EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; - + EXPECT_EQ(commonTool.VectorToStr(resvec2), "Success") << "uninstall fail!"; if (!clearResult1 && !clearResult2) { APP_LOGI("Callback_0900 failed - cycle count: %{public}d", i); break; } result = true; } - if (result && stLevel_.BMSLevel > 1) { APP_LOGI("Callback_0900 success - cycle count: %{public}d", stLevel_.BMSLevel); } @@ -3510,7 +3446,6 @@ HWTEST_F(ActsBmsKitSystemTest, CleanBundleCacheFiles_0400, Function | MediumTest std::vector resvec; std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle45.hap"; std::string appName = BASE_BUNDLE_NAME + "1"; - CommonTool commonTool; Install(bundleFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); @@ -3540,19 +3475,15 @@ HWTEST_F(ActsBmsKitSystemTest, CleanBundleCacheFiles_0400, Function | MediumTest EXPECT_NE(name1Exist, 0) << "the cache test dir1 exists."; name2Exist = access(testCacheDir2.c_str(), F_OK); EXPECT_NE(name2Exist, 0) << "the cache test dir2 exists."; - resvec.clear(); Uninstall(appName, resvec); - std::string uninstallResult = commonTool.VectorToStr(resvec); - EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; - + EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "uninstall fail!"; if (!cleanCacheResult) { APP_LOGI("CleanBundleCacheFiles_0400 failed - cycle count: %{public}d", i); break; } result = true; } - if (result && stLevel_.BMSLevel > 1) { APP_LOGI("CleanBundleCacheFiles_0400 success - cycle count: %{public}d", stLevel_.BMSLevel); } @@ -4012,11 +3943,8 @@ HWTEST_F(ActsBmsKitSystemTest, AbilityDump_0100, Function | MediumTest | Level0) std::string appName = BASE_BUNDLE_NAME + "1"; std::string abilityName = "bmsThirdBundle_A1"; Install(bundleFilePath, InstallFlag::NORMAL, resvec); - CommonTool commonTool; - std::string installResult = commonTool.VectorToStr(resvec); - EXPECT_EQ(installResult, "Success") << "install fail!"; - + EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; Want want; ElementName name; name.SetAbilityName(abilityName); @@ -4032,7 +3960,6 @@ HWTEST_F(ActsBmsKitSystemTest, AbilityDump_0100, Function | MediumTest | Level0) bool queryResult = bundleMgrProxy->QueryAbilityInfo(want, abilityInfo); EXPECT_EQ(abilityInfo.name, abilityName); EXPECT_TRUE(queryResult); - std::string path = "/data/test/abilityInfo.txt"; std::ofstream file(path); file.close(); @@ -4043,19 +3970,15 @@ HWTEST_F(ActsBmsKitSystemTest, AbilityDump_0100, Function | MediumTest | Level0) long length = lseek(fd, 0, SEEK_END); EXPECT_GT(length, 0); close(fd); - resvec.clear(); Uninstall(appName, resvec); - std::string uninstallResult = commonTool.VectorToStr(resvec); - EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; - + EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "uninstall fail!"; if (!queryResult) { APP_LOGI("AbilityDump_0100 failed - cycle count: %{public}d", i); break; } result = true; } - if (result && stLevel_.BMSLevel > 1) { APP_LOGI("AbilityDump_0100 success - cycle count: %{public}d", stLevel_.BMSLevel); } @@ -4509,14 +4432,10 @@ HWTEST_F(ActsBmsKitSystemTest, ApplicationInfo_0100, Function | MediumTest | Lev bool result = false; for (int i = 1; i <= stLevel_.BMSLevel; i++) { std::vector resvec; - std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; std::string appName = BASE_BUNDLE_NAME + "1"; - Install(bundleFilePath, InstallFlag::NORMAL, resvec); - + Install(THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap", InstallFlag::NORMAL, resvec); CommonTool commonTool; - std::string installResult = commonTool.VectorToStr(resvec); - EXPECT_EQ(installResult, "Success") << "install fail!"; - + EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; ApplicationInfo appInfo; int userId = Constants::DEFAULT_USERID; sptr bundleMgrProxy = GetBundleMgrProxy(); @@ -4534,8 +4453,7 @@ HWTEST_F(ActsBmsKitSystemTest, ApplicationInfo_0100, Function | MediumTest | Lev file.close(); int fd = open(path.c_str(), O_RDWR); EXPECT_NE(fd, -1) << "open file error"; - std::string prefix = "[pAppInfo]"; - pAppInfo->Dump(prefix, fd); + pAppInfo->Dump("[pAppInfo]", fd); long length = lseek(fd, 0, SEEK_END); lseek(fd, 0, SEEK_SET); std::string strAppInfo; @@ -4546,19 +4464,15 @@ HWTEST_F(ActsBmsKitSystemTest, ApplicationInfo_0100, Function | MediumTest | Lev std::string cacheDir = BUNDLE_DATA_ROOT_PATH + appName + "/cache"; EXPECT_TRUE(IsSubStr(strAppInfo, cacheDir)); close(fd); - resvec.clear(); Uninstall(appName, resvec); - std::string uninstallResult = commonTool.VectorToStr(resvec); - EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; - + EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "uninstall fail!"; if (retVal <= 0) { APP_LOGI("ApplicationInfo_0100 failed - cycle count: %{public}d", i); break; } result = true; } - if (result && stLevel_.BMSLevel > 1) { APP_LOGI("ApplicationInfo_0100 success - cycle count: %{public}d", stLevel_.BMSLevel); } @@ -4710,7 +4624,7 @@ HWTEST_F(ActsBmsKitSystemTest, Uninstall_KeepData_0100, Function | MediumTest | installParam.installFlag = InstallFlag::NORMAL; installParam.userId = Constants::DEFAULT_USERID; installParam.isKeepData = false; - sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); + sptr statusReceiver = new (std::nothrow) StatusReceiverImpl(); EXPECT_NE(statusReceiver, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver); std::string installMsg = statusReceiver->GetResultMsg(); @@ -4747,7 +4661,7 @@ HWTEST_F(ActsBmsKitSystemTest, Uninstall_KeepData_0200, Function | MediumTest | installParam.installFlag = InstallFlag::NORMAL; installParam.userId = Constants::DEFAULT_USERID; installParam.isKeepData = true; - sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); + sptr statusReceiver = new (std::nothrow) StatusReceiverImpl(); EXPECT_NE(statusReceiver, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver); std::string installMsg = statusReceiver->GetResultMsg(); @@ -4784,14 +4698,14 @@ HWTEST_F(ActsBmsKitSystemTest, Uninstall_KeepData_0300, Function | MediumTest | installParam.installFlag = InstallFlag::NORMAL; installParam.userId = Constants::DEFAULT_USERID; installParam.isKeepData = false; - sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); + sptr statusReceiver = new (std::nothrow) StatusReceiverImpl(); EXPECT_NE(statusReceiver, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver); std::string installMsg = statusReceiver->GetResultMsg(); EXPECT_EQ(installMsg, "Success") << "install fail!"; bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle4.hap"; - sptr statusReceiver2 = (new (std::nothrow) StatusReceiverImpl()); + sptr statusReceiver2 = new (std::nothrow) StatusReceiverImpl(); EXPECT_NE(statusReceiver2, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver2); installMsg = statusReceiver2->GetResultMsg(); @@ -4835,14 +4749,14 @@ HWTEST_F(ActsBmsKitSystemTest, Uninstall_KeepData_0400, Function | MediumTest | installParam.installFlag = InstallFlag::NORMAL; installParam.userId = Constants::DEFAULT_USERID; installParam.isKeepData = true; - sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); + sptr statusReceiver = new (std::nothrow) StatusReceiverImpl(); EXPECT_NE(statusReceiver, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver); std::string installMsg = statusReceiver->GetResultMsg(); EXPECT_EQ(installMsg, "Success") << "install fail!"; bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle4.hap"; - sptr statusReceiver2 = (new (std::nothrow) StatusReceiverImpl()); + sptr statusReceiver2 = new (std::nothrow) StatusReceiverImpl(); EXPECT_NE(statusReceiver2, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver2); installMsg = statusReceiver2->GetResultMsg(); @@ -4881,24 +4795,20 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundlesForUid_0100, Function | MediumTest | Le APP_LOGE("bundle mgr proxy is nullptr."); EXPECT_EQ(bundleMgrProxy, nullptr); } - std::string installResult; CommonTool commonTool; for (int i = 6; i <= 8; i++) { std::vector resvec; std::string hapFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle" + std::to_string(i) + ".hap"; - std::cout << "begin install" << hapFilePath << std::endl; Install(hapFilePath, InstallFlag::NORMAL, resvec); - installResult = commonTool.VectorToStr(resvec); - EXPECT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; } bool ret; for (int i = 1; i <= 3; i++) { std::string appName = BASE_BUNDLE_NAME + std::to_string(i); BundleInfo bundleInfo; bundleMgrProxy->GetBundleInfo(appName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); - int uid = bundleInfo.uid; std::vector bundleNames; - ret = bundleMgrProxy->GetBundlesForUid(uid, bundleNames); + ret = bundleMgrProxy->GetBundlesForUid(bundleInfo.uid, bundleNames); EXPECT_TRUE(ret); for (auto bundleName : bundleNames) { EXPECT_EQ(bundleName, appName); @@ -4908,8 +4818,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundlesForUid_0100, Function | MediumTest | Le std::vector resvec; std::string appName = BASE_BUNDLE_NAME + std::to_string(i); Uninstall(appName, resvec); - std::string uninstallResult = commonTool.VectorToStr(resvec); - EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "uninstall fail!"; } if (!ret) { APP_LOGI("GetBundlesForUid_0100 failed - cycle count: %{public}d", i); @@ -5014,55 +4923,39 @@ HWTEST_F(ActsBmsKitSystemTest, GetNameForUid_0100, Function | MediumTest | Level bool result = false; for (int i = 1; i <= stLevel_.BMSLevel; i++) { CommonTool commonTool; - std::string installResult; std::vector resvec; - std::string bundleFilePath1 = THIRD_BUNDLE_PATH + "bmsThirdBundle6.hap"; - std::string bundleFilePath2 = THIRD_BUNDLE_PATH + "bmsThirdBundle7.hap"; - std::string appName1 = BASE_BUNDLE_NAME + '1'; - std::string appName2 = BASE_BUNDLE_NAME + '2'; - std::string name1; - std::string name2; - Install(bundleFilePath1, InstallFlag::NORMAL, resvec); - installResult = commonTool.VectorToStr(resvec); - EXPECT_EQ(installResult, "Success") << "install fail!"; + std::string name1, name2; + Install(THIRD_BUNDLE_PATH + "bmsThirdBundle6.hap", InstallFlag::NORMAL, resvec); + EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; resvec.clear(); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); EXPECT_EQ(bundleMgrProxy, nullptr); } - BundleInfo bundleInfo1; - bundleMgrProxy->GetBundleInfo(appName1, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo1); - int uid1 = bundleInfo1.uid; - bool ret = bundleMgrProxy->GetNameForUid(uid1, name1); + bundleMgrProxy->GetBundleInfo(BASE_BUNDLE_NAME + '1', BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo1); + bool ret = bundleMgrProxy->GetNameForUid(bundleInfo1.uid, name1); EXPECT_TRUE(ret); - - Uninstall(appName1, resvec); + Uninstall(BASE_BUNDLE_NAME + '1', resvec); EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "uninstall fail!"; resvec.clear(); - Install(bundleFilePath2, InstallFlag::NORMAL, resvec); - installResult = commonTool.VectorToStr(resvec); - EXPECT_EQ(installResult, "Success") << "install fail!"; + Install(THIRD_BUNDLE_PATH + "bmsThirdBundle7.hap", InstallFlag::NORMAL, resvec); + EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; resvec.clear(); - - Install(bundleFilePath1, InstallFlag::NORMAL, resvec); - installResult = commonTool.VectorToStr(resvec); - EXPECT_EQ(installResult, "Success") << "install fail!"; - + Install(THIRD_BUNDLE_PATH + "bmsThirdBundle6.hap", InstallFlag::NORMAL, resvec); + EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; BundleInfo bundleInfo2; - bundleMgrProxy->GetBundleInfo(appName1, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo2); - int uid2 = bundleInfo2.uid; - ret = bundleMgrProxy->GetNameForUid(uid2, name2); + bundleMgrProxy->GetBundleInfo(BASE_BUNDLE_NAME + '1', BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo2); + ret = bundleMgrProxy->GetNameForUid(bundleInfo2.uid, name2); EXPECT_TRUE(ret); - EXPECT_NE(uid1, uid2); + EXPECT_NE(bundleInfo1.uid, bundleInfo2.uid); EXPECT_EQ(name1, name2); for (int i = 1; i <= 2; i++) { std::string appName = BASE_BUNDLE_NAME + std::to_string(i); std::vector resvec2; Uninstall(appName, resvec2); - std::string uninstallResult = commonTool.VectorToStr(resvec2); - EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(commonTool.VectorToStr(resvec2), "Success") << "uninstall fail!"; } if (!ret) { APP_LOGI("GetNameForUid_0100 failed - cycle count: %{public}d", i); @@ -5070,7 +4963,6 @@ HWTEST_F(ActsBmsKitSystemTest, GetNameForUid_0100, Function | MediumTest | Level } result = true; } - if (result && stLevel_.BMSLevel > 1) { APP_LOGI("GetNameForUid_0100 success - cycle count: %{public}d", stLevel_.BMSLevel); } @@ -5861,4 +5753,4 @@ HWTEST_F(ActsBmsKitSystemTest, IsApplicationEnabled_0300, Function | MediumTest std::cout << "END IsApplicationEnabled_0300" << std::endl; } } // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/test/systemtest/common/bms/bms_compatible_system_test/bms_compatible_system_test.cpp b/test/systemtest/common/bms/bms_compatible_system_test/bms_compatible_system_test.cpp index e44d524d26f483132cc303199b146068b2f917e8..eeb0dcf8762895e8cf0c0bd958245b0daca0fa6b 100644 --- a/test/systemtest/common/bms/bms_compatible_system_test/bms_compatible_system_test.cpp +++ b/test/systemtest/common/bms/bms_compatible_system_test/bms_compatible_system_test.cpp @@ -49,7 +49,6 @@ const int MIN_WIDTH = 100; const int DEFAULT_HEIGHT = 100; const int DEFAULT_WIDTH = 200; const int FORM_NUM = 3; - } // namespace using OHOS::AAFwk::Want; using namespace testing::ext; @@ -152,7 +151,7 @@ void BmsCompatibleSystemTest::Uninstall(const std::string &bundleName, std::stri } else { InstallParam installParam; installParam.userId = Constants::DEFAULT_USERID; - sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); + sptr statusReceiver = new (std::nothrow) StatusReceiverImpl(); EXPECT_NE(statusReceiver, nullptr); installerProxy->Uninstall(bundleName, installParam, statusReceiver); uninstallMessage = statusReceiver->GetResultMsg(); @@ -509,7 +508,7 @@ HWTEST_F(BmsCompatibleSystemTest, BMS_ConvertToCompatible_0800, Function | Mediu int userId = Constants::DEFAULT_USERID; Install(bundleFilePath, InstallFlag::NORMAL, message); - ASSERT_EQ(message, "Success") << "install fail!"; + EXPECT_EQ(message, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (bundleMgrProxy == nullptr) { @@ -527,7 +526,7 @@ HWTEST_F(BmsCompatibleSystemTest, BMS_ConvertToCompatible_0800, Function | Mediu std::string permissions = commonTool.VectorToStr(compatibleApplicationInfo.permissions); EXPECT_EQ(permissions, CAMERA); Uninstall(bundleName, message); - ASSERT_EQ(message, "Success") << "uninstall fail!"; + EXPECT_EQ(message, "Success") << "uninstall fail!"; GTEST_LOG_(INFO) << "END BMS_ConvertToCompatible_0800"; } /** @@ -572,9 +571,9 @@ HWTEST_F(BmsCompatibleSystemTest, BMS_ConvertToCompatible_1000, Function | Mediu int userId = Constants::DEFAULT_USERID; Install(bundleFilePath1, InstallFlag::NORMAL, message); - ASSERT_EQ(message, "Success") << "install fail!"; + EXPECT_EQ(message, "Success") << "install fail!"; Install(bundleFilePath2, InstallFlag::REPLACE_EXISTING, message); - ASSERT_EQ(message, "Success") << "install fail!"; + EXPECT_EQ(message, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (bundleMgrProxy == nullptr) { @@ -590,7 +589,7 @@ HWTEST_F(BmsCompatibleSystemTest, BMS_ConvertToCompatible_1000, Function | Mediu EXPECT_EQ(compatibleApplicationInfo.name, bundleName); CheckCompatibleApplicationInfo(compatibleApplicationInfo, bundleName); Uninstall(bundleName, message); - ASSERT_EQ(message, "Success") << "uninstall fail!"; + EXPECT_EQ(message, "Success") << "uninstall fail!"; GTEST_LOG_(INFO) << "END BMS_ConvertToCompatible_1000"; } /** @@ -607,9 +606,9 @@ HWTEST_F(BmsCompatibleSystemTest, BMS_ConvertToCompatible_1100, Function | Mediu std::string message; int userId = Constants::DEFAULT_USERID; Install(bundleFilePath, InstallFlag::NORMAL, message); - ASSERT_EQ(message, "Success") << "install fail!"; + EXPECT_EQ(message, "Success") << "install fail!"; Uninstall(bundleName, message); - ASSERT_EQ(message, "Success") << "uninstall fail!"; + EXPECT_EQ(message, "Success") << "uninstall fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (bundleMgrProxy == nullptr) { @@ -664,7 +663,7 @@ HWTEST_F(BmsCompatibleSystemTest, BMS_QueryAbilityInfoByUri_0100, Function | Med std::string uri = "dataability://com.test.demo.dataability.UserADataAbility"; std::string message; Install(bundleFilePath, InstallFlag::NORMAL, message); - ASSERT_EQ(message, "Success") << "install fail!"; + EXPECT_EQ(message, "Success") << "install fail!"; std::string abilityUri = "dataability:///com.test.demo.dataability.UserADataAbility"; AbilityInfo abilityInfo; sptr bundleMgrProxy = GetBundleMgrProxy(); @@ -678,7 +677,7 @@ HWTEST_F(BmsCompatibleSystemTest, BMS_QueryAbilityInfoByUri_0100, Function | Med EXPECT_EQ(abilityInfo.bundleName, bundleName); EXPECT_EQ(abilityInfo.uri, uri); Uninstall(bundleName, message); - ASSERT_EQ(message, "Success") << "uninstall fail!"; + EXPECT_EQ(message, "Success") << "uninstall fail!"; GTEST_LOG_(INFO) << "END BMS_QueryAbilityInfoByUri_0100"; } /** @@ -725,6 +724,5 @@ HWTEST_F(BmsCompatibleSystemTest, BMS_QueryAbilityInfoByUri_0300, Function | Med EXPECT_EQ(abilityInfo.uri, ""); GTEST_LOG_(INFO) << "END BMS_QueryAbilityInfoByUri_0300"; } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/bms/bms_install_system_test/bms_install_system_test.cpp b/test/systemtest/common/bms/bms_install_system_test/bms_install_system_test.cpp index b018a324f714d7dc0d19c17b3f7680aa08257bc7..3c2cf82c4e07efb70749da69a328ec0410feb9ec 100755 --- a/test/systemtest/common/bms/bms_install_system_test/bms_install_system_test.cpp +++ b/test/systemtest/common/bms/bms_install_system_test/bms_install_system_test.cpp @@ -31,7 +31,6 @@ using namespace testing::ext; using namespace std::chrono_literals; namespace { - const std::string THIRD_BUNDLE_PATH = "/data/test/bms_bundle/"; const std::string CODE_ROOT_PATH = "/data/accounts/account_0/applications/"; const std::string DATA_ROOT_PATH = "/data/accounts/account_0/appdata/"; @@ -41,6 +40,7 @@ const std::string SYSTEM_BASE_BUNDLE_NAME = "com.system.hiworld.example"; const std::string MSG_SUCCESS = "[SUCCESS]"; const std::string OPERATION_FAILURE = "Failure"; const std::string OPERATION_SUCCESS = "Success"; +const int TIMEOUT = 10; } // namespace namespace OHOS { @@ -87,7 +87,7 @@ void StatusReceiverImpl::OnFinished(const int32_t resultCode, const std::string std::string StatusReceiverImpl::GetResultMsg() const { auto future = resultMsgSignal_.get_future(); - std::chrono::seconds timeout(10); + std::chrono::seconds timeout(TIMEOUT); if (future.wait_for(timeout) == std::future_status::timeout) { return OPERATION_FAILURE + " timeout"; } @@ -103,6 +103,7 @@ public: explicit SubscriberTest(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; virtual void OnReceiveEvent(const CommonEventData &data) override; std::string GetSubscriberResultMsg() const; + virtual ~SubscriberTest() = default; private: mutable std::promise subscriberMsgSignal_; @@ -2445,6 +2446,5 @@ HWTEST_F(BmsInstallSystemTest, BMS_DFX_0400, Function | MediumTest | Level2) EXPECT_FALSE(getInfoResult); std::cout << "END BMS_DFX_0400" << std::endl; } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/bms/bms_launcher_service_system_test/bms_launcher_service_system_test.cpp b/test/systemtest/common/bms/bms_launcher_service_system_test/bms_launcher_service_system_test.cpp index 3fa58800fc32e6c7b93f7d0d68cc485c523d4861..30137f71ee9761cc5de883d40a822cd907ba3ade 100644 --- a/test/systemtest/common/bms/bms_launcher_service_system_test/bms_launcher_service_system_test.cpp +++ b/test/systemtest/common/bms/bms_launcher_service_system_test/bms_launcher_service_system_test.cpp @@ -44,7 +44,7 @@ const std::string BUNDLE_ADD = "Bundle Add Success"; const std::string BUNDLE_UPDATE = "Bundle Update Success"; const std::string BUNDLE_REMOVE = "Bundle Remove Success"; constexpr uint32_t WAIT_SECONDS = 5; - +const unsigned int LIST_SIZE = 2; } // namespace using OHOS::AAFwk::Want; using namespace testing::ext; @@ -173,7 +173,7 @@ void BmsLauncherServiceSystemTest::Install( InstallParam installParam; installParam.installFlag = installFlag; installParam.userId = Constants::DEFAULT_USERID; - sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); + sptr statusReceiver = new (std::nothrow) StatusReceiverImpl(); EXPECT_NE(statusReceiver, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver); installMessage = statusReceiver->GetResultMsg(); @@ -194,7 +194,7 @@ void BmsLauncherServiceSystemTest::Uninstall(const std::string &bundleName, std: } else { InstallParam installParam; installParam.userId = Constants::DEFAULT_USERID; - sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); + sptr statusReceiver = new (std::nothrow) StatusReceiverImpl(); EXPECT_NE(statusReceiver, nullptr); installerProxy->Uninstall(bundleName, installParam, statusReceiver); uninstallMessage = statusReceiver->GetResultMsg(); @@ -294,13 +294,13 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_Register_0100, Function | MediumTest std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; std::string bundleName = "com.example.third1"; std::string message; - std::shared_ptr launcherservice = std::make_shared(); + LauncherService launcherservice; sptr callback = new TestBundleStatusCallback(); - launcherservice->RegisterCallback(callback); + launcherservice.RegisterCallback(callback); Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; EXPECT_TRUE(Wait(BUNDLE_ADD)); - launcherservice->UnRegisterCallback(); + launcherservice.UnRegisterCallback(); Uninstall(bundleName, message); EXPECT_EQ(message, "Success") << "uninstall fail!"; GTEST_LOG_(INFO) << "END BMS_Register_0100"; @@ -316,15 +316,15 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_Register_0200, Function | MediumTest std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; std::string bundleName = "com.example.third1"; std::string message; - std::shared_ptr launcherservice = std::make_shared(); + LauncherService launcherservice; sptr callback = new TestBundleStatusCallback(); - launcherservice->RegisterCallback(callback); + launcherservice.RegisterCallback(callback); Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; Uninstall(bundleName, message); EXPECT_TRUE(Wait(BUNDLE_REMOVE)); EXPECT_EQ(message, "Success") << "uninstall fail!"; - launcherservice->UnRegisterCallback(); + launcherservice.UnRegisterCallback(); GTEST_LOG_(INFO) << "END BMS_Register_0200"; } /** @@ -339,16 +339,16 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_Register_0300, Function | MediumTest std::string bundleFilePath1 = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; std::string bundleFilePath2 = THIRD_BUNDLE_PATH + "bmsThirdBundle4.hap"; std::string message; - std::shared_ptr launcherservice = std::make_shared(); + LauncherService launcherservice; sptr callback = new TestBundleStatusCallback(); - launcherservice->RegisterCallback(callback); + launcherservice.RegisterCallback(callback); Install(bundleFilePath1, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; EXPECT_TRUE(Wait(BUNDLE_ADD)); Install(bundleFilePath2, InstallFlag::REPLACE_EXISTING, message); EXPECT_EQ(message, "Success") << "install fail!"; EXPECT_TRUE(Wait(BUNDLE_UPDATE)); - launcherservice->UnRegisterCallback(); + launcherservice.UnRegisterCallback(); Uninstall(bundleName, message); EXPECT_EQ(message, "Success") << "uninstall fail!"; GTEST_LOG_(INFO) << "END BMS_Register_0300"; @@ -364,10 +364,10 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_Register_0400, Function | MediumTest std::string bundleName = THIRD_BASE_BUNDLE_NAME + "2"; std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle2.hap"; std::string message; - std::shared_ptr launcherservice = std::make_shared(); + LauncherService launcherservice; sptr callback = new TestBundleStatusCallback(); - launcherservice->RegisterCallback(callback); - launcherservice->UnRegisterCallback(); + launcherservice.RegisterCallback(callback); + launcherservice.UnRegisterCallback(); Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; EXPECT_FALSE(Wait(BUNDLE_ADD)); @@ -392,13 +392,9 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0100, Function | Mediu Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; - std::shared_ptr launcherservice = std::make_shared(); + LauncherService launcherservice; std::vector launcherAbilityInfos; - if (!launcherservice) { - APP_LOGE("launcher service is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); + bool result = launcherservice.GetAbilityList(bundleName, userId, launcherAbilityInfos); EXPECT_TRUE(result) << "Get ability list failed"; EXPECT_FALSE(launcherAbilityInfos.empty()) << "Launcher ability infos is empty"; EXPECT_EQ(launcherAbilityInfos[0].name, abilityName); @@ -429,13 +425,9 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0200, Function | Mediu Install(bundleFilePath2, InstallFlag::REPLACE_EXISTING, message); EXPECT_EQ(message, "Success") << "install fail!"; - std::shared_ptr launcherservice = std::make_shared(); + LauncherService launcherservice; std::vector launcherAbilityInfos; - if (!launcherservice) { - APP_LOGE("launcher service is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); + bool result = launcherservice.GetAbilityList(bundleName, userId, launcherAbilityInfos); EXPECT_TRUE(result) << "Get ability list failed"; EXPECT_FALSE(launcherAbilityInfos.empty()) << "Launcher ability infos is empty"; EXPECT_EQ(launcherAbilityInfos[0].name, abilityName); @@ -462,15 +454,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0300, Function | Mediu Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; std::vector launcherAbilityInfos; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcher service is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); + LauncherService launcherservice; + + bool result = launcherservice.GetAbilityList(bundleName, userId, launcherAbilityInfos); EXPECT_TRUE(result) << "Get ability list failed"; EXPECT_FALSE(launcherAbilityInfos.empty()) << "Launcher ability infos is empty"; - EXPECT_GE(launcherAbilityInfos.size(), 1); + EXPECT_EQ(launcherAbilityInfos.size(), LIST_SIZE); EXPECT_EQ(launcherAbilityInfos[0].name, abilityName1); EXPECT_EQ(launcherAbilityInfos[1].name, abilityName2); Uninstall(bundleName, message); @@ -500,15 +489,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0400, Function | Mediu Install(bundleFilePath2, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; std::vector launcherAbilityInfos; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcher service is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); + LauncherService launcherservice; + + bool result = launcherservice.GetAbilityList(bundleName, userId, launcherAbilityInfos); EXPECT_TRUE(result) << "Get ability list failed"; EXPECT_FALSE(launcherAbilityInfos.empty()) << "Launcher ability infos is empty"; - EXPECT_GE(launcherAbilityInfos.size(), 1); + EXPECT_EQ(launcherAbilityInfos.size(), LIST_SIZE); EXPECT_EQ(launcherAbilityInfos[0].name, abilityName1); EXPECT_EQ(launcherAbilityInfos[1].name, abilityName2); Uninstall(bundleName, message); @@ -527,12 +513,9 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0500, Function | Mediu int userId = Constants::DEFAULT_USERID; std::vector launcherAbilityInfos; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcher service is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); + LauncherService launcherservice; + + bool result = launcherservice.GetAbilityList(bundleName, userId, launcherAbilityInfos); EXPECT_FALSE(result); GTEST_LOG_(INFO) << "END BMS_GetAbilityList_0500"; } @@ -554,13 +537,10 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0600, Function | Mediu Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; - std::shared_ptr launcherservice = std::make_shared(); + LauncherService launcherservice; std::vector launcherAbilityInfos; - if (!launcherservice) { - APP_LOGE("launcher service is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result1 = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); + + bool result1 = launcherservice.GetAbilityList(bundleName, userId, launcherAbilityInfos); EXPECT_TRUE(result1) << "Get ability list failed"; EXPECT_FALSE(launcherAbilityInfos.empty()) << "Launcher ability infos is empty"; EXPECT_EQ(launcherAbilityInfos[0].name, abilityName); @@ -568,7 +548,7 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0600, Function | Mediu Uninstall(bundleName, message); EXPECT_EQ(message, "Success") << "uninstall fail!"; - bool result2 = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); + bool result2 = launcherservice.GetAbilityList(bundleName, userId, launcherAbilityInfos); EXPECT_FALSE(result2); GTEST_LOG_(INFO) << "END BMS_GetAbilityList_0600"; } @@ -585,12 +565,9 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0700, Function | Mediu int userId = Constants::DEFAULT_USERID; std::vector launcherAbilityInfos; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcher service is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); + LauncherService launcherservice; + + bool result = launcherservice.GetAbilityList(bundleName, userId, launcherAbilityInfos); EXPECT_TRUE(result); EXPECT_FALSE(launcherAbilityInfos.empty()) << "Launcher ability infos is empty"; EXPECT_EQ(launcherAbilityInfos[0].name, abilityName); @@ -622,12 +599,9 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityInfo_0100, Function | Mediu want.SetElement(name); LauncherAbilityInfo launcherAbilityInfo; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcherservice is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool Result = launcherservice->GetAbilityInfo(want, userId, launcherAbilityInfo); + LauncherService launcherservice; + + bool Result = launcherservice.GetAbilityInfo(want, userId, launcherAbilityInfo); EXPECT_TRUE(Result); EXPECT_EQ(launcherAbilityInfo.name, abilityName); @@ -658,12 +632,9 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityInfo_0200, Function | Mediu want.SetElement(name); LauncherAbilityInfo launcherAbilityInfos; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcher service is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->GetAbilityInfo(want, userId, launcherAbilityInfos); + LauncherService launcherservice; + + bool result = launcherservice.GetAbilityInfo(want, userId, launcherAbilityInfos); EXPECT_TRUE(result) << "Get ability list failed"; EXPECT_EQ(launcherAbilityInfos.name, abilityName); Uninstall(bundleName, message); @@ -697,12 +668,9 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityInfo_0300, Function | Mediu name.SetBundleName(bundleName); want.SetElement(name); LauncherAbilityInfo launcherAbilityInfo; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcherservice is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->GetAbilityInfo(want, userId, launcherAbilityInfo); + LauncherService launcherservice; + + bool result = launcherservice.GetAbilityInfo(want, userId, launcherAbilityInfo); EXPECT_FALSE(result); GTEST_LOG_(INFO) << "END GetAbilityInfo_0300"; } @@ -724,12 +692,9 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityInfo_0400, Function | Mediu want.SetElement(name); LauncherAbilityInfo launcherAbilityInfo; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcherservice is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool Result = launcherservice->GetAbilityInfo(want, userId, launcherAbilityInfo); + LauncherService launcherservice; + + bool Result = launcherservice.GetAbilityInfo(want, userId, launcherAbilityInfo); EXPECT_TRUE(Result); EXPECT_EQ(launcherAbilityInfo.name, abilityName); @@ -764,12 +729,9 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityInfo_0500, Function | Mediu want.SetElement(name); LauncherAbilityInfo launcherAbilityInfos; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcher service is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->GetAbilityInfo(want, userId, launcherAbilityInfos); + LauncherService launcherservice; + + bool result = launcherservice.GetAbilityInfo(want, userId, launcherAbilityInfos); EXPECT_TRUE(result); EXPECT_EQ(launcherAbilityInfos.name, abilityName); Uninstall(bundleName, message); @@ -790,14 +752,11 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetApplicationInfo_0100, Function | M int userId = Constants::DEFAULT_USERID; Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcher service is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } + LauncherService launcherservice; + ApplicationInfo appInfo; ApplicationFlag flag = ApplicationFlag::GET_BASIC_APPLICATION_INFO; - bool result = launcherservice->GetApplicationInfo(bundleName, flag, userId, appInfo); + bool result = launcherservice.GetApplicationInfo(bundleName, flag, userId, appInfo); EXPECT_TRUE(result); EXPECT_EQ(appInfo.name, bundleName); Uninstall(bundleName, message); @@ -820,13 +779,10 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetApplicationInfo_0200, Function | M Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcherservice is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } + LauncherService launcherservice; + ApplicationInfo applicationInfo; - bool Result = launcherservice->GetApplicationInfo( + bool Result = launcherservice.GetApplicationInfo( bundleName, ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMS, userId, applicationInfo); EXPECT_TRUE(Result); @@ -849,13 +805,10 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetApplicationInfo_0300, Function | M std::string bundleName = SYSTEM_BASE_BUNDLE_NAME + "1"; int userId = Constants::DEFAULT_USERID; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcherservice is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } + LauncherService launcherservice; + ApplicationInfo applicationInfo; - bool Result = launcherservice->GetApplicationInfo( + bool Result = launcherservice.GetApplicationInfo( bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, applicationInfo); EXPECT_TRUE(Result); EXPECT_EQ(applicationInfo.name, bundleName); @@ -882,13 +835,10 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetApplicationInfo_0400, Function | M Install(bundleFilePath2, InstallFlag::REPLACE_EXISTING, message); EXPECT_EQ(message, "Success") << "install fail!"; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcher service is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } + LauncherService launcherservice; + ApplicationInfo applicationInfo; - bool Result = launcherservice->GetApplicationInfo( + bool Result = launcherservice.GetApplicationInfo( bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, applicationInfo); EXPECT_TRUE(Result); EXPECT_EQ(applicationInfo.name, bundleName); @@ -913,14 +863,11 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetApplicationInfo_0500, Function | M Uninstall(bundleName, message); EXPECT_EQ(message, "Success") << "uninstall fail!"; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcher service is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } + LauncherService launcherservice; + ApplicationInfo appInfo; bool result = - launcherservice->GetApplicationInfo(bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo); + launcherservice.GetApplicationInfo(bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo); EXPECT_FALSE(result); GTEST_LOG_(INFO) << "END BMS_GetApplicationInfo_0500"; } @@ -936,14 +883,11 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetApplicationInfo_0600, Function | M std::string bundleName = ""; int userId = Constants::DEFAULT_USERID; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcher service is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } + LauncherService launcherservice; + ApplicationInfo appInfo; bool result = - launcherservice->GetApplicationInfo(bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo); + launcherservice.GetApplicationInfo(bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo); EXPECT_FALSE(result); GTEST_LOG_(INFO) << "END BMS_GetApplicationInfo_0600"; } @@ -964,12 +908,9 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsAbilityEnabled_0100, Function | Med AbilityInfo abilityInfo; abilityInfo.bundleName = bundleName; abilityInfo.name = abilityName; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcherservice is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->IsAbilityEnabled(abilityInfo); + LauncherService launcherservice; + + bool result = launcherservice.IsAbilityEnabled(abilityInfo); EXPECT_TRUE(result); Uninstall(bundleName, message); EXPECT_EQ(message, "Success") << "uninstall fail!"; @@ -993,12 +934,9 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsAbilityEnabled_0200, Function | Med APP_LOGE("bundle mgr proxy is nullptr."); EXPECT_EQ(bundleMgrProxy, nullptr); } - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcherservice is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->IsAbilityEnabled(abilityInfo); + LauncherService launcherservice; + + bool result = launcherservice.IsAbilityEnabled(abilityInfo); EXPECT_TRUE(result); GTEST_LOG_(INFO) << "END BMS_IsAbilityEnabled_0200"; } @@ -1015,12 +953,9 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsAbilityEnabled_0300, Function | Med AbilityInfo abilityInfo; abilityInfo.bundleName = bundleName; abilityInfo.name = abilityName; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcherservice is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->IsAbilityEnabled(abilityInfo); + LauncherService launcherservice; + + bool result = launcherservice.IsAbilityEnabled(abilityInfo); EXPECT_FALSE(result); GTEST_LOG_(INFO) << "END BMS_IsAbilityEnabled_0300"; } @@ -1049,12 +984,9 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsAbilityEnabled_0400, Function | Med } bool ret = bundleMgrProxy->SetAbilityEnabled(abilityInfo, true); EXPECT_TRUE(ret); - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcherservice is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->IsAbilityEnabled(abilityInfo); + LauncherService launcherservice; + + bool result = launcherservice.IsAbilityEnabled(abilityInfo); EXPECT_TRUE(result); Uninstall(bundleName, message); EXPECT_EQ(message, "Success") << "uninstall fail!"; @@ -1073,12 +1005,9 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsBundleEnabled_0100, Function | Medi std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcherservice is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->IsBundleEnabled(bundleName); + LauncherService launcherservice; + + bool result = launcherservice.IsBundleEnabled(bundleName); EXPECT_TRUE(result); Uninstall(bundleName, message); EXPECT_EQ(message, "Success") << "uninstall fail!"; @@ -1098,15 +1027,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsBundleEnabled_0200, Function | Medi std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; - std::shared_ptr launcherservice = std::make_shared(); + LauncherService launcherservice; sptr bundleMgrProxy = GetBundleMgrProxy(); - if (!launcherservice) { - APP_LOGE("launcherservice is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } + bool ret = bundleMgrProxy->SetApplicationEnabled(bundleName, false); EXPECT_TRUE(ret); - bool result = launcherservice->IsBundleEnabled(bundleName); + bool result = launcherservice.IsBundleEnabled(bundleName); EXPECT_FALSE(result); Uninstall(bundleName, message); EXPECT_EQ(message, "Success") << "uninstall fail!"; @@ -1121,12 +1047,9 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsBundleEnabled_0300, Function | Medi { GTEST_LOG_(INFO) << "START BMS_IsBundleEnabled_0300"; std::string bundleName = SYSTEM_BASE_BUNDLE_NAME + "1"; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcherservice is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->IsBundleEnabled(bundleName); + LauncherService launcherservice; + + bool result = launcherservice.IsBundleEnabled(bundleName); EXPECT_TRUE(result); GTEST_LOG_(INFO) << "END BMS_IsBundleEnabled_0300"; } @@ -1139,12 +1062,9 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsBundleEnabled_0400, Function | Medi { GTEST_LOG_(INFO) << "START BMS_IsBundleEnabled_0400"; std::string bundleName = ""; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcherservice is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->IsBundleEnabled(bundleName); + LauncherService launcherservice; + + bool result = launcherservice.IsBundleEnabled(bundleName); EXPECT_FALSE(result); GTEST_LOG_(INFO) << "END BMS_IsBundleEnabled_0400"; } @@ -1164,12 +1084,9 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetShortcutInfos_0100, Function | Med Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; std::vector launcherShortcutInfo; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcher service is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->GetShortcutInfos(bundleName, launcherShortcutInfo); + LauncherService launcherservice; + + bool result = launcherservice.GetShortcutInfos(bundleName, launcherShortcutInfo); EXPECT_TRUE(result) << "Get shortcut info failed"; EXPECT_FALSE(launcherShortcutInfo.empty()) << "Launcher shortcut infos is empty"; EXPECT_EQ(launcherShortcutInfo[0].bundleName, bundleName); @@ -1200,15 +1117,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetShortcutInfos_0200, Function | Med Install(bundleFilePath2, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; std::vector launcherShortcutInfo; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcher service is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->GetShortcutInfos(bundleName, launcherShortcutInfo); + LauncherService launcherservice; + + bool result = launcherservice.GetShortcutInfos(bundleName, launcherShortcutInfo); EXPECT_TRUE(result) << "Get shortcut info failed"; EXPECT_FALSE(launcherShortcutInfo.empty()) << "Launcher shortcut infos is empty"; - EXPECT_GE(launcherShortcutInfo.size(), 1); + EXPECT_EQ(launcherShortcutInfo.size(), LIST_SIZE); EXPECT_EQ(launcherShortcutInfo[0].shortcutid, shortcutId1); EXPECT_EQ(launcherShortcutInfo[1].shortcutid, shortcutId2); Uninstall(bundleName, message); @@ -1230,12 +1144,9 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetShortcutInfos_0300, Function | Med Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; std::vector launcherShortcutInfo; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcher service is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->GetShortcutInfos(bundleName, launcherShortcutInfo); + LauncherService launcherservice; + + bool result = launcherservice.GetShortcutInfos(bundleName, launcherShortcutInfo); EXPECT_FALSE(result); EXPECT_TRUE(launcherShortcutInfo.empty()); Uninstall(bundleName, message); @@ -1252,12 +1163,9 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetShortcutInfos_0400, Function | Med GTEST_LOG_(INFO) << "START BMS_GetShortcutInfos_0400"; std::string bundleName = ""; std::vector launcherShortcutInfo; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcher service is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->GetShortcutInfos(bundleName, launcherShortcutInfo); + LauncherService launcherservice; + + bool result = launcherservice.GetShortcutInfos(bundleName, launcherShortcutInfo); EXPECT_FALSE(result); GTEST_LOG_(INFO) << "END BMS_GetShortcutInfos_0400"; } @@ -1283,12 +1191,9 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetShortcutInfos_0500, Function | Med EXPECT_EQ(message, "Success") << "install fail!"; std::vector launcherShortcutInfo; - std::shared_ptr launcherservice = std::make_shared(); - if (!launcherservice) { - APP_LOGE("launcher service is nullptr."); - EXPECT_EQ(launcherservice, nullptr); - } - bool result = launcherservice->GetShortcutInfos(bundleName, launcherShortcutInfo); + LauncherService launcherservice; + + bool result = launcherservice.GetShortcutInfos(bundleName, launcherShortcutInfo); EXPECT_TRUE(result); EXPECT_FALSE(launcherShortcutInfo.empty()) << "Launcher shortcut info is empty"; EXPECT_EQ(launcherShortcutInfo[0].bundleName, bundleName); diff --git a/test/systemtest/common/bms/bms_search_system_test/bms_search_system_test.cpp b/test/systemtest/common/bms/bms_search_system_test/bms_search_system_test.cpp index 3ed774b21716b8412dfd1f73cf86bcd2ccd00fc9..27164f0e94280cb8c43eeed9844fe804b8c508a9 100644 --- a/test/systemtest/common/bms/bms_search_system_test/bms_search_system_test.cpp +++ b/test/systemtest/common/bms/bms_search_system_test/bms_search_system_test.cpp @@ -45,7 +45,6 @@ const std::string OPERATION_SUCCESS = "Success"; namespace OHOS { namespace AppExecFwk { - class BundleStatusCallbackImpl : public BundleStatusCallbackHost { public: BundleStatusCallbackImpl(); @@ -1427,6 +1426,5 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_3900, Function | MediumTest | Level1) EXPECT_NE(name2Exist, 0) << "the test file2 exists."; std::cout << "END BMS_SEARCH_3900" << std::endl; } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/bms/bms_uninstall_system_test/bms_uninstall_system_test.cpp b/test/systemtest/common/bms/bms_uninstall_system_test/bms_uninstall_system_test.cpp index aff2267f599c8beb95e1dfe7c1939405a717bbc3..e74303550a0acab6a4e9293422f92ed4f4d2bdca 100755 --- a/test/systemtest/common/bms/bms_uninstall_system_test/bms_uninstall_system_test.cpp +++ b/test/systemtest/common/bms/bms_uninstall_system_test/bms_uninstall_system_test.cpp @@ -47,7 +47,6 @@ const int32_t MAX_BUNDLE_NAME = 6; namespace OHOS { namespace AppExecFwk { - class StatusReceiverImpl : public StatusReceiverHost { public: StatusReceiverImpl(); @@ -1369,6 +1368,5 @@ HWTEST_F(BmsUninstallSystemTest, BMS_DFX_0500, Function | MediumTest | Level2) EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!"; std::cout << "END BMS_DFX_0500" << std::endl; } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/tools/BUILD.gn b/tools/BUILD.gn index 399d30752ca3db683bc2aa6bd62cadf946c4cf5e..b47fd7e86ec0bc3b9df3db730f710bf587879347 100644 --- a/tools/BUILD.gn +++ b/tools/BUILD.gn @@ -12,5 +12,8 @@ # limitations under the License. group("tools_target") { - deps = [ "bm:tools_bm" ] + deps = [ + "bm:tools_bm", + "fm:tools_fm", + ] } diff --git a/tools/fm/BUILD.gn b/tools/fm/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..088c82dd6bcf7707064b929f90cf4ec75bb49d55 --- /dev/null +++ b/tools/fm/BUILD.gn @@ -0,0 +1,77 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +config("tools_fm_config") { + include_dirs = [ + "${aafwk_path}/interfaces/innerkits/want/include", + "${aafwk_path}/interfaces/innerkits/base/include", + "${aafwk_path}/services/common/include", + "${aafwk_path}/tools/aa/include", + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "include", + ] +} + +ohos_source_set("tools_fm_source_set") { + sources = [ + "${aafwk_path}/tools/aa/src/shell_command.cpp", + "src/fms_command.cpp", + "src/main.cpp", + ] + + defines = [ + "APP_LOG_TAG = \"FmsTool\"", + "LOG_DOMAIN = 0xD001152", + ] + + public_configs = [ ":tools_fm_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + deps = [ + "${aafwk_path}/interfaces/innerkits/want:want", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +ohos_executable("fm") { + deps = [ ":tools_fm_source_set" ] + + install_enable = true + + subsystem_name = "appexecfwk" + part_name = "appexecfwk_standard" +} + +group("tools_fm") { + deps = [ ":fm" ] +} diff --git a/tools/fm/include/fms_command.h b/tools/fm/include/fms_command.h new file mode 100755 index 0000000000000000000000000000000000000000..86414c03d098a98779ab30517ea1dd070071caff --- /dev/null +++ b/tools/fm/include/fms_command.h @@ -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. + */ + +#ifndef FOUNDATION_APPEXECFWK_STANDARD_TOOLS_FM_INCLUDE_FMS_COMMAND_H +#define FOUNDATION_APPEXECFWK_STANDARD_TOOLS_FM_INCLUDE_FMS_COMMAND_H + +#include "shell_command.h" +#include "form_mgr_interface.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const std::string FM_TOOL_NAME = "fm"; + +const std::string FM_HELP_MSG = "usage: fm \n" + "These are common fm commands list:\n" + " help list available commands\n" + " query query form info with options\n"; + +const std::string HELP_MSG_QUERY = + "usage: fm query \n" + "options list:\n" + " -h, --help list available commands\n" + " -s, --storage query form storage info\n" + " -n query form info by a bundle name\n" + " -i query form info by a form id\n"; + + +const std::string HELP_MSG_NO_BUNDLE_PATH_OPTION = + "error: you must specify a form id with '-1' or '--formid'."; + +const std::string HELP_MSG_NO_BUNDLE_NAME_OPTION = + "error: you must specify a bundle name with '-n' or '--name'."; + +const std::string STRING_QUERY_FORM_INFO_OK = "query form info successfully."; +const std::string STRING_QUERY_FORM_INFO_NG = "error: failed to query form info."; +} // namespace + +class FormMgrShellCommand : public OHOS::AAFwk::ShellCommand { +public: + FormMgrShellCommand(int argc, char *argv[]); + ~FormMgrShellCommand() override + {} + +private: + /** + * @brief Create command map. + */ + ErrCode CreateCommandMap() override; + /** + * @brief Create message map. + */ + ErrCode CreateMessageMap() override; + /** + * @brief init. + */ + ErrCode init() override; + /** + * @brief Run help command. + */ + ErrCode RunAsHelpCommand(); + /** + * @brief Run query form info command. + */ + ErrCode RunAsQueryCommand(); + // ErrCode RunAsDumpCommand(); + + /** + * @brief Query all of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t QueryStorageFormInfos(); + /** + * @brief Query form infos by bundleName. + * @param bundleName BundleName. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t QueryFormInfoByBundleName(const std::string& bundleName); + /** + * @brief Query form infos by form id. + * @param formId The id of the form. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t QueryFormInfoByFormId(const std::int64_t formId); + /** + * @brief Handle command args. + * @param optopt Command optopt. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleUnknownOption(const char optopt); + /** + * @brief Handle command args. + * @param option Command option. + * @param bundleName BundleName. + * @param formId The id of the form. + * @param cmdFlag Command Flag. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleNormalOption(const int option, std::string &bundleName, int64_t &formId, int32_t &cmdFlag); + + /** + * @brief Execute query form info command. + * @param bundleName BundleName. + * @param formId The id of the form. + * @param cmdFlag Command Flag. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t ExecuteQuery(const std::string &bundleName, const int64_t formId, const int32_t cmdFlag); + + /** + * @brief Connect form manager service. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t ConnectFms(); + + bool WriteInterfaceToken(MessageParcel &data); + int GetStringInfo(IFormMgr::Message code, MessageParcel &data, std::string &stringInfo); + int SendTransactCmd(IFormMgr::Message code, MessageParcel &data, MessageParcel &reply); +private: + sptr remoteObject_; +}; + +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_STANDARD_TOOLS_FM_INCLUDE_FMS_COMMAND_H \ No newline at end of file diff --git a/tools/fm/src/fms_command.cpp b/tools/fm/src/fms_command.cpp new file mode 100755 index 0000000000000000000000000000000000000000..462165df9a8f3367e9b8f15e57fb03010cec9ca0 --- /dev/null +++ b/tools/fm/src/fms_command.cpp @@ -0,0 +1,499 @@ +/* + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "fms_command.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "string_ex.h" +#include "system_ability_definition.h" + +using namespace OHOS::AAFwk; + +namespace OHOS { +namespace AppExecFwk { +namespace { +const int COMMAND_QUERY_INVALID = -1; +const int COMMAND_QUERY_STORAGE = 0; +const int COMMAND_QUERY_NAME = 1; +const int COMMAND_QUERY_ID = 2; + +// const std::string BUNDLE_NAME_EMPTY = ""; + +const std::string SHORT_OPTIONS = "hsn:i:"; +const struct option LONG_OPTIONS[] = { + {"help", no_argument, nullptr, 'h'}, + {"storage", no_argument, nullptr, 's'}, + {"bundle-name", required_argument, nullptr, 'n'}, + {"form-id", required_argument, nullptr, 'i'}, + {0, 0, 0, 0}, +}; +} // namespace + +FormMgrShellCommand::FormMgrShellCommand(int argc, char *argv[]) : ShellCommand(argc, argv, FM_TOOL_NAME) +{ +} +ErrCode FormMgrShellCommand::init() +{ + return ERR_OK; +} +/** + * @brief Create command map. + */ +ErrCode FormMgrShellCommand::CreateCommandMap() +{ + commandMap_ = { + {"help", std::bind(&FormMgrShellCommand::RunAsHelpCommand, this)}, + {"query", std::bind(&FormMgrShellCommand::RunAsQueryCommand, this)}, + // {"dump", std::bind(&FormMgrShellCommand::RunAsDumpCommand, this)}, + }; + + return OHOS::ERR_OK; +} +/** + * @brief Create message map. + */ +ErrCode FormMgrShellCommand::CreateMessageMap() +{ + messageMap_ = { + // error + message + { + ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR, + "error: fm query internal error.", + }, + { + ERR_APPEXECFWK_FORM_INVALID_PARAM, + "error: fm query param error.", + }, + { + ERR_APPEXECFWK_FORM_PERMISSION_DENY, + "error: fm query permission denied.", + }, + { + ERR_APPEXECFWK_FORM_NOT_EXIST_ID, + "warning: fm query no form info.", + }, + { + ERR_APPEXECFWK_FORM_COMMON_CODE, + "error: unknown.", + }, + }; + + return OHOS::ERR_OK; +} +/** + * @brief Run help command. + */ +ErrCode FormMgrShellCommand::RunAsHelpCommand() +{ + resultReceiver_.append(FM_HELP_MSG); + + return OHOS::ERR_OK; +} +/** + * @brief Run query form info command. + */ +ErrCode FormMgrShellCommand::RunAsQueryCommand() +{ + int32_t result = OHOS::ERR_OK; + int32_t cmdFlag = COMMAND_QUERY_INVALID; + int option = -1; + int counter = 0; + std::string bundleName = ""; + int64_t formId = 0; + + while (true) { + counter++; + option = getopt_long(argc_, argv_, SHORT_OPTIONS.c_str(), LONG_OPTIONS, nullptr); + APP_LOGI("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind); + if (optind < 0 || optind > argc_) { + return OHOS::ERR_INVALID_VALUE; + } + + for (int i = 0; i < argc_; i++) { + APP_LOGI("argv_[%{public}d]: %{public}s", i, argv_[i]); + } + + if (option == -1) { + if (counter == 1) { + // When scanning the first argument + if (strcmp(argv_[optind], cmd_.c_str()) == 0) { + // 'fm query' with no option: fm query + // 'fm query' with a wrong argument: fm query xxx + APP_LOGE("'fm query' with no option."); + resultReceiver_.append(HELP_MSG_NO_OPTION + "\n"); + result = OHOS::ERR_INVALID_VALUE; + } + } + break; + } + + if (option == '?') { + result = HandleUnknownOption(optopt); + break; + } + + result = HandleNormalOption(option, bundleName, formId, cmdFlag); + // if(result == OHOS::ERR_OK) { + // break; + // } + } + + if (result == OHOS::ERR_OK) { + result = ExecuteQuery(bundleName, formId, cmdFlag); + } else { + resultReceiver_.append(HELP_MSG_QUERY); + } + + return result; +} +/** + * @brief Handle command args. + * @param optopt Command optopt. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrShellCommand::HandleUnknownOption(const char optopt) +{ + int32_t result = OHOS::ERR_OK; + switch (optopt) { + case 'n': + case 'i': { + // 'fm query -n' with no argument: fm query -n + // 'fm query --bundle-name' with no argument: fm query --bundle-name + // 'fm query -i' with no argument: fm query -i + // 'fm query --form-id' with no argument: fm query --form-id + APP_LOGE("'fm query' %{public}s with no argument.", argv_[optind - 1]); + resultReceiver_.append("error: option '"); + resultReceiver_.append(argv_[optind - 1]); + resultReceiver_.append("' requires a value.\n"); + result = OHOS::ERR_INVALID_VALUE; + break; + } + case 0: { + // 'fm query' with a unknown option: fm query --x + // 'fm query' with a unknown option: fm query --xxx + std::string unknownOption = ""; + std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption); + APP_LOGE("'fm query' with a unknown option: %{public}s", unknownOption.c_str()); + resultReceiver_.append(unknownOptionMsg); + result = OHOS::ERR_INVALID_VALUE; + break; + } + default: { + // 'fm query' with a unknown option: fm query -x + // 'fm query' with a unknown option: fm query -xxx + std::string unknownOption = ""; + std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption); + APP_LOGE("'fm query' with a unknown option: %{public}s", unknownOption.c_str()); + resultReceiver_.append(unknownOptionMsg); + result = OHOS::ERR_INVALID_VALUE; + break; + } + } + + return result; +} +/** + * @brief Handle command args. + * @param option Command option. + * @param bundleName BundleName. + * @param formId The id of the form. + * @param cmdFlag Command Flag. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrShellCommand::HandleNormalOption(const int option, std::string &bundleName, int64_t &formId, int32_t &cmdFlag) +{ + APP_LOGI("%{public}s start, option: %{public}d", __func__, option); + int32_t result = OHOS::ERR_OK; + switch (option) { + case 'h': { + // 'fm query -h' + // 'fm query --help' + APP_LOGI("'fm query' %{public}s", argv_[optind - 1]); + result = OHOS::ERR_INVALID_VALUE; + break; + } + case 's': { + // 'fm query -s' + // 'fm query --storage' + cmdFlag = COMMAND_QUERY_STORAGE; + break; + } + case 'n': { + // 'fm query -n ' + // 'fm query --bundle-name ' + if(optarg == nullptr) { + resultReceiver_.append("error: option "); + resultReceiver_.append("'-n'"); + resultReceiver_.append(" requires a value.\n"); + result = OHOS::ERR_INVALID_VALUE; + break; + } + cmdFlag = COMMAND_QUERY_NAME; + bundleName = optarg; + break; + } + case 'i': { + // 'fm query -i ' + // 'fm query --form-id ' + if(optarg == nullptr) { + resultReceiver_.append("error: option "); + resultReceiver_.append("'-i'"); + resultReceiver_.append(" requires a value.\n"); + result = OHOS::ERR_INVALID_VALUE; + break; + } + cmdFlag = COMMAND_QUERY_ID; + formId = std::stoll(optarg); + break; + } + default: { + result = OHOS::ERR_INVALID_VALUE; + APP_LOGI("'fm query' invalid option."); + break; + } + } + APP_LOGI("%{public}s end, result: %{public}d", __func__, result); + return result; +} +/** + * @brief Execute query form info command. + * @param bundleName BundleName. + * @param formId The id of the form. + * @param cmdFlag Command Flag. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrShellCommand::ExecuteQuery(const std::string &bundleName, const int64_t formId, const int32_t cmdFlag) +{ + APP_LOGI("%{public}s start, bundleName: %{public}s, formId:%{public}" PRId64 "", __func__, bundleName.c_str(), formId); + int32_t result = OHOS::ERR_OK; + switch (cmdFlag) { + case COMMAND_QUERY_STORAGE: { + result = QueryStorageFormInfos(); + break; + } + case COMMAND_QUERY_NAME: { + result = QueryFormInfoByBundleName(bundleName); + break; + } + case COMMAND_QUERY_ID: { + result = QueryFormInfoByFormId(formId); + break; + } + default: { + APP_LOGI("'fm query' invalid command."); + break; + } + APP_LOGI("%{public}s end, cmdFlag: %{public}d", __func__, cmdFlag); + } + + if (result == OHOS::ERR_OK) { + resultReceiver_ = STRING_QUERY_FORM_INFO_OK + "\n" + resultReceiver_; + } else if(result == OHOS::ERR_APPEXECFWK_FORM_NOT_EXIST_ID){ + resultReceiver_ = STRING_QUERY_FORM_INFO_OK + "\n"; + resultReceiver_.append(GetMessageFromCode(result)); + } else { + resultReceiver_ = STRING_QUERY_FORM_INFO_NG + "\n"; + resultReceiver_.append(GetMessageFromCode(result)); + } + + return result; +} +/** + * @brief Query all of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrShellCommand::QueryStorageFormInfos() +{ + APP_LOGI("%{public}s start", __func__); + + int errCode = ConnectFms(); + if(errCode != OHOS::ERR_OK) { + return errCode; + } + + std::string formInfos; + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int result = GetStringInfo(IFormMgr::Message::FORM_MGR_STORAGE_FORM_INFOS, data, formInfos); + if (result == ERR_OK) { + resultReceiver_= formInfos; + } else { + APP_LOGE("'fm query' failed to query form info."); + } + APP_LOGI("%{public}s end, formInfo: %{public}s", __func__, resultReceiver_.c_str()); + + return result; +} +/** + * @brief Query form infos by bundleName. + * @param bundleName BundleName. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrShellCommand::QueryFormInfoByBundleName(const std::string& bundleName) +{ + APP_LOGI("%{public}s start, bundleName: %{public}s", __func__, bundleName.c_str()); + + int errCode = ConnectFms(); + if(errCode != OHOS::ERR_OK) { + return errCode; + } + + std::string formInfos; + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteString(bundleName)) { + APP_LOGE("%{public}s, failed to write bundleName", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int result = GetStringInfo(IFormMgr::Message::FORM_MGR_FORM_INFOS_BY_NAME, data, formInfos); + if (result == ERR_OK) { + APP_LOGI("%{public}s, DumpFormInfoByBundleName success", __func__); + resultReceiver_ = formInfos; + } else { + APP_LOGE("'fm query' failed to query form info."); + } + APP_LOGI("%{public}s end, formInfo: %{public}s", __func__, resultReceiver_.c_str()); + + return result; +} +/** + * @brief Query form infos by form id. + * @param formId The id of the form. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrShellCommand::QueryFormInfoByFormId(const std::int64_t formId) +{ + APP_LOGI("%{public}s start, formId: %{public}" PRId64 "", __func__, formId); + + int errCode = ConnectFms(); + if(errCode != OHOS::ERR_OK) { + return errCode; + } + + std::string formInfo; + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int result = GetStringInfo(IFormMgr::Message::FORM_MGR_FORM_INFOS_BY_ID, data, formInfo); + if (result == ERR_OK) { + resultReceiver_ = formInfo; + } else if(result == OHOS::ERR_APPEXECFWK_FORM_NOT_EXIST_ID) { + APP_LOGW("'fm query' no form info."); + } else { + APP_LOGE("'fm query' failed to query form info."); + } + APP_LOGI("%{public}s end, formInfo: %{public}s", __func__, resultReceiver_.c_str()); + + return result; +} +bool FormMgrShellCommand::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(IFormMgr::GetDescriptor())) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return false; + } + return true; +} +int FormMgrShellCommand::GetStringInfo(IFormMgr::Message code, MessageParcel &data, std::string &stringInfo) +{ + int error; + MessageParcel reply; + error = SendTransactCmd(code, data, reply); + if (error != ERR_OK) { + return error; + } + + error = reply.ReadInt32(); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to read reply result: %{public}d", __func__, error); + return error; + } + std::vector stringInfoList; + if (!reply.ReadStringVector(&stringInfoList)) { + APP_LOGE("%{public}s, failed to read string vector from reply", __func__); + return false; + } + if (stringInfoList.empty()) { + APP_LOGI("%{public}s, No string info", __func__); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + for (auto &info : stringInfoList) { + stringInfo += info; + } + APP_LOGD("%{public}s, get string info success", __func__); + return ERR_OK; +} +int FormMgrShellCommand::SendTransactCmd(IFormMgr::Message code, MessageParcel &data, MessageParcel &reply) +{ + MessageOption option(MessageOption::TF_SYNC); + + if (!remoteObject_) { + APP_LOGE("%{public}s, failed to get remote object, cmd: %{public}d", __func__, code); + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + } + int32_t result = remoteObject_->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_OK; +} +/** + * @brief Connect form manager service. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrShellCommand::ConnectFms() +{ + if(remoteObject_ != nullptr) { + return OHOS::ERR_OK; + } + sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemManager == nullptr) { + APP_LOGE("%{private}s:fail to get system ability manager", __func__); + return ERR_APPEXECFWK_FORM_GET_FMS_FAILED; + } + remoteObject_ = systemManager->GetSystemAbility(FORM_MGR_SERVICE_ID); + if (remoteObject_ == nullptr) { + APP_LOGE("%{private}s:fail to connect FormMgrService", __func__); + return ERR_APPEXECFWK_FORM_GET_FMS_FAILED; + } + + APP_LOGI("%{public}s end, get fms proxy success", __func__); + return OHOS::ERR_OK; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/tools/fm/src/main.cpp b/tools/fm/src/main.cpp new file mode 100755 index 0000000000000000000000000000000000000000..7b2115dbeb15dcef0e3e4d24350e40a4c1086b44 --- /dev/null +++ b/tools/fm/src/main.cpp @@ -0,0 +1,23 @@ +/* + * 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 "fms_command.h" + +int main(int argc, char *argv[]) +{ + OHOS::AppExecFwk::FormMgrShellCommand cmd(argc, argv); + std::cout << cmd.ExecCommand(); + return 0; +}