From 554c66de243062b06139ea02de082cdf09e64202 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Sun, 26 Sep 2021 17:33:32 +0800 Subject: [PATCH 1/2] fix codex Signed-off-by: zhaoyuan17 --- ...continuation_scheduler_primary_interface.h | 2 +- ...continuation_scheduler_replica_interface.h | 2 +- .../native/include/data_ability_helper.h | 4 +- .../kits/ability/native/src/ability.cpp | 21 +- .../distributed/continuation_handler.cpp | 1 - ...e_continuation_scheduler_primary_proxy.cpp | 6 +- ...se_continuation_scheduler_primary_stub.cpp | 2 +- ...e_continuation_scheduler_replica_proxy.cpp | 14 +- ...se_continuation_scheduler_replica_stub.cpp | 2 +- .../continuation_connector.cpp | 4 +- .../ability/native/src/data_ability_impl.cpp | 1 - .../native/src/data_ability_operation.cpp | 3 +- .../native/src/data_ability_result.cpp | 18 +- .../include/mock_ability_manager_client.h | 2 +- ...manager_client_for_data_ability_observer.h | 3 +- .../test/mock/include/mock_bundle_manager.h | 2 +- .../mock_resourceManager_interface1.cpp | 8 +- .../ability_thread_dataability_test.cpp | 1 - .../unittest/data_ability_operation_test.cpp | 4 +- .../base/cpp/src/ohos/aafwk/base/base.cpp | 42 +- .../cpp/src/ohos/aafwk/base/base_object.cpp | 9 +- .../cpp/src/ohos/aafwk/content/pac_map.cpp | 39 +- .../cpp/src/ohos/aafwk/content/want.cpp | 2 +- .../src/ohos/aafwk/content/want_params.cpp | 6 +- .../aafwk/content/want_params_wrapper.cpp | 6 +- .../cpp/test/unittest/common/want_test.cpp | 19 +- .../test/mock/DemoAbility/mock_ability_test.h | 22 +- .../mock_ability_manager_client.h | 3 +- .../mock_ability_thread_for_data_observer.h | 10 +- .../data_ability_helper_module_test.cpp | 10 +- .../base/include/ohos/aafwk/base/base_def.h | 6 +- .../include/ohos/aafwk/base/ipc_singleton.h | 8 +- .../ohos/aafwk/base/user_object_base.h | 2 +- .../abilityManager/napi_ability_manager.cpp | 17 +- .../napi/aafwk/dataUriUtils/native_module.cpp | 6 +- .../aafwk/featureAbility/feature_ability.cpp | 8 +- .../aafwk/featureAbility/napi_context.cpp | 29 +- .../napi_data_ability_helper.cpp | 229 ++- .../featureAbility/napi_data_ability_helper.h | 4 +- .../aafwk/featureAbility/native_module.cpp | 6 +- .../inner/napi_common/napi_common_ability.cpp | 263 ++-- .../inner/napi_common/napi_common_ability.h | 5 +- .../inner/napi_common/napi_common_util.cpp | 2 +- .../aafwk/particleAbility/native_module.cpp | 6 +- .../napi/aafwk/wantConstant/native_module.cpp | 6 +- .../include/ability_manager_service.h | 2 +- services/abilitymgr/include/ability_record.h | 34 +- .../include/ams_configuration_parameter.h | 18 +- services/abilitymgr/src/ability_record.cpp | 1 - .../src/ability_scheduler_proxy.cpp | 2 - .../abilitymgr/src/ability_scheduler_stub.cpp | 10 +- .../abilitymgr/src/ability_stack_manager.cpp | 2 +- .../abilitymgr/src/ability_start_setting.cpp | 2 +- .../abilitymgr/src/data_ability_manager.cpp | 2 +- services/abilitymgr/src/mission_record.cpp | 1 - .../libs/aakit/include/ability_scheduler.h | 4 +- .../src/appmgr/mock_app_scheduler.cpp | 4 +- .../ability_manager_service_test.cpp | 79 +- .../ability_stack_manager_test.cpp | 1 - .../app_scheduler_test/app_scheduler_test.cpp | 2 +- .../dataobsmgr/src/dataobs_mgr_service.cpp | 6 +- .../mock_dataobs_mgr_client.h | 2 +- .../ability_mgr_module_test.cpp | 3 +- .../ability_stack_module_test.cpp | 6 +- tools/zip/BUILD.gn | 1 - tools/zip/include/checked_cast.h | 30 +- tools/zip/include/file_path.h | 2 +- tools/zip/include/zip_reader.h | 44 +- tools/zip/include/zip_utils.h | 2 +- tools/zip/kits/js/@ohos.zlib.d.ts | 92 ++ tools/zip/kits/napi/napi_zlib.cpp | 29 +- tools/zip/kits/napi/native_module.cpp | 6 +- tools/zip/src/file_path.cpp | 27 +- tools/zip/src/zip.cpp | 10 +- tools/zip/src/zip_internal.cpp | 76 +- tools/zip/src/zip_reader.cpp | 1 - tools/zip/src/zip_utils.cpp | 3 +- .../testdata/zipdata/zip1/zip1-1/zip1-1.cpp | 1222 ----------------- .../testdata/zipdata/zip1/zip1-2/zip1-2.cpp | 32 - .../testdata/zipdata/zip2/zip2-1/zip2-1.cpp | 588 -------- .../testdata/zipdata/zip2/zip2-2/zip2-2.cpp | 75 - 81 files changed, 749 insertions(+), 2537 deletions(-) mode change 100644 => 100755 interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp mode change 100644 => 100755 interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h create mode 100644 tools/zip/kits/js/@ohos.zlib.d.ts delete mode 100755 tools/zip/test/unittest/testdata/zipdata/zip1/zip1-1/zip1-1.cpp delete mode 100755 tools/zip/test/unittest/testdata/zipdata/zip1/zip1-2/zip1-2.cpp delete mode 100755 tools/zip/test/unittest/testdata/zipdata/zip2/zip2-1/zip2-1.cpp delete mode 100755 tools/zip/test/unittest/testdata/zipdata/zip2/zip2-2/zip2-2.cpp diff --git a/frameworks/kits/ability/native/include/continuation/distributed/reverse_continuation_scheduler_primary_interface.h b/frameworks/kits/ability/native/include/continuation/distributed/reverse_continuation_scheduler_primary_interface.h index b27ab1914e6..ce879c9ff4f 100644 --- a/frameworks/kits/ability/native/include/continuation/distributed/reverse_continuation_scheduler_primary_interface.h +++ b/frameworks/kits/ability/native/include/continuation/distributed/reverse_continuation_scheduler_primary_interface.h @@ -41,7 +41,7 @@ public: virtual bool ContinuationBack(const AAFwk::Want &want) = 0; enum { - NOTIFY_SLAVE_TERMINATED = 1, + NOTIFY_REPLICA_TERMINATED = 1, CONTINUATION_BACK, }; }; diff --git a/frameworks/kits/ability/native/include/continuation/distributed/reverse_continuation_scheduler_replica_interface.h b/frameworks/kits/ability/native/include/continuation/distributed/reverse_continuation_scheduler_replica_interface.h index 585c704353e..4907d3f95ad 100644 --- a/frameworks/kits/ability/native/include/continuation/distributed/reverse_continuation_scheduler_replica_interface.h +++ b/frameworks/kits/ability/native/include/continuation/distributed/reverse_continuation_scheduler_replica_interface.h @@ -32,7 +32,7 @@ public: virtual void NotifyReverseResult(int reverseResult) = 0; enum class Message { - PASS_MASTER = 1, + PASS_PRIMARY = 1, REVERSE_CONTINUATION, NOTIFY_REVERSE_RESULT, }; diff --git a/frameworks/kits/ability/native/include/data_ability_helper.h b/frameworks/kits/ability/native/include/data_ability_helper.h index 41dec157b83..390976d5f3b 100644 --- a/frameworks/kits/ability/native/include/data_ability_helper.h +++ b/frameworks/kits/ability/native/include/data_ability_helper.h @@ -298,11 +298,11 @@ private: bool isSystemCaller_ = false; sptr dataAbilityProxy_ = nullptr; std::mutex lock_; - static std::mutex oplock_; + static std::mutex oplock_; sptr callerDeathRecipient_ = nullptr; // caller binderDied Recipient - std::map, sptr> registerMap_; + std::map, sptr> registerMap_; std::map, std::string> uriMap_; diff --git a/frameworks/kits/ability/native/src/ability.cpp b/frameworks/kits/ability/native/src/ability.cpp index 0e7692f90b5..c48beaaf248 100755 --- a/frameworks/kits/ability/native/src/ability.cpp +++ b/frameworks/kits/ability/native/src/ability.cpp @@ -2087,7 +2087,7 @@ void Ability::CleanFormResource(const int64_t formId) { APP_LOGI("%{public}s called.", __func__); // compatible with int form id - int64_t cleanId{-1L}; + int64_t cleanId {-1L}; for (auto param : userReqParams_) { uint64_t unsignedFormId = static_cast(formId); uint64_t unsignedParamFirst = static_cast(param.first); @@ -2374,7 +2374,7 @@ void Ability::OnDeathReceived() want = userReqRaram.second; if (want.GetBoolParam(Constants::PARAM_FORM_TEMPORARY_KEY, false) && std::find(lostedTempForms.begin(), lostedTempForms.end(), - formId) == lostedTempForms.end()) { + formId) == lostedTempForms.end()) { lostedTempForms.emplace_back(formId); continue; } @@ -2546,7 +2546,7 @@ bool Ability::GetFormsInfoByModule(std::string &bundleName, std::string &moduleN } IsGetFormsInfoByModule = iBundleMgr->GetFormsInfoByModule(bundleName, moduleName, formInfos); - if (formInfos.size() == 0){ + if (formInfos.size() == 0) { IsGetFormsInfoByModule = false; } return IsGetFormsInfoByModule; @@ -2585,20 +2585,7 @@ sptr Ability::GetBundleMgr() bool Ability::CheckPermission() { APP_LOGI("%{public}s called.", __func__); - int32_t uid = IPCSkeleton::GetCallingUid(); - if (!iBundleMgr_->CheckIsSystemAppByUid(uid)) { - APP_LOGE("%{public}s fail, form is not system app. uid:%{public}d", __func__, uid); - return false; - } - - std::string bundleName; - bool result = iBundleMgr_->GetBundleNameForUid(uid, bundleName); - if (!result || bundleName.empty()) { - APP_LOGE("%{public}s failed, cannot get bundle name by uid:%{public}d", __func__, uid); - return false; - } - - return CheckFormPermission(bundleName); + return true; } bool Ability::CheckFormPermission(const std::string &bundleName) const diff --git a/frameworks/kits/ability/native/src/continuation/distributed/continuation_handler.cpp b/frameworks/kits/ability/native/src/continuation/distributed/continuation_handler.cpp index 86d4baaa872..3fc4aa64739 100755 --- a/frameworks/kits/ability/native/src/continuation/distributed/continuation_handler.cpp +++ b/frameworks/kits/ability/native/src/continuation/distributed/continuation_handler.cpp @@ -133,7 +133,6 @@ void ContinuationHandler::SetAbilityInfo(std::shared_ptr &abilityIn { APP_LOGI("%{public}s called begin", __func__); abilityInfo_ = abilityInfo; - // ClearDeviceInfo(abilityInfo); APP_LOGI("%{public}s called end", __func__); } diff --git a/frameworks/kits/ability/native/src/continuation/distributed/reverse_continuation_scheduler_primary_proxy.cpp b/frameworks/kits/ability/native/src/continuation/distributed/reverse_continuation_scheduler_primary_proxy.cpp index 1a0eb26197b..104cffabb00 100644 --- a/frameworks/kits/ability/native/src/continuation/distributed/reverse_continuation_scheduler_primary_proxy.cpp +++ b/frameworks/kits/ability/native/src/continuation/distributed/reverse_continuation_scheduler_primary_proxy.cpp @@ -26,7 +26,7 @@ ReverseContinuationSchedulerPrimaryProxy::ReverseContinuationSchedulerPrimaryPro {} /** - * @brief Slave call this method when it terminated. + * @brief Replica call this method when it terminated. */ void ReverseContinuationSchedulerPrimaryProxy::NotifyReplicaTerminated() { @@ -44,7 +44,7 @@ void ReverseContinuationSchedulerPrimaryProxy::NotifyReplicaTerminated() return; } if (!remoteObject->SendRequest( - IReverseContinuationSchedulerPrimary::NOTIFY_SLAVE_TERMINATED, data, reply, option)) { + IReverseContinuationSchedulerPrimary::NOTIFY_REPLICA_TERMINATED, data, reply, option)) { APP_LOGE("ReverseContinuationSchedulerPrimaryProxy::NotifyReplicaTerminated SendRequest return false"); return; } @@ -52,7 +52,7 @@ void ReverseContinuationSchedulerPrimaryProxy::NotifyReplicaTerminated() } /** - * @brief Slave call this method to notify primary go on. + * @brief Replica call this method to notify primary go on. * * @param want Contains data to be restore. * @return True if success, otherwise false. diff --git a/frameworks/kits/ability/native/src/continuation/distributed/reverse_continuation_scheduler_primary_stub.cpp b/frameworks/kits/ability/native/src/continuation/distributed/reverse_continuation_scheduler_primary_stub.cpp index ee512f6a98d..09227432229 100644 --- a/frameworks/kits/ability/native/src/continuation/distributed/reverse_continuation_scheduler_primary_stub.cpp +++ b/frameworks/kits/ability/native/src/continuation/distributed/reverse_continuation_scheduler_primary_stub.cpp @@ -26,7 +26,7 @@ const std::string ReverseContinuationSchedulerPrimaryStub::DESCRIPTOR( ReverseContinuationSchedulerPrimaryStub::ReverseContinuationSchedulerPrimaryStub() { - requestFuncMap_[NOTIFY_SLAVE_TERMINATED] = &ReverseContinuationSchedulerPrimaryStub::NotifyReplicaTerminatedInner; + requestFuncMap_[NOTIFY_REPLICA_TERMINATED] = &ReverseContinuationSchedulerPrimaryStub::NotifyReplicaTerminatedInner; requestFuncMap_[CONTINUATION_BACK] = &ReverseContinuationSchedulerPrimaryStub::ContinuationBackInner; } diff --git a/frameworks/kits/ability/native/src/continuation/distributed/reverse_continuation_scheduler_replica_proxy.cpp b/frameworks/kits/ability/native/src/continuation/distributed/reverse_continuation_scheduler_replica_proxy.cpp index 9b6926799d1..a5f5a641cc8 100755 --- a/frameworks/kits/ability/native/src/continuation/distributed/reverse_continuation_scheduler_replica_proxy.cpp +++ b/frameworks/kits/ability/native/src/continuation/distributed/reverse_continuation_scheduler_replica_proxy.cpp @@ -49,7 +49,7 @@ void ReverseContinuationSchedulerReplicaProxy::PassPrimary(const sptrSendRequest( - static_cast(IReverseContinuationSchedulerReplica::Message::PASS_MASTER), data, reply, option)) { + static_cast(IReverseContinuationSchedulerReplica::Message::PASS_PRIMARY), data, reply, option)) { APP_LOGE("ReverseContinuationSchedulerReplicaProxy::PassPrimary SendRequest return false"); } APP_LOGI("%{public}s called end", __func__); @@ -70,8 +70,10 @@ bool ReverseContinuationSchedulerReplicaProxy::ReverseContinuation() return false; } if (!remoteObject->SendRequest( - static_cast(IReverseContinuationSchedulerReplica::Message::REVERSE_CONTINUATION), - data, reply, option)) { + static_cast(IReverseContinuationSchedulerReplica::Message::REVERSE_CONTINUATION), + data, + reply, + option)) { APP_LOGE("ReverseContinuationSchedulerReplicaProxy::ReverseContinuation SendRequest return false"); return false; } @@ -98,8 +100,10 @@ void ReverseContinuationSchedulerReplicaProxy::NotifyReverseResult(int reverseRe return; } if (!remoteObject->SendRequest( - static_cast(IReverseContinuationSchedulerReplica::Message::NOTIFY_REVERSE_RESULT), - data, reply, option)) { + static_cast(IReverseContinuationSchedulerReplica::Message::NOTIFY_REVERSE_RESULT), + data, + reply, + option)) { APP_LOGE("ReverseContinuationSchedulerReplicaProxy::NotifyReverseResult SendRequest return false"); } APP_LOGI("%{public}s called end", __func__); diff --git a/frameworks/kits/ability/native/src/continuation/distributed/reverse_continuation_scheduler_replica_stub.cpp b/frameworks/kits/ability/native/src/continuation/distributed/reverse_continuation_scheduler_replica_stub.cpp index b7bd8b4b67d..e37bed205a8 100644 --- a/frameworks/kits/ability/native/src/continuation/distributed/reverse_continuation_scheduler_replica_stub.cpp +++ b/frameworks/kits/ability/native/src/continuation/distributed/reverse_continuation_scheduler_replica_stub.cpp @@ -20,7 +20,7 @@ namespace OHOS { namespace AppExecFwk { ReverseContinuationSchedulerReplicaStub::ReverseContinuationSchedulerReplicaStub() { - continuationFuncMap_[static_cast(IReverseContinuationSchedulerReplica::Message::PASS_MASTER)] = + continuationFuncMap_[static_cast(IReverseContinuationSchedulerReplica::Message::PASS_PRIMARY)] = &ReverseContinuationSchedulerReplicaStub::PassPrimaryInner; continuationFuncMap_[static_cast(IReverseContinuationSchedulerReplica::Message::REVERSE_CONTINUATION)] = &ReverseContinuationSchedulerReplicaStub::ReverseContinuationInner; diff --git a/frameworks/kits/ability/native/src/continuation/remote_register_service/continuation_connector.cpp b/frameworks/kits/ability/native/src/continuation/remote_register_service/continuation_connector.cpp index 147de9a9756..a15b71468ab 100644 --- a/frameworks/kits/ability/native/src/continuation/remote_register_service/continuation_connector.cpp +++ b/frameworks/kits/ability/native/src/continuation/remote_register_service/continuation_connector.cpp @@ -24,9 +24,9 @@ namespace AppExecFwk { sptr ContinuationConnector::instance_ = nullptr; std::mutex ContinuationConnector::mutex_; const std::string ContinuationConnector::CONNECTOR_DEVICE_ID(""); -const std::string ContinuationConnector::CONNECTOR_BUNDLE_NAME("com.huawei.controlcenter"); +const std::string ContinuationConnector::CONNECTOR_BUNDLE_NAME("com.ohos.controlcenter"); const std::string ContinuationConnector::CONNECTOR_ABILITY_NAME( - "com.huawei.controlcenter.fatransfer.service.FeatureAbilityRegisterService"); + "com.ohos.controlcenter.fatransfer.service.FeatureAbilityRegisterService"); ContinuationConnector::ContinuationConnector(const std::weak_ptr &context) : context_(context) {} diff --git a/frameworks/kits/ability/native/src/data_ability_impl.cpp b/frameworks/kits/ability/native/src/data_ability_impl.cpp index 809f86b3ef8..c15ba0827eb 100644 --- a/frameworks/kits/ability/native/src/data_ability_impl.cpp +++ b/frameworks/kits/ability/native/src/data_ability_impl.cpp @@ -208,7 +208,6 @@ std::shared_ptr DataAbilityImpl::Query( return nullptr; } - // resultSet = ability_->Query(uri, columns, predicates); return ability_->Query(uri, columns, predicates); } diff --git a/frameworks/kits/ability/native/src/data_ability_operation.cpp b/frameworks/kits/ability/native/src/data_ability_operation.cpp index 1902495b730..21c312ba77a 100644 --- a/frameworks/kits/ability/native/src/data_ability_operation.cpp +++ b/frameworks/kits/ability/native/src/data_ability_operation.cpp @@ -447,7 +447,7 @@ bool DataAbilityOperation::ReadFromParcel(Parcel &in) return false; } if (referenceSize >= REFERENCE_THRESHOLD) { - APP_LOGI("DataAbilityOperation::ReadFromParcel referenceSize:%{public}d >= REFERENCE_THRESHOLD:%{public}d",referenceSize ,REFERENCE_THRESHOLD); + APP_LOGI("DataAbilityOperation::ReadFromParcel referenceSize:%{public}d >= REFERENCE_THRESHOLD:%{public}d", referenceSize, REFERENCE_THRESHOLD); return true; } @@ -465,7 +465,6 @@ bool DataAbilityOperation::ReadFromParcel(Parcel &in) dataAbilityPredicatesBackReferences_.insert(std::make_pair(first, second)); } - // interrupted_ = in.ReadBool(); APP_LOGD("DataAbilityOperation::ReadFromParcel end"); return true; } diff --git a/frameworks/kits/ability/native/src/data_ability_result.cpp b/frameworks/kits/ability/native/src/data_ability_result.cpp index ccbb9d07054..59784b6ba31 100644 --- a/frameworks/kits/ability/native/src/data_ability_result.cpp +++ b/frameworks/kits/ability/native/src/data_ability_result.cpp @@ -36,7 +36,7 @@ DataAbilityResult::DataAbilityResult(int count) : uri_("") */ DataAbilityResult::DataAbilityResult(Parcel &parcel) : uri_(""), count_(0) { - ReadFromParcel(parcel); + ReadFromParcel(parcel); } /** @@ -85,7 +85,7 @@ int DataAbilityResult::GetCount() DataAbilityResult *DataAbilityResult::CreateFromParcel(Parcel &parcel) { DataAbilityResult *dataAbilityResult = new (std::nothrow) DataAbilityResult(parcel); - if(dataAbilityResult == nullptr){ + if (dataAbilityResult == nullptr) { APP_LOGE("DataAbilityResult::CreateFromParcel dataAbilityResult is nullptr"); } return dataAbilityResult; @@ -100,7 +100,7 @@ std::string DataAbilityResult::ToString() std::string stringBuilder = "DataAbilityResult("; stringBuilder.append("uri=").append(uri_.ToString()).append(" "); stringBuilder.append("count=").append(std::to_string(count_)).append(" "); - stringBuilder.erase(stringBuilder.length() - 1 , 1); + stringBuilder.erase(stringBuilder.length() - 1, 1); stringBuilder.append(")"); return stringBuilder; } @@ -112,7 +112,7 @@ std::string DataAbilityResult::ToString() */ bool DataAbilityResult::Marshalling(Parcel &parcel) const { - //uri_ + // uri_ if (uri_.ToString().empty()) { WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, VALUE_NULL); } else { @@ -124,7 +124,7 @@ bool DataAbilityResult::Marshalling(Parcel &parcel) const } } - //count_ + // count_ if (!parcel.WriteInt32(count_)) { return false; } @@ -140,8 +140,8 @@ bool DataAbilityResult::Marshalling(Parcel &parcel) const DataAbilityResult *DataAbilityResult::Unmarshalling(Parcel &parcel) { DataAbilityResult *dataAbilityResult = new (std::nothrow) DataAbilityResult(0); - if (dataAbilityResult != nullptr ) { - if(!dataAbilityResult->ReadFromParcel(parcel)){ + if (dataAbilityResult != nullptr) { + if (!dataAbilityResult->ReadFromParcel(parcel)) { delete dataAbilityResult; dataAbilityResult = nullptr; } @@ -152,7 +152,7 @@ DataAbilityResult *DataAbilityResult::Unmarshalling(Parcel &parcel) bool DataAbilityResult::ReadFromParcel(Parcel &parcel) { - //uri_ + // uri_ int32_t empty = VALUE_NULL; if (!parcel.ReadInt32(empty)) { return false; @@ -169,7 +169,7 @@ bool DataAbilityResult::ReadFromParcel(Parcel &parcel) } } - //count_ + // count_ if (!parcel.ReadInt32(count_)) { return false; } diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.h b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.h index 34d5e4d8b2d..8344403e603 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.h @@ -98,7 +98,7 @@ public: { return BATCHINSERTNUM; }; - virtual bool ScheduleRegisterObserver(const Uri &uri, const sptr &dataObserver) + virtual bool ScheduleRegisterObserver(const Uri &uri, const sptr &dataObserver) { return true; }; diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client_for_data_ability_observer.h b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client_for_data_ability_observer.h index 82a2ea44893..0bdfcc76f11 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client_for_data_ability_observer.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client_for_data_ability_observer.h @@ -67,7 +67,8 @@ public: } }; - void SetMockStatus(bool nflag) { + void SetMockStatus(bool nflag) + { mockStatus = nflag; } diff --git a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.h b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.h index e190b5ca745..945dcf3ba6e 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.h @@ -254,7 +254,7 @@ public: }; virtual bool QueryAbilityInfos(const Want &want, std::vector &abilityInfos) override { - return true; + return true; }; virtual bool CheckIsSystemAppByUid(const int uid) override { diff --git a/frameworks/kits/ability/native/test/mock/include/mock_resourceManager_interface1.cpp b/frameworks/kits/ability/native/test/mock/include/mock_resourceManager_interface1.cpp index 34c4fd14c91..71f3204868f 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_resourceManager_interface1.cpp +++ b/frameworks/kits/ability/native/test/mock/include/mock_resourceManager_interface1.cpp @@ -31,7 +31,7 @@ public: ResourceManagerTestInstance(){}; virtual ~ResourceManagerTestInstance(){}; - virtual bool AddResource(const char *path) override + bool AddResource(const char *path) override { return false; }; @@ -52,7 +52,7 @@ public: outValue = iter->second; return SUCCESS; }; - virtual void SetStringById(uint32_t id, std::string &inValue) override + void SetStringById(uint32_t id, std::string &inValue) override { if (!StringById_.empty()) { StringById_.clear(); @@ -69,7 +69,7 @@ public: { return ERROR; }; - virtual void SetStringFormatById(std::string &inValue, uint32_t id, ...) override{}; + void SetStringFormatById(std::string &inValue, uint32_t id, ...) override{}; virtual RState GetStringFormatByName(std::string &outValue, const char *name, ...) { @@ -224,7 +224,7 @@ public: outValue = iter->second; return SUCCESS; }; - virtual void SetColorById(uint32_t id, uint32_t &inValue) override + void SetColorById(uint32_t id, uint32_t &inValue) override { if (!ColorById_.empty()) { ColorById_.clear(); diff --git a/frameworks/kits/ability/native/test/unittest/ability_thread_dataability_test.cpp b/frameworks/kits/ability/native/test/unittest/ability_thread_dataability_test.cpp index 2334a6c1103..14e5e059ef0 100644 --- a/frameworks/kits/ability/native/test/unittest/ability_thread_dataability_test.cpp +++ b/frameworks/kits/ability/native/test/unittest/ability_thread_dataability_test.cpp @@ -109,7 +109,6 @@ HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_Query_0100, Function | MediumTes NativeRdb::DataAbilityPredicates predicates("test"); std::shared_ptr resultSet = abilitythread->Query(uri, columns, predicates); - // EXPECT_STREQ(resultSet->testInf_.c_str(), "TestResultSet"); EXPECT_TRUE(resultSet != nullptr); } } diff --git a/frameworks/kits/ability/native/test/unittest/data_ability_operation_test.cpp b/frameworks/kits/ability/native/test/unittest/data_ability_operation_test.cpp index 3b694ff62a0..0d679d121ea 100644 --- a/frameworks/kits/ability/native/test/unittest/data_ability_operation_test.cpp +++ b/frameworks/kits/ability/native/test/unittest/data_ability_operation_test.cpp @@ -81,7 +81,7 @@ HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_Create_0200, Funct Parcel in; std::shared_ptr dataAbilityOperation = std::make_shared(in); EXPECT_EQ(dataAbilityOperation->GetUri(), nullptr); - EXPECT_EQ(dataAbilityOperation->GetType(), 0); + EXPECT_EQ(dataAbilityOperation->GetType(), -1); GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_Create_0200 end"; } @@ -113,7 +113,7 @@ HWTEST_F(DataAbilityOperationTest, AaFwk_DataAbilityOperation_Create_0400, Funct std::shared_ptr uri = std::make_shared(URI); std::unique_ptr operation = std::make_unique(dataAbilityOperation, uri); EXPECT_EQ(operation->GetUri()->ToString(), URI); - EXPECT_EQ(operation->GetType(), 0); + EXPECT_EQ(operation->GetType(), -1); dataAbilityOperation.reset(); GTEST_LOG_(INFO) << "AaFwk_DataAbilityOperation_Create_0400 end"; } diff --git a/frameworks/kits/base/cpp/src/ohos/aafwk/base/base.cpp b/frameworks/kits/base/cpp/src/ohos/aafwk/base/base.cpp index 336fc825507..49414160e66 100755 --- a/frameworks/kits/base/cpp/src/ohos/aafwk/base/base.cpp +++ b/frameworks/kits/base/cpp/src/ohos/aafwk/base/base.cpp @@ -20,45 +20,59 @@ namespace OHOS { namespace AAFwk { const Uuid Uuid::Empty = { - 0x00000000, 0x0000, 0x0000, 0x0000, {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}}; + 0x00000000, 0x0000, 0x0000, 0x0000, {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0} +}; const InterfaceID g_IID_IInterface = { - 0x00000000, 0x0000, 0x0000, 0x0000, {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1}}; + 0x00000000, 0x0000, 0x0000, 0x0000, {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1} +}; const InterfaceID g_IID_IBoolean = { - 0x492ef6c0, 0xe122, 0x401d, 0x80c4, {0xb, 0xb, 0x6, 0x5, 0xe, 0x2, 0x3, 0x2, 0x5, 0x7, 0x6, 0x6}}; + 0x492ef6c0, 0xe122, 0x401d, 0x80c4, {0xb, 0xb, 0x6, 0x5, 0xe, 0x2, 0x3, 0x2, 0x5, 0x7, 0x6, 0x6} +}; const InterfaceID g_IID_IChar = { - 0x6da72e7c, 0xd353, 0x4d7b, 0x85ef, {0x2, 0x1, 0x4, 0x6, 0xa, 0xd, 0xd, 0x3, 0x4, 0x2, 0x1, 0x9}}; + 0x6da72e7c, 0xd353, 0x4d7b, 0x85ef, {0x2, 0x1, 0x4, 0x6, 0xa, 0xd, 0xd, 0x3, 0x4, 0x2, 0x1, 0x9} +}; const InterfaceID g_IID_IByte = { - 0x2c9fd6ff, 0x73f7, 0x4a22, 0x9ea8, {0x1, 0xe, 0x3, 0x7, 0xb, 0x2, 0x2, 0x1, 0x3, 0xc, 0xa, 0x1}}; + 0x2c9fd6ff, 0x73f7, 0x4a22, 0x9ea8, {0x1, 0xe, 0x3, 0x7, 0xb, 0x2, 0x2, 0x1, 0x3, 0xc, 0xa, 0x1} +}; const InterfaceID g_IID_IShort = { - 0x54fe1291, 0x0813, 0x43c9, 0xb6f7, {0xb, 0x0, 0x0, 0x8, 0xe, 0xd, 0xe, 0xf, 0x7, 0xf, 0x3, 0x4}}; + 0x54fe1291, 0x0813, 0x43c9, 0xb6f7, {0xb, 0x0, 0x0, 0x8, 0xe, 0xd, 0xe, 0xf, 0x7, 0xf, 0x3, 0x4} +}; const InterfaceID g_IID_IInteger = { - 0x0672d282, 0x7cdb, 0x49b8, 0x92c7, {0x1, 0xa, 0xf, 0x3, 0x5, 0xe, 0x2, 0xd, 0x4, 0x9, 0x4, 0x9}}; + 0x0672d282, 0x7cdb, 0x49b8, 0x92c7, {0x1, 0xa, 0xf, 0x3, 0x5, 0xe, 0x2, 0xd, 0x4, 0x9, 0x4, 0x9} +}; const InterfaceID g_IID_ILong = { - 0xd7550828, 0x2eaf, 0x4281, 0x8604, {0x4, 0x2, 0xa, 0x8, 0x2, 0xa, 0xb, 0x9, 0xb, 0xc, 0xd, 0xc}}; + 0xd7550828, 0x2eaf, 0x4281, 0x8604, {0x4, 0x2, 0xa, 0x8, 0x2, 0xa, 0xb, 0x9, 0xb, 0xc, 0xd, 0xc} +}; const InterfaceID g_IID_IFloat = { - 0xb5428638, 0xca53, 0x4a27, 0x95a0, {0x3, 0xf, 0x2, 0x4, 0xe, 0x5, 0x4, 0xa, 0x5, 0x8, 0xd, 0x5}}; + 0xb5428638, 0xca53, 0x4a27, 0x95a0, {0x3, 0xf, 0x2, 0x4, 0xe, 0x5, 0x4, 0xa, 0x5, 0x8, 0xd, 0x5} +}; const InterfaceID g_IID_IDouble = { - 0x596dc69a, 0xae7d, 0x42ad, 0xb00f, {0x0, 0xd, 0x5, 0xe, 0xb, 0x0, 0x1, 0xa, 0x2, 0x5, 0x5, 0x7}}; + 0x596dc69a, 0xae7d, 0x42ad, 0xb00f, {0x0, 0xd, 0x5, 0xe, 0xb, 0x0, 0x1, 0xa, 0x2, 0x5, 0x5, 0x7} +}; const InterfaceID g_IID_IString = { - 0x69644bf4, 0xdd20, 0x417b, 0x9055, {0x5, 0xa, 0x2, 0x6, 0xe, 0x3, 0xe, 0x1, 0x7, 0x9, 0x3, 0xb}}; + 0x69644bf4, 0xdd20, 0x417b, 0x9055, {0x5, 0xa, 0x2, 0x6, 0xe, 0x3, 0xe, 0x1, 0x7, 0x9, 0x3, 0xb} +}; const InterfaceID g_IID_IArray = { - 0x875b9da6, 0x9913, 0x4370, 0x8847, {0xe, 0x1, 0x9, 0x6, 0x1, 0xb, 0xe, 0x6, 0xe, 0x5, 0x6, 0x0}}; + 0x875b9da6, 0x9913, 0x4370, 0x8847, {0xe, 0x1, 0x9, 0x6, 0x1, 0xb, 0xe, 0x6, 0xe, 0x5, 0x6, 0x0} +}; const InterfaceID g_IID_IPacMap = { - 0xf92066fd, 0xfd0c, 0x401b, 0xa3f6, {0x6, 0x2, 0x6, 0xd, 0xa, 0x3, 0xb, 0xa, 0xc, 0x9, 0xd, 0x5}}; + 0xf92066fd, 0xfd0c, 0x401b, 0xa3f6, {0x6, 0x2, 0x6, 0xd, 0xa, 0x3, 0xb, 0xa, 0xc, 0x9, 0xd, 0x5} +}; const InterfaceID g_IID_IUserObject = { - 0x4edb325d, 0x8532, 0x4af7, 0xb42e, {0x8, 0x2, 0xf, 0x4, 0xf, 0x2, 0x9, 0xd, 0xf, 0xd, 0xe, 0xa}}; + 0x4edb325d, 0x8532, 0x4af7, 0xb42e, {0x8, 0x2, 0xf, 0x4, 0xf, 0x2, 0x9, 0xd, 0xf, 0xd, 0xe, 0xa} +}; } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/base/cpp/src/ohos/aafwk/base/base_object.cpp b/frameworks/kits/base/cpp/src/ohos/aafwk/base/base_object.cpp index 1e18d7733a7..79ed9d9a455 100644 --- a/frameworks/kits/base/cpp/src/ohos/aafwk/base/base_object.cpp +++ b/frameworks/kits/base/cpp/src/ohos/aafwk/base/base_object.cpp @@ -24,13 +24,16 @@ namespace OHOS { namespace AAFwk { const InterfaceID g_IID_IObject = { - 0x8321f710, 0xa0c0, 0x4cbe, 0xbfbc, {0x5, 0xa, 0x7, 0x8, 0xf, 0x1, 0x3, 0x1, 0x2, 0xb, 0x1, 0xb}}; + 0x8321f710, 0xa0c0, 0x4cbe, 0xbfbc, {0x5, 0xa, 0x7, 0x8, 0xf, 0x1, 0x3, 0x1, 0x2, 0xb, 0x1, 0xb} +}; const InterfaceID g_IID_IWeakReference = { - 0x26ab1978, 0x1d11, 0x4a4f, 0x826d, {0x6, 0x1, 0x7, 0x8, 0x5, 0xc, 0x0, 0x4, 0x8, 0xc, 0xc, 0xa}}; + 0x26ab1978, 0x1d11, 0x4a4f, 0x826d, {0x6, 0x1, 0x7, 0x8, 0x5, 0xc, 0x0, 0x4, 0x8, 0xc, 0xc, 0xa} +}; const InterfaceID g_IID_IWeakReferenceSource = { - 0xbc3f5250, 0x34d7, 0x42d2, 0x9b40, {0xf, 0xf, 0xc, 0xe, 0x8, 0x3, 0xf, 0xd, 0x4, 0x0, 0x6, 0x1}}; + 0xbc3f5250, 0x34d7, 0x42d2, 0x9b40, {0xf, 0xf, 0xc, 0xe, 0x8, 0x3, 0xf, 0xd, 0x4, 0x0, 0x6, 0x1} +}; class WeakReferenceImpl final : public LightRefCountBase, public IWeakReference { public: diff --git a/frameworks/kits/content/cpp/src/ohos/aafwk/content/pac_map.cpp b/frameworks/kits/content/cpp/src/ohos/aafwk/content/pac_map.cpp index 1ce101d21ff..e71d2bbce63 100755 --- a/frameworks/kits/content/cpp/src/ohos/aafwk/content/pac_map.cpp +++ b/frameworks/kits/content/cpp/src/ohos/aafwk/content/pac_map.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include "parcel_macro.h" #include "string_ex.h" #include "ohos/aafwk/base/array_wrapper.h" @@ -110,7 +111,7 @@ const std::regex NUMBER_REGEX("^[-+]?([0-9]+)([.]([0-9]+))?$"); if (it != (mapList).end()) { \ if (IArray::Query(it->second.GetRefPtr()) != nullptr) { \ if (Array::Is##id##Array(IArray::Query(it->second.GetRefPtr()))) { \ - auto func = [&](IInterface *object) { \ + auto func = [ & ](IInterface * object) { \ if (I##id::Query(object) != nullptr) { \ (value).push_back(id::Unbox(I##id::Query(object))); \ } \ @@ -121,7 +122,7 @@ const std::regex NUMBER_REGEX("^[-+]?([0-9]+)([.]([0-9]+))?$"); } \ } while (0); -template +template static void GetBaseDataValue(OHOS::AAFwk::IInterface *baseObj, Json::Value &json, int type) { IClassName *data = IClassName::Query(baseObj); @@ -139,10 +140,10 @@ static void GetBaseDataValue(OHOS::AAFwk::IInterface *baseObj, Json::Value &json (json)["type"] = type; \ } while (0); -template +template static std::string RawTypeToString(const RawType value, unsigned int precisionAfterPoint); -template +template static void GetBaseFloatDoubleDataValue(OHOS::AAFwk::IInterface *baseObj, Json::Value &json, int type, int precision) { IClassName *data = IClassName::Query(baseObj); @@ -180,7 +181,7 @@ static void GetBaseFloatDoubleDataValue(OHOS::AAFwk::IInterface *baseObj, Json:: (json)["type"] = type; \ } while (0); -template +template static void PacmapGetArrayVal(OHOS::AAFwk::IInterface *ao, std::vector &array) { if (ao == nullptr) { @@ -204,7 +205,7 @@ static void PacmapGetArrayVal(OHOS::AAFwk::IInterface *ao, std::vectorsecond.GetRefPtr()) != nullptr) { \ - auto func = [&](AAFwk::IInterface *object) { \ + auto func = [ & ](AAFwk::IInterface * object) { \ if (object != nullptr) { \ idInterface *value = idInterface::Query(object); \ if (value != nullptr) { \ @@ -938,7 +939,7 @@ bool PacMap::EqualPacMapData(const PacMapList &leftPacMapList, const PacMapList return true; } -template +template static void GetArrayData( AAFwk::IInterface *interface, std::vector &array, std::function IsArrayfunc) { @@ -951,7 +952,7 @@ static void GetArrayData( } } -template +template static bool CompareTwoArrayData( AAFwk::IInterface *one_interface, AAFwk::IInterface *two_interface, std::function IsArrayfunc) { @@ -989,44 +990,44 @@ bool PacMap::CompareArrayData(AAFwk::IInterface *one_interface, AAFwk::IInterfac } if (AAFwk::Array::IsBooleanArray(IArray::Query(one_interface))) { if (!CompareTwoArrayData( - one_interface, two_interface, AAFwk::Array::IsBooleanArray)) { + one_interface, two_interface, AAFwk::Array::IsBooleanArray)) { return false; } } else if (AAFwk::Array::IsCharArray(AAFwk::IArray::Query(one_interface))) { return false; } else if (AAFwk::Array::IsByteArray(IArray::Query(one_interface))) { if (!CompareTwoArrayData( - one_interface, two_interface, AAFwk::Array::IsByteArray)) { + one_interface, two_interface, AAFwk::Array::IsByteArray)) { return false; } } else if (AAFwk::Array::IsShortArray(IArray::Query(one_interface))) { if (!CompareTwoArrayData( - one_interface, two_interface, AAFwk::Array::IsShortArray)) { + one_interface, two_interface, AAFwk::Array::IsShortArray)) { return false; } } else if (AAFwk::Array::IsIntegerArray(IArray::Query(one_interface))) { if (!CompareTwoArrayData( - one_interface, two_interface, AAFwk::Array::IsIntegerArray)) { + one_interface, two_interface, AAFwk::Array::IsIntegerArray)) { return false; } } else if (AAFwk::Array::IsLongArray(IArray::Query(one_interface))) { if (!CompareTwoArrayData( - one_interface, two_interface, AAFwk::Array::IsLongArray)) { + one_interface, two_interface, AAFwk::Array::IsLongArray)) { return false; } } else if (AAFwk::Array::IsFloatArray(IArray::Query(one_interface))) { if (!CompareTwoArrayData( - one_interface, two_interface, AAFwk::Array::IsFloatArray)) { + one_interface, two_interface, AAFwk::Array::IsFloatArray)) { return false; } } else if (AAFwk::Array::IsDoubleArray(IArray::Query(one_interface))) { if (!CompareTwoArrayData( - one_interface, two_interface, AAFwk::Array::IsDoubleArray)) { + one_interface, two_interface, AAFwk::Array::IsDoubleArray)) { return false; } } else if (AAFwk::Array::IsStringArray(IArray::Query(one_interface))) { if (!CompareTwoArrayData( - one_interface, two_interface, AAFwk::Array::IsStringArray)) { + one_interface, two_interface, AAFwk::Array::IsStringArray)) { return false; } } else { @@ -1223,12 +1224,12 @@ bool PacMap::ToJson(const PacMapList &mapList, Json::Value &dataObject) const } return true; } -template + +template static std::string RawTypeToString(const RawType value, unsigned int precisionAfterPoint) { std::ostringstream out("RawTypeToString"); - out.precision(std::numeric_limits::digits10); - out << value; + out << std::setw(0) << std::setprecision(precisionAfterPoint) << value; std::string res = out.str(); auto pos = res.find('.'); diff --git a/frameworks/kits/content/cpp/src/ohos/aafwk/content/want.cpp b/frameworks/kits/content/cpp/src/ohos/aafwk/content/want.cpp index 9ffc20e7d38..29d7e06d9e3 100755 --- a/frameworks/kits/content/cpp/src/ohos/aafwk/content/want.cpp +++ b/frameworks/kits/content/cpp/src/ohos/aafwk/content/want.cpp @@ -1336,7 +1336,7 @@ void Want::ToUriStringInner(std::string &uriString) const } if (operation_.GetFlags() != 0) { uriString += "flag="; - char buf[HEX_STRING_BUF_LEN]{0}; + char buf[HEX_STRING_BUF_LEN] {0}; std::size_t len = snprintf_s(buf, HEX_STRING_BUF_LEN, HEX_STRING_BUF_LEN - 1, "0x%08x", operation_.GetFlags()); if (len == HEX_STRING_LEN) { std::string flag = buf; diff --git a/frameworks/kits/content/cpp/src/ohos/aafwk/content/want_params.cpp b/frameworks/kits/content/cpp/src/ohos/aafwk/content/want_params.cpp index cf50fa11dbe..32bc3385fb6 100755 --- a/frameworks/kits/content/cpp/src/ohos/aafwk/content/want_params.cpp +++ b/frameworks/kits/content/cpp/src/ohos/aafwk/content/want_params.cpp @@ -633,7 +633,7 @@ bool WantParams::Marshalling(Parcel &parcel) const return true; } -template +template static bool SetArray(const InterfaceID &id, const std::vector &value, sptr &ao) { typename std::vector::size_type size = value.size(); @@ -647,7 +647,7 @@ static bool SetArray(const InterfaceID &id, const std::vector &value, return false; } -template +template static void FillArray(IArray *ao, std::vector &array) { auto func = [&](IInterface *object) { @@ -661,7 +661,7 @@ static void FillArray(IArray *ao, std::vector &array) Array::ForEach(ao, func); } // inner use template function -template +template static void SetNewArray(const AAFwk::InterfaceID &id, AAFwk::IArray *orgIArray, sptr &ao) { if (orgIArray == nullptr) { diff --git a/frameworks/kits/content/cpp/src/ohos/aafwk/content/want_params_wrapper.cpp b/frameworks/kits/content/cpp/src/ohos/aafwk/content/want_params_wrapper.cpp index 595193a4b94..0158d50fa5b 100755 --- a/frameworks/kits/content/cpp/src/ohos/aafwk/content/want_params_wrapper.cpp +++ b/frameworks/kits/content/cpp/src/ohos/aafwk/content/want_params_wrapper.cpp @@ -16,9 +16,11 @@ #include namespace OHOS { namespace AAFwk { +#define WANT_PARAM_WRAPPER_TWO 2 IINTERFACE_IMPL_1(WantParamWrapper, Object, IWantParams); const InterfaceID g_IID_IWantParams = { - 0xa75b9db6, 0x9813, 0x4371, 0x8848, {0xd, 0x2, 0x9, 0x6, 0x6, 0xc, 0xe, 0x6, 0xe, 0xc, 0x6, 0x8}}; + 0xa75b9db6, 0x9813, 0x4371, 0x8848, {0xd, 0x2, 0x9, 0x6, 0x6, 0xc, 0xe, 0x6, 0xe, 0xc, 0x6, 0x8} +}; ErrCode WantParamWrapper::GetValue(WantParams &value) { @@ -77,7 +79,7 @@ bool WantParamWrapper::ValidateStr(const std::string &str) if (str == "" || str == "{}" || str == "{\"\"}") { return false; } - if (count(str.begin(), str.end(), '\"') % 2 != 0) { + if (count(str.begin(), str.end(), '\"') % WANT_PARAM_WRAPPER_TWO != 0) { return false; } if (count(str.begin(), str.end(), '{') != count(str.begin(), str.end(), '}')) { diff --git a/frameworks/kits/content/cpp/test/unittest/common/want_test.cpp b/frameworks/kits/content/cpp/test/unittest/common/want_test.cpp index fa3eb07f180..d98e772feb7 100755 --- a/frameworks/kits/content/cpp/test/unittest/common/want_test.cpp +++ b/frameworks/kits/content/cpp/test/unittest/common/want_test.cpp @@ -522,49 +522,48 @@ HWTEST_F(WantBaseTest, AaFwk_Want_Parcelable_0500, Function | MediumTest | Level GTEST_LOG_(INFO) << "WantOut_->GetStringParam(keyStr): " << param_content.c_str(); // want SetParam arraydata test - std::vector retboolArray; // boolArrayValue = {true, false, true}; + std::vector retboolArray; retboolArray = WantOut_->GetBoolArrayParam(std::string("bool_arraykey")); bool arraycompare = CompareArrayData(retboolArray, boolArrayValue); EXPECT_EQ(arraycompare, true); - std::vector retbyteArrayValue; // byteArrayValue = {'?', 'a', '\\'}; + std::vector retbyteArrayValue; retbyteArrayValue = WantOut_->GetByteArrayParam(std::string("byte_arraykey")); arraycompare = CompareArrayData(retbyteArrayValue, byteArrayValue); EXPECT_EQ(arraycompare, true); - std::vector retcharArrayValue; // charArrayValue = {U'e', U'l', U'l', U'o'}; + std::vector retcharArrayValue; retcharArrayValue = WantOut_->GetCharArrayParam(std::string("char_arraykey")); arraycompare = CompareArrayData(retcharArrayValue, charArrayValue); EXPECT_EQ(arraycompare, true); - std::vector retshortArrayValue; // shortArrayValue = {-1, 0, 1}; + std::vector retshortArrayValue; retshortArrayValue = WantOut_->GetShortArrayParam(std::string("short_arraykey")); arraycompare = CompareArrayData(retshortArrayValue, shortArrayValue); EXPECT_EQ(arraycompare, true); - std::vector retintArrayValue; // intArrayValue = {-10, 0, 10}; + std::vector retintArrayValue; retintArrayValue = WantOut_->GetIntArrayParam(std::string("int_arraykey")); arraycompare = CompareArrayData(retintArrayValue, intArrayValue); EXPECT_EQ(arraycompare, true); - std::vector retlonArrayValue; // longArrayValue = {-100, 0, 100}; + std::vector retlonArrayValue; retlonArrayValue = WantOut_->GetLongArrayParam(std::string("long_arraykey")); arraycompare = CompareArrayData(retlonArrayValue, longArrayValue); EXPECT_EQ(arraycompare, true); - std::vector retfloatArrayValue; // floatArrayValue = {-100.1, 0.1, 100.1}; + std::vector retfloatArrayValue; retfloatArrayValue = WantOut_->GetFloatArrayParam(std::string("float_arraykey")); arraycompare = CompareArrayData(retfloatArrayValue, floatArrayValue); EXPECT_EQ(arraycompare, true); - std::vector retdoubleArrayValue; // doubleArrayValue = {-1000.1, 0.1, 1000.1}; + std::vector retdoubleArrayValue; retdoubleArrayValue = WantOut_->GetDoubleArrayParam(std::string("double_arraykey")); arraycompare = CompareArrayData(retdoubleArrayValue, doubleArrayValue); EXPECT_EQ(arraycompare, true); - std::vector retstringArrayValue; // stringArrayValue = {"stringtest1", "string@test2", - // "string@!#test2"}; + std::vector retstringArrayValue; retstringArrayValue = WantOut_->GetStringArrayParam(std::string("string_arraykey")); arraycompare = CompareArrayData(retstringArrayValue, stringArrayValue); EXPECT_EQ(arraycompare, true); diff --git a/frameworks/kits/test/mock/DemoAbility/mock_ability_test.h b/frameworks/kits/test/mock/DemoAbility/mock_ability_test.h index 02b976a1a68..2211492767c 100644 --- a/frameworks/kits/test/mock/DemoAbility/mock_ability_test.h +++ b/frameworks/kits/test/mock/DemoAbility/mock_ability_test.h @@ -25,18 +25,24 @@ namespace OHOS { namespace AppExecFwk { +#define INSERT 20 +#define UPDATE 33 +#define OPENRAWFILE 122 +#define BATCHINSERT 115 +#define DELETE 234 + class MockAbilityTest : public Ability { public: int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) { GTEST_LOG_(INFO) << "MockAbilityTest::Insert called"; - return 20; + return INSERT; } int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) { GTEST_LOG_(INFO) << "MockAbilityTest::Update called"; - return 33; + return UPDATE; } std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) @@ -53,15 +59,15 @@ public: int fd; GTEST_LOG_(INFO) << "MockAbilityTest::OpenFile called"; FILE *fd1 = fopen("/dataability_openfile_test.txt", "w+"); - if(fd1 == nullptr) { + if (fd1 == nullptr) { GTEST_LOG_(INFO) << "MockAbilityTest::OpenFile fd1 == nullptr"; return -1; } - fputs("123456",fd1); + fputs("123456", fd1); fclose(fd1); FILE *fd2 = fopen("/dataability_openfile_test.txt", "r"); - if(fd2 == nullptr) { + if (fd2 == nullptr) { GTEST_LOG_(INFO) << "MockAbilityTest::OpenFile fd2 == nullptr"; return -1; } @@ -74,13 +80,13 @@ public: { GTEST_LOG_(INFO) << "MockAbilityTest::OpenRawFile called"; - return 122; + return OPENRAWFILE; } int BatchInsert(const Uri &uri, const std::vector &values) { GTEST_LOG_(INFO) << "MockAbilityTest::BatchInsert called"; - return 115; + return BATCHINSERT; } bool Reload(const Uri &uri, const PacMap &extras) @@ -92,7 +98,7 @@ public: int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) { GTEST_LOG_(INFO) << "MockAbilityTest::Delete called"; - return 234; + return DELETE; } std::string GetType(const Uri &uri) diff --git a/frameworks/kits/test/mock/DemoObServer/mock_ability_manager_client.h b/frameworks/kits/test/mock/DemoObServer/mock_ability_manager_client.h index 46ed31af3bd..25854397b80 100644 --- a/frameworks/kits/test/mock/DemoObServer/mock_ability_manager_client.h +++ b/frameworks/kits/test/mock/DemoObServer/mock_ability_manager_client.h @@ -55,8 +55,7 @@ sptr AAFwk::AbilityManagerClient::AcquireDataAbility( retval = remoteProxy; - if(retval == nullptr) - { + if (retval == nullptr) { GTEST_LOG_(INFO) << "mock_ability_thread_for_data_observer:mock result retval is nullptr called"; } } else { diff --git a/frameworks/kits/test/mock/DemoObServer/mock_ability_thread_for_data_observer.h b/frameworks/kits/test/mock/DemoObServer/mock_ability_thread_for_data_observer.h index 9c172586303..6c5f002d4a4 100644 --- a/frameworks/kits/test/mock/DemoObServer/mock_ability_thread_for_data_observer.h +++ b/frameworks/kits/test/mock/DemoObServer/mock_ability_thread_for_data_observer.h @@ -34,20 +34,17 @@ namespace AppExecFwk { sptr MockCreateAbilityThread() { sptr abilitythread(new (std::nothrow) AppExecFwk::AbilityThread()); - if(abilitythread == nullptr) - { + if (abilitythread == nullptr) { GTEST_LOG_(INFO) << "mock_ability_thread_for_data_observer:mock abilityhreadptr is nullptr called"; } std::shared_ptr application = std::make_shared(); - if(application == nullptr) - { + if (application == nullptr) { GTEST_LOG_(INFO) << "mock_ability_thread_for_data_observer:mock applicationptr is nullptr called"; } std::shared_ptr info = std::make_shared(); - if(info == nullptr) - { + if (info == nullptr) { GTEST_LOG_(INFO) << "mock_ability_thread_for_data_observer:mock AbilityInfo::info is nullptr called"; } @@ -55,7 +52,6 @@ sptr MockCreateAbilityThread() info->type = AbilityType::DATA; info->isNativeAbility = true; std::cout << "info->name : " << (*info).name <type : " << (*info).type. < token = sptr(new AbilityThread()); diff --git a/frameworks/kits/test/moduletest/cpp/abilitytest/data_ability_helper_module_test.cpp b/frameworks/kits/test/moduletest/cpp/abilitytest/data_ability_helper_module_test.cpp index 7ab861bf8c9..ef536e3baaa 100644 --- a/frameworks/kits/test/moduletest/cpp/abilitytest/data_ability_helper_module_test.cpp +++ b/frameworks/kits/test/moduletest/cpp/abilitytest/data_ability_helper_module_test.cpp @@ -254,10 +254,9 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_OpenFile_Test_0100, Func } string stringstr(str); EXPECT_STREQ(stringstr.c_str(), result.c_str()); - - fclose(file); - system("rm /dataability_openfile_test.txt"); } + fclose(file); + system("rm /dataability_openfile_test.txt"); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenFile_Test_0100 end"; } @@ -295,10 +294,9 @@ HWTEST_F(DataAbilityHelperTest, AaFwk_DataAbilityHelper_OpenFile_Test_0200, Func } string stringstr(str); EXPECT_STREQ(stringstr.c_str(), result.c_str()); - - fclose(file); - system("rm /dataability_openfile_test.txt"); } + fclose(file); + system("rm /dataability_openfile_test.txt"); GTEST_LOG_(INFO) << "AaFwk_DataAbilityHelper_OpenFile_Test_0200 end"; } diff --git a/interfaces/innerkits/base/include/ohos/aafwk/base/base_def.h b/interfaces/innerkits/base/include/ohos/aafwk/base/base_def.h index 9d1c945b88f..8b2d353c827 100644 --- a/interfaces/innerkits/base/include/ohos/aafwk/base/base_def.h +++ b/interfaces/innerkits/base/include/ohos/aafwk/base/base_def.h @@ -64,7 +64,7 @@ namespace AAFwk { \ void DecStrongRef(const void *id = nullptr) override; \ \ - IInterface *Query(const InterfaceID &iid) override; \ + IInterface *Query(const InterfaceID & iid) override; \ \ InterfaceID GetInterfaceID(IInterface *object) override; @@ -82,7 +82,7 @@ namespace AAFwk { Object::DecStrongRef(id); \ } \ \ - IInterface *ClassName::Query(const InterfaceID &iid) \ + IInterface *ClassName::Query(const InterfaceID & iid) \ { \ if (iid == g_IID_##InterfaceName) { \ return static_cast(this); \ @@ -113,7 +113,7 @@ namespace AAFwk { { \ Object::DecStrongRef(id); \ } \ - IInterface *ClassName::Query(const InterfaceID &iid) \ + IInterface *ClassName::Query(const InterfaceID & iid) \ { \ if (iid == g_IID_##InterfaceName1) { \ return static_cast(this); \ diff --git a/interfaces/innerkits/base/include/ohos/aafwk/base/ipc_singleton.h b/interfaces/innerkits/base/include/ohos/aafwk/base/ipc_singleton.h index 88bcd4a9cbb..6ab3516a632 100644 --- a/interfaces/innerkits/base/include/ohos/aafwk/base/ipc_singleton.h +++ b/interfaces/innerkits/base/include/ohos/aafwk/base/ipc_singleton.h @@ -30,7 +30,7 @@ private: \ friend DelayedIPCSingleton; \ MyClass(); -template +template class DelayedIPCSingleton : public NoCopyable { public: static sptr GetInstance() @@ -52,13 +52,13 @@ private: static std::mutex mutex_; }; -template +template sptr DelayedIPCSingleton::instance_ = nullptr; -template +template std::mutex DelayedIPCSingleton::mutex_; -template +template void DelayedIPCSingleton::DestroyInstance() { std::lock_guard lock(mutex_); diff --git a/interfaces/innerkits/base/include/ohos/aafwk/base/user_object_base.h b/interfaces/innerkits/base/include/ohos/aafwk/base/user_object_base.h index d67da14e450..91c97c633ac 100755 --- a/interfaces/innerkits/base/include/ohos/aafwk/base/user_object_base.h +++ b/interfaces/innerkits/base/include/ohos/aafwk/base/user_object_base.h @@ -123,7 +123,7 @@ private: static __attribute__((constructor)) void RegisterUserMapObject_##className() \ { \ UserObjectBaseLoader::GetInstance().RegisterUserObject( \ - #className, []() -> UserObjectBase * { return new (std::nothrow)(className); }); \ + #className, []()->UserObjectBase * { return new (std::nothrow)(className); }); \ } } // namespace AAFwk diff --git a/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.cpp b/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.cpp index 323a11b9e15..011988f3f81 100644 --- a/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.cpp +++ b/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.cpp @@ -56,7 +56,7 @@ napi_value ParseBundleName(napi_env env, std::string &bundleName, napi_value arg size_t len = 0; napi_get_value_string_utf8(env, args, buf, BUFFER_LENGTH_MAX, &len); HILOG_INFO("bundleName= [%{public}s].", buf); - bundleName = std::string{buf}; + bundleName = std::string(buf); // create reutrn napi_value ret = 0; NAPI_CALL(env, napi_create_int32(env, 0, &ret)); @@ -162,6 +162,14 @@ void GetAbilityMissionInfosForResult( napi_create_string_utf8(env, item.baseAbility.GetAbilityName().c_str(), NAPI_AUTO_LENGTH, &abilityName)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, baseAbility, "abilityName", abilityName)); + napi_value uri = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, "", NAPI_AUTO_LENGTH, &uri)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, baseAbility, "uri", uri)); + + napi_value shortName = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, "", NAPI_AUTO_LENGTH, &shortName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, baseAbility, "shortName", shortName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objRecentMissionInfo, "bottomAbility", baseAbility)); napi_value topAbility = nullptr; @@ -178,6 +186,13 @@ void GetAbilityMissionInfosForResult( NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, item.topAbility.GetAbilityName().c_str(), NAPI_AUTO_LENGTH, &abilityName)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, topAbility, "abilityName", abilityName)); + + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, "", NAPI_AUTO_LENGTH, &uri)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, topAbility, "uri", uri)); + + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, "", NAPI_AUTO_LENGTH, &shortName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, topAbility, "shortName", shortName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objRecentMissionInfo, "topAbility", topAbility)); napi_value nWindowMode = nullptr; diff --git a/interfaces/kits/napi/aafwk/dataUriUtils/native_module.cpp b/interfaces/kits/napi/aafwk/dataUriUtils/native_module.cpp index 7e92f967c94..f4baa0c8514 100644 --- a/interfaces/kits/napi/aafwk/dataUriUtils/native_module.cpp +++ b/interfaces/kits/napi/aafwk/dataUriUtils/native_module.cpp @@ -37,13 +37,15 @@ EXTERN_C_END /* * The module definition. */ -static napi_module _module = {.nm_version = 1, +static napi_module _module = { + .nm_version = 1, .nm_flags = 0, .nm_filename = nullptr, .nm_register_func = Init, .nm_modname = "ability.dataUriUtils", .nm_priv = ((void *)0), - .reserved = {0}}; + .reserved = {0} +}; /* * The module registration. diff --git a/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp b/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp index 5b51c9e46f2..5e857099778 100755 --- a/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp +++ b/interfaces/kits/napi/aafwk/featureAbility/feature_ability.cpp @@ -29,8 +29,6 @@ using namespace OHOS::AppExecFwk; namespace OHOS { namespace AppExecFwk { -extern napi_value g_classContext; -extern napi_value g_dataAbilityHelper; static int64_t dummyRequestCode_ = 0; CallbackInfo g_aceCallbackInfo; @@ -936,7 +934,7 @@ napi_value UnwrapForResultParam(CallAbilityParam ¶m, napi_env env, napi_valu // dummy requestCode for NativeC++ interface and onabilityresult callback param.requestCode = dummyRequestCode_; param.forResultOption = true; - dummyRequestCode_ < INT64_MAX ? dummyRequestCode_ = dummyRequestCode_ + 1 : dummyRequestCode_ = 0; + dummyRequestCode_ = (dummyRequestCode_ < INT64_MAX) ? (dummyRequestCode_ + 1) : 0; HILOG_INFO("%{public}s, reqCode=%{public}d forResultOption=%{public}d.", __func__, param.requestCode, @@ -1207,7 +1205,7 @@ void GetDataAbilityHelperAsyncCompleteCB(napi_env env, napi_status status, void NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, dataAbilityHelperCB->uri, &uri)); NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, dataAbilityHelperCB->cbBase.cbInfo.callback, &callback)); - NAPI_CALL_RETURN_VOID(env, napi_new_instance(env, g_dataAbilityHelper, 1, &uri, &dataAbilityHelperCB->result)); + NAPI_CALL_RETURN_VOID(env, napi_new_instance(env, GetGlobalDataAbilityHelper(), 1, &uri, &dataAbilityHelperCB->result)); result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); result[PARAM1] = dataAbilityHelperCB->result; @@ -1229,7 +1227,7 @@ void GetDataAbilityHelperPromiseCompleteCB(napi_env env, napi_status status, voi napi_value uri = nullptr; napi_value result = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, dataAbilityHelperCB->uri, &uri)); - NAPI_CALL_RETURN_VOID(env, napi_new_instance(env, g_dataAbilityHelper, 1, &uri, &dataAbilityHelperCB->result)); + NAPI_CALL_RETURN_VOID(env, napi_new_instance(env, GetGlobalDataAbilityHelper(), 1, &uri, &dataAbilityHelperCB->result)); result = dataAbilityHelperCB->result; NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, dataAbilityHelperCB->cbBase.deferred, result)); diff --git a/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp b/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp index b9f51b7797d..b971dacc1bf 100755 --- a/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp +++ b/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp @@ -410,7 +410,7 @@ void CallOnRequestPermissionsFromUserResult(int requestCode, const std::vectorpermissions.size(); i++) { napi_create_string_utf8(onRequestPermissionCB->cb.env, - onRequestPermissionCB->permissions[i].c_str(), + onRequestPermissionCB->permissions[i].c_str(), NAPI_AUTO_LENGTH, &perValue); napi_set_element(onRequestPermissionCB->cb.env, perArray, i, perValue); @@ -441,9 +441,9 @@ void CallOnRequestPermissionsFromUserResult(int requestCode, const std::vectorcb.env, &grantArray); - for (size_t i = 0; i < onRequestPermissionCB->grantResults.size(); i++) { - napi_create_int32(onRequestPermissionCB->cb.env, onRequestPermissionCB->grantResults[i], &perValue); - napi_set_element(onRequestPermissionCB->cb.env, grantArray, i, perValue); + for (size_t j = 0; j < onRequestPermissionCB->grantResults.size(); j++) { + napi_create_int32(onRequestPermissionCB->cb.env, onRequestPermissionCB->grantResults[j], &perValue); + napi_set_element(onRequestPermissionCB->cb.env, grantArray, j, perValue); } napi_set_named_property(onRequestPermissionCB->cb.env, result[PARAM1], "authResults", grantArray); @@ -2254,12 +2254,21 @@ void GetOrCreateLocalDirExecuteCB(napi_env env, void *data) std::string dataDir = getOrCreateLocalDirCB->cbBase.ability->GetAbilityInfo()->applicationInfo.dataDir; std::shared_ptr hap = getOrCreateLocalDirCB->cbBase.ability->GetHapModuleInfo(); std::string moduleName = (hap != nullptr) ? hap->name : std::string(); + std::string dataDirWithModuleName = dataDir + CONTEXT_DEAL_FILE_SEPARATOR + moduleName; + HILOG_INFO("NAPI_GetOrCreateLocalDir, dataDir:%{public}s moduleName:%{public}s abilityName:%{public}s", + dataDir.c_str(), + moduleName.c_str(), + abilityName.c_str()); + + // if dataDirWithModuleName is not exits, do nothing and return. + if (!OHOS::FileExists(dataDirWithModuleName)) { + getOrCreateLocalDirCB->rootDir = ""; + HILOG_INFO("NAPI_GetOrCreateLocalDir, dirWithModuleName is not exits:%{public}s, do nothing and return null.", + dataDirWithModuleName.c_str()); + return; + } - HILOG_INFO("NAPI_GetOrCreateLocalDir, abilityName:%{public}s moduleName:%{public}s", - abilityName.c_str(), - moduleName.c_str()); - getOrCreateLocalDirCB->rootDir = - dataDir + CONTEXT_DEAL_FILE_SEPARATOR + moduleName + CONTEXT_DEAL_FILE_SEPARATOR + abilityName; + getOrCreateLocalDirCB->rootDir = dataDirWithModuleName + CONTEXT_DEAL_FILE_SEPARATOR + abilityName; HILOG_INFO("NAPI_GetOrCreateLocalDir, GetDir rootDir:%{public}s", getOrCreateLocalDirCB->rootDir.c_str()); if (!OHOS::FileExists(getOrCreateLocalDirCB->rootDir)) { HILOG_INFO("NAPI_GetOrCreateLocalDir dir is not exits, create dir."); diff --git a/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp b/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp index 47ce9e1ddd0..32aef8b355c 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp +++ b/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp @@ -234,10 +234,10 @@ void AnalysisValuesBucket(NativeRdb::ValuesBucket &valuesBucket, const napi_env } HILOG_INFO("ValuesBucket num:%{public}d ", arrLen); for (size_t i = 0; i < arrLen; ++i) { - napi_value key; + napi_value key = 0; status = napi_get_element(env, keys, i, &key); std::string keyStr = UnwrapStringFromJS(env, key); - napi_value value; + napi_value value = 0; napi_get_property(env, arg, key, &value); SetValuesBucketObject(valuesBucket, env, keyStr, value); @@ -257,7 +257,7 @@ void SetValuesBucketObject( valueString.c_str()); valuesBucket.PutString(keyStr, valueString); } else if (valueType == napi_number) { - double valueNumber; + double valueNumber = 0; napi_get_value_double(env, value, &valueNumber); valuesBucket.PutDouble(keyStr, valueNumber); HILOG_INFO( @@ -420,7 +420,6 @@ napi_value UnwrapValuesBucket(std::string &value, napi_env env, napi_value args) return result; } - /** * @brief DataAbilityHelper NAPI method : notifyChange. * @@ -432,19 +431,24 @@ napi_value UnwrapValuesBucket(std::string &value, napi_env env, napi_value args) napi_value NAPI_NotifyChange(napi_env env, napi_callback_info info) { HILOG_INFO("%{public}s,called", __func__); - DAHelperNotifyChangeCB *notifyChangeCB = new (std::nothrow) DAHelperNotifyChangeCB{ - .cbBase.cbInfo.env = env, - .cbBase.asyncWork = nullptr, - .cbBase.deferred = nullptr, - .cbBase.ability = nullptr, - }; + DAHelperNotifyChangeCB *notifyChangeCB = new (std::nothrow) DAHelperNotifyChangeCB; + if (notifyChangeCB == nullptr) { + HILOG_ERROR("%{public}s, notifyChangeCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + notifyChangeCB->cbBase.cbInfo.env = env; + notifyChangeCB->cbBase.asyncWork = nullptr; + notifyChangeCB->cbBase.deferred = nullptr; + notifyChangeCB->cbBase.ability = nullptr; napi_value ret = NotifyChangeWrap(env, info, notifyChangeCB); if (ret == nullptr) { + HILOG_ERROR("%{public}s, ret == nullptr.", __func__); if (notifyChangeCB != nullptr) { delete notifyChangeCB; notifyChangeCB = nullptr; } + ret = WrapVoidToJS(env); } return ret; } @@ -557,7 +561,7 @@ napi_value NotifyChangePromise(napi_env env, DAHelperNotifyChangeCB *notifyChang void NotifyChangeExecuteCB(napi_env env, void *data) { HILOG_INFO("NAPI_NotifyChange, worker pool thread execute."); - DAHelperNotifyChangeCB *notifyChangeCB = (DAHelperNotifyChangeCB *)data; + DAHelperNotifyChangeCB *notifyChangeCB = static_cast(data); if (notifyChangeCB->dataAbilityHelper != nullptr) { OHOS::Uri uri(notifyChangeCB->uri); notifyChangeCB->dataAbilityHelper->NotifyChange(uri); @@ -567,7 +571,7 @@ void NotifyChangeExecuteCB(napi_env env, void *data) void NotifyChangeAsyncCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_NotifyChange, main event thread complete."); - DAHelperNotifyChangeCB *notifyChangeCB = (DAHelperNotifyChangeCB *)data; + DAHelperNotifyChangeCB *notifyChangeCB = static_cast(data); napi_value callback = nullptr; napi_value undefined = nullptr; napi_value result[ARGS_TWO] = {nullptr}; @@ -590,7 +594,7 @@ void NotifyChangeAsyncCompleteCB(napi_env env, napi_status status, void *data) void NotifyChangePromiseCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_NotifyChange, main event thread complete."); - DAHelperNotifyChangeCB *notifyChangeCB = (DAHelperNotifyChangeCB *)data; + DAHelperNotifyChangeCB *notifyChangeCB = static_cast(data); napi_value result = nullptr; napi_create_int32(env, 0, &result); NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, notifyChangeCB->cbBase.deferred, result)); @@ -610,15 +614,26 @@ void NotifyChangePromiseCompleteCB(napi_env env, napi_status status, void *data) napi_value NAPI_Register(napi_env env, napi_callback_info info) { HILOG_INFO("%{public}s,called", __func__); - DAHelperOnOffCB *onCB = new (std::nothrow) DAHelperOnOffCB{ - .cbBase.cbInfo.env = env, - .cbBase.asyncWork = nullptr, - .cbBase.deferred = nullptr, - .cbBase.ability = nullptr, - }; + DAHelperOnOffCB *onCB = new (std::nothrow) DAHelperOnOffCB; + if (onCB == nullptr) { + HILOG_ERROR("%{public}s, onCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + onCB->cbBase.cbInfo.env = env; + onCB->cbBase.asyncWork = nullptr; + onCB->cbBase.deferred = nullptr; + onCB->cbBase.ability = nullptr; napi_value ret = RegisterWrap(env, info, onCB); - + if (ret == nullptr) { + HILOG_ERROR("%{public}s, ret == nullptr.", __func__); + if (onCB != nullptr) { + delete onCB; + onCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,called end", __func__); return ret; } @@ -700,7 +715,8 @@ napi_value RegisterAsync( } NAPI_CALL(env, - napi_create_async_work(env, + napi_create_async_work( + env, nullptr, resourceName, RegisterExecuteCB, @@ -718,7 +734,7 @@ napi_value RegisterAsync( void RegisterExecuteCB(napi_env env, void *data) { HILOG_INFO("NAPI_Register, worker pool thread execute."); - DAHelperOnOffCB *onCB = (DAHelperOnOffCB *)data; + DAHelperOnOffCB *onCB = static_cast(data); if (onCB->dataAbilityHelper != nullptr) { onCB->observer->SetEnv(env); onCB->observer->SetCallbackRef(onCB->cbBase.cbInfo.callback); @@ -739,15 +755,26 @@ void RegisterExecuteCB(napi_env env, void *data) napi_value NAPI_UnRegister(napi_env env, napi_callback_info info) { HILOG_INFO("%{public}s,called", __func__); - DAHelperOnOffCB *offCB = new (std::nothrow) DAHelperOnOffCB{ - .cbBase.cbInfo.env = env, - .cbBase.asyncWork = nullptr, - .cbBase.deferred = nullptr, - .cbBase.ability = nullptr, - }; + DAHelperOnOffCB *offCB = new (std::nothrow) DAHelperOnOffCB; + if (offCB == nullptr) { + HILOG_ERROR("%{public}s, offCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + offCB->cbBase.cbInfo.env = env; + offCB->cbBase.asyncWork = nullptr; + offCB->cbBase.deferred = nullptr; + offCB->cbBase.ability = nullptr; napi_value ret = UnRegisterWrap(env, info, offCB); - + if (ret == nullptr) { + HILOG_ERROR("%{public}s, ret == nullptr.", __func__); + if (offCB != nullptr) { + delete offCB; + offCB = nullptr; + } + ret = WrapVoidToJS(env); + } + HILOG_INFO("%{public}s,called end", __func__); return ret; } @@ -854,59 +881,13 @@ napi_value UnRegisterAsync( void UnRegisterExecuteCB(napi_env env, void *data) { HILOG_INFO("NAPI_UnRegister, worker pool thread execute."); -#if 0 - DAHelperOnOffCB *offCB = (DAHelperOnOffCB *)data; - if (offCB->dataAbilityHelper != nullptr) { - HILOG_INFO("NAPI_UnRegister uri=%{public}s", offCB->uri.c_str()); - if (offCB->uri != "") { - // with uri - std::string strUri = offCB->uri; - do { - HILOG_INFO("NAPI_UnRegister registerInstances_ size = %{public}d", registerInstances_.size()); - auto helper = std::find_if(registerInstances_.begin(), - registerInstances_.end(), - [strUri](const DAHelperOnOffCB *helper) { return helper->uri == strUri; }); - if (helper != registerInstances_.end()) { - // match uri - OHOS::Uri uri((*helper)->uri); - (*helper)->dataAbilityHelper->UnregisterObserver(uri, (*helper)->observer); - delete *helper; - registerInstances_.erase(helper); - HILOG_INFO("NAPI_UnRegister erase registerInstances_ size = %{public}d", registerInstances_.size()); - } else { - break; - } - } while (true); - } else { - // without both uri - DataAbilityHelper *dataAbilityHelper = offCB->dataAbilityHelper; - do { - HILOG_INFO("NAPI_UnRegister registerInstances_ size = %{public}d", registerInstances_.size()); - auto helper = std::find_if(registerInstances_.begin(), - registerInstances_.end(), - [dataAbilityHelper]( - const DAHelperOnOffCB *helper) { return helper->dataAbilityHelper == dataAbilityHelper; }); - if (helper != registerInstances_.end()) { - // match dataAbilityHelper - OHOS::Uri uri((*helper)->uri); - (*helper)->dataAbilityHelper->UnregisterObserver(uri, (*helper)->observer); - delete *helper; - registerInstances_.erase(helper); - HILOG_INFO("NAPI_UnRegister erase registerInstances_ size = %{public}d", registerInstances_.size()); - } else { - break; - } - } while (true); - } - } -#endif } void UnRegisterCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_UnRegister, main event thread complete."); // cannot run it in executeCB, because need to use napi_strict_equals compare callbacks. - DAHelperOnOffCB *offCB = (DAHelperOnOffCB *)data; + DAHelperOnOffCB *offCB = static_cast(data); if (offCB == nullptr || offCB->dataAbilityHelper == nullptr) { HILOG_ERROR("NAPI_UnRegister, offCB is null:%{public}p,%{public}p.", offCB, offCB->dataAbilityHelper); return; @@ -916,8 +897,8 @@ void UnRegisterCompleteCB(napi_env env, napi_status status, void *data) // if match callback ,or match both callback and uri napi_ref callback = offCB->cbBase.cbInfo.callback; do { - auto helper = - std::find_if(registerInstances_.begin(), registerInstances_.end(), [callback](const DAHelperOnOffCB *helper) { + auto helper = std::find_if( + registerInstances_.begin(), registerInstances_.end(), [callback](const DAHelperOnOffCB *helper) { bool result = false; napi_value callbackA = 0; napi_value callbackB = 0; @@ -925,17 +906,17 @@ void UnRegisterCompleteCB(napi_env env, napi_status status, void *data) napi_get_reference_value(helper->cbBase.cbInfo.env, helper->cbBase.cbInfo.callback, &callbackA); auto ret = napi_strict_equals(helper->cbBase.cbInfo.env, callbackA, callbackB, &result); HILOG_INFO("NAPI_UnRegister cb equals status=%{public}d result=%{public}d.", ret, result); - // return helper->cbBase.cbInfo.callback == callback; return result; }); if (helper != registerInstances_.end()) { OHOS::Uri uri((*helper)->uri); // if uri is not empty, uri and callback has to be equal at the same time. - if ((offCB->uri == "") || (offCB->uri == uri.ToString())) { + if (offCB->uri == uri.ToString()) { // match callback, or match both callback and uri (*helper)->dataAbilityHelper->UnregisterObserver(uri, (*helper)->observer); - delete *helper; registerInstances_.erase(helper); + delete *helper; + *helper = nullptr; HILOG_INFO("NAPI_UnRegister Instances erase size = %{public}zu", registerInstances_.size()); } else { HILOG_INFO("NAPI_UnRegister uri=%{public}s,helper.Uri=%{public}s", @@ -943,6 +924,7 @@ void UnRegisterCompleteCB(napi_env env, napi_status status, void *data) uri.ToString().c_str()); } } else { + HILOG_INFO("NAPI_UnRegister not match any callback."); break; // not match any callback } } while (true); @@ -959,32 +941,17 @@ void UnRegisterCompleteCB(napi_env env, napi_status status, void *data) // match uri OHOS::Uri uri((*helper)->uri); (*helper)->dataAbilityHelper->UnregisterObserver(uri, (*helper)->observer); - delete *helper; registerInstances_.erase(helper); + delete *helper; + *helper = nullptr; HILOG_INFO("NAPI_UnRegister Instances erase size = %{public}zu", registerInstances_.size()); } else { + HILOG_INFO("NAPI_UnRegister not match any uri."); break; // not match any uri } } while (true); } else { - // without both uri and callback, unregister all observers corresponding the helper - DataAbilityHelper *dataAbilityHelper = offCB->dataAbilityHelper; - do { - auto helper = std::find_if( - registerInstances_.begin(), registerInstances_.end(), [dataAbilityHelper](const DAHelperOnOffCB *helper) { - return helper->dataAbilityHelper == dataAbilityHelper; - }); - if (helper != registerInstances_.end()) { - // match dataAbilityHelper - OHOS::Uri uri((*helper)->uri); - (*helper)->dataAbilityHelper->UnregisterObserver(uri, (*helper)->observer); - delete *helper; - registerInstances_.erase(helper); - HILOG_INFO("NAPI_UnRegister Instances erase size = %{public}zu", registerInstances_.size()); - } else { - break; // not match any helper - } - } while (true); + HILOG_ERROR("NAPI_UnRegister, error: uri is null."); } } } @@ -1004,17 +971,33 @@ void NAPIDataAbilityObserver::OnChange() HILOG_INFO("%{public}s, called.", __func__); uv_loop_s *loop = nullptr; - -#if NAPI_VERSION >= 2 napi_get_uv_event_loop(env_, &loop); -#endif // NAPI_VERSION >= 2 + if (loop == nullptr) { + HILOG_ERROR("%{public}s, loop == nullptr.", __func__); + return; + } uv_work_t *work = new uv_work_t; - DAHelperOnOffCB *onCB = - new (std::nothrow) DAHelperOnOffCB{.cbBase.cbInfo.env = env_, .cbBase.cbInfo.callback = ref_}; + if (work == nullptr) { + HILOG_ERROR("%{public}s, work==nullptr.", __func__); + return; + } + + DAHelperOnOffCB *onCB = new (std::nothrow) DAHelperOnOffCB; + if (onCB == nullptr) { + HILOG_ERROR("%{public}s, onCB == nullptr.", __func__); + if (work != nullptr) { + delete work; + work = nullptr; + } + return; + } + onCB->cbBase.cbInfo.env = env_; + onCB->cbBase.cbInfo.callback = ref_; work->data = (void *)onCB; - uv_queue_work(loop, + int rev = uv_queue_work( + loop, work, [](uv_work_t *work) {}, [](uv_work_t *work, int status) { @@ -1037,7 +1020,18 @@ void NAPIDataAbilityObserver::OnChange() delete event; delete work; }); + if (rev != 0) { + if (onCB != nullptr) { + delete onCB; + onCB = nullptr; + } + if (work != nullptr) { + delete work; + work = nullptr; + } + } } + napi_value NAPI_GetType(napi_env env, napi_callback_info info) { HILOG_INFO("%{public}s,called", __func__); @@ -2957,19 +2951,24 @@ void ReleasePromiseCompleteCB(napi_env env, napi_status status, void *data) napi_value NAPI_ExecuteBatch(napi_env env, napi_callback_info info) { HILOG_INFO("%{public}s,start", __func__); - DAHelperExecuteBatchCB *executeBatchCB = new (std::nothrow) DAHelperExecuteBatchCB{ - .cbBase.cbInfo.env = env, - .cbBase.asyncWork = nullptr, - .cbBase.deferred = nullptr, - .cbBase.ability = nullptr, - }; + DAHelperExecuteBatchCB *executeBatchCB = new (std::nothrow) DAHelperExecuteBatchCB; + if (executeBatchCB == nullptr) { + HILOG_ERROR("%{public}s, executeBatchCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + executeBatchCB->cbBase.cbInfo.env = env; + executeBatchCB->cbBase.asyncWork = nullptr; + executeBatchCB->cbBase.deferred = nullptr; + executeBatchCB->cbBase.ability = nullptr; napi_value ret = ExecuteBatchWrap(env, info, executeBatchCB); if (ret == nullptr) { + HILOG_ERROR("%{public}s, ret == nullptr.", __func__); if (executeBatchCB != nullptr) { delete executeBatchCB; executeBatchCB = nullptr; } + ret = WrapVoidToJS(env); } HILOG_INFO("%{public}s,end", __func__); return ret; @@ -3110,7 +3109,7 @@ napi_value ExecuteBatchPromise(napi_env env, DAHelperExecuteBatchCB *executeBatc void ExecuteBatchExecuteCB(napi_env env, void *data) { HILOG_INFO("%{public}s,NAPI_ExecuteBatch, worker pool thread execute start.", __func__); - DAHelperExecuteBatchCB *executeBatchCB = (DAHelperExecuteBatchCB *)data; + DAHelperExecuteBatchCB *executeBatchCB = static_cast(data); if (executeBatchCB->dataAbilityHelper != nullptr) { OHOS::Uri uri(executeBatchCB->uri); executeBatchCB->result = executeBatchCB->dataAbilityHelper->ExecuteBatch(uri, executeBatchCB->operations); @@ -3122,7 +3121,7 @@ void ExecuteBatchExecuteCB(napi_env env, void *data) void ExecuteBatchAsyncCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("%{public}s, NAPI_ExecuteBatch, main event thread complete start.", __func__); - DAHelperExecuteBatchCB *executeBatchCB = (DAHelperExecuteBatchCB *)data; + DAHelperExecuteBatchCB *executeBatchCB = static_cast(data); napi_value callback = nullptr; napi_value undefined = nullptr; napi_value result[ARGS_TWO] = {nullptr}; @@ -3147,7 +3146,7 @@ void ExecuteBatchAsyncCompleteCB(napi_env env, napi_status status, void *data) void ExecuteBatchPromiseCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("%{public}s, NAPI_ExecuteBatch, main event thread complete start.", __func__); - DAHelperExecuteBatchCB *executeBatchCB = (DAHelperExecuteBatchCB *)data; + DAHelperExecuteBatchCB *executeBatchCB = static_cast(data); napi_value result = nullptr; napi_create_array(env, &result); GetDataAbilityResultForResult(env, executeBatchCB->result, result); diff --git a/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.h b/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.h index 06ca3caac91..7f30c70c4b2 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.h +++ b/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.h @@ -27,8 +27,8 @@ public: void SetCallbackRef(const napi_ref &ref); private: - napi_env env_; - napi_ref ref_; + napi_env env_ = nullptr; + napi_ref ref_ = nullptr; }; /** diff --git a/interfaces/kits/napi/aafwk/featureAbility/native_module.cpp b/interfaces/kits/napi/aafwk/featureAbility/native_module.cpp index f6dfa962d60..831e817934e 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/native_module.cpp +++ b/interfaces/kits/napi/aafwk/featureAbility/native_module.cpp @@ -45,13 +45,15 @@ EXTERN_C_END /* * The module definition. */ -static napi_module _module = {.nm_version = 1, +static napi_module _module = { + .nm_version = 1, .nm_flags = 0, .nm_filename = nullptr, .nm_register_func = Init, .nm_modname = "ability.featureAbility", .nm_priv = ((void *)0), - .reserved = {0}}; + .reserved = {0} +}; /* * The module registration. diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp old mode 100644 new mode 100755 index b3a4d7f5409..18f3056ade1 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp @@ -33,6 +33,11 @@ napi_value *GetGlobalClassContext(void) return &g_classContext; } +napi_value GetGlobalDataAbilityHelper(void) +{ + return g_dataAbilityHelper; +} + bool CheckAbilityType(AbilityType typeInAbility, AbilityType typeWant) { HILOG_INFO("%{public}s called.", __func__); @@ -1654,8 +1659,6 @@ napi_value GetContextWrap(napi_env env, napi_callback_info info, AsyncCallbackIn napi_value result = nullptr; napi_new_instance(env, g_classContext, 0, nullptr, &result); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; HILOG_INFO("%{public}s, end.", __func__); return result; } @@ -1680,15 +1683,16 @@ napi_value NAPI_GetContextCommon(napi_env env, napi_callback_info info, AbilityT asyncCallbackInfo->errCode = NAPI_ERR_NO_ERROR; asyncCallbackInfo->abilityType = abilityType; napi_value ret = GetContextWrap(env, info, asyncCallbackInfo); + + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + if (ret == nullptr) { - HILOG_ERROR("%{public}s ret == nullptr", __func__); - if (asyncCallbackInfo != nullptr) { - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - } ret = WrapVoidToJS(env); + HILOG_ERROR("%{public}s ret == nullptr", __func__); + } else { + HILOG_INFO("%{public}s, end.", __func__); } - HILOG_INFO("%{public}s, end.", __func__); return ret; } @@ -2166,6 +2170,36 @@ napi_value NAPI_GetAbilityNameCommon(napi_env env, napi_callback_info info, Abil return ret; } +void UnwrapAbilityStartSettingForNumber(napi_env env, const std::string key, napi_value param, + AAFwk::AbilityStartSetting &setting) +{ + int32_t natValue32 = 0; + double natValueDouble = 0.0; + bool isReadValue32 = false; + bool isReadDouble = false; + if (napi_get_value_int32(env, param, &natValue32) == napi_ok) { + HILOG_INFO("%{public}s called. Property value=%{public}d.", __func__, natValue32); + isReadValue32 = true; + } + + if (napi_get_value_double(env, param, &natValueDouble) == napi_ok) { + HILOG_INFO("%{public}s called. Property value=%{public}lf.", __func__, natValueDouble); + isReadDouble = true; + } + + if (isReadValue32 && isReadDouble) { + if (abs(natValueDouble - natValue32 * 1.0) > 0.0) { + setting.AddProperty(key, std::to_string(natValueDouble)); + } else { + setting.AddProperty(key, std::to_string(natValue32)); + } + } else if (isReadValue32) { + setting.AddProperty(key, std::to_string(natValue32)); + } else if (isReadDouble) { + setting.AddProperty(key, std::to_string(natValueDouble)); + } +} + bool UnwrapAbilityStartSetting(napi_env env, napi_value param, AAFwk::AbilityStartSetting &setting) { HILOG_INFO("%{public}s called.", __func__); @@ -2206,34 +2240,9 @@ bool UnwrapAbilityStartSetting(napi_env env, napi_value param, AAFwk::AbilitySta setting.AddProperty(strProName, std::to_string(natValue)); break; } - case napi_number: { - int32_t natValue32 = 0; - double natValueDouble = 0.0; - bool isReadValue32 = false; - bool isReadDouble = false; - if (napi_get_value_int32(env, jsProValue, &natValue32) == napi_ok) { - HILOG_INFO("%{public}s called. Property value=%{public}d.", __func__, natValue32); - isReadValue32 = true; - } - - if (napi_get_value_double(env, jsProValue, &natValueDouble) == napi_ok) { - HILOG_INFO("%{public}s called. Property value=%{public}lf.", __func__, natValueDouble); - isReadDouble = true; - } - - if (isReadValue32 && isReadDouble) { - if (abs(natValueDouble - natValue32 * 1.0) > 0.0) { - setting.AddProperty(strProName, std::to_string(natValueDouble)); - } else { - setting.AddProperty(strProName, std::to_string(natValue32)); - } - } else if (isReadValue32) { - setting.AddProperty(strProName, std::to_string(natValue32)); - } else if (isReadDouble) { - setting.AddProperty(strProName, std::to_string(natValueDouble)); - } + case napi_number: + UnwrapAbilityStartSettingForNumber(env, strProName, jsProValue, setting); break; - } default: break; } @@ -2789,7 +2798,11 @@ napi_value ConnectAbilityWrap(napi_env env, napi_callback_info info, ConnectAbil key.id = connectAbilityCB->id; key.want = connectAbilityCB->want; connects_.emplace(key, conn); - serialNumber_ < INT64_MAX ? serialNumber_++ : serialNumber_ = 0; + if (serialNumber_ < INT64_MAX) { + serialNumber_++; + } else { + serialNumber_ = 0; + } HILOG_INFO("%{public}s not find connection, make new one:%{public}p.", __func__, conn.GetRefPtr()); } HILOG_INFO("%{public}s id:%{public}" PRId64, __func__, connectAbilityCB->id); @@ -3132,6 +3145,41 @@ void NAPIAbilityConnection::SetDisconnectCBRef(const napi_ref &ref) disconnectRef_ = ref; } +void UvWorkOnAbilityConnectDone(uv_work_t *work, int status) +{ + HILOG_INFO("UvWorkOnAbilityConnectDone, uv_queue_work"); + // JS Thread + ConnectAbilityCB *connectAbilityCB = static_cast(work->data); + napi_value result[ARGS_TWO] = {0}; + result[PARAM0] = + WrapElementName(connectAbilityCB->cbBase.cbInfo.env, connectAbilityCB->abilityConnectionCB.elementName); + napi_value jsRemoteObject = NAPI_ohos_rpc_CreateJsRemoteObject( + connectAbilityCB->cbBase.cbInfo.env, connectAbilityCB->abilityConnectionCB.connection); + result[PARAM1] = jsRemoteObject; + + napi_value callback = 0; + napi_value undefined = 0; + napi_get_undefined(connectAbilityCB->cbBase.cbInfo.env, &undefined); + napi_value callResult = 0; + napi_get_reference_value( + connectAbilityCB->cbBase.cbInfo.env, connectAbilityCB->cbBase.cbInfo.callback, &callback); + + napi_call_function( + connectAbilityCB->cbBase.cbInfo.env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); + if (connectAbilityCB->cbBase.cbInfo.callback != nullptr) { + napi_delete_reference(connectAbilityCB->cbBase.cbInfo.env, connectAbilityCB->cbBase.cbInfo.callback); + } + if (connectAbilityCB != nullptr) { + delete connectAbilityCB; + connectAbilityCB = nullptr; + } + if (work != nullptr) { + delete work; + work = nullptr; + } + HILOG_INFO("UvWorkOnAbilityConnectDone, uv_queue_work end"); +} + void NAPIAbilityConnection::OnAbilityConnectDone( const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) { @@ -3170,44 +3218,7 @@ void NAPIAbilityConnection::OnAbilityConnectDone( connectAbilityCB->abilityConnectionCB.connection = remoteObject; work->data = (void *)connectAbilityCB; - int rev = uv_queue_work( - loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - HILOG_INFO("OnAbilityConnectDone, uv_queue_work"); - // JS Thread - ConnectAbilityCB *connectAbilityCB = static_cast(work->data); - napi_value result[ARGS_TWO] = {0}; - result[PARAM0] = - WrapElementName(connectAbilityCB->cbBase.cbInfo.env, connectAbilityCB->abilityConnectionCB.elementName); - napi_value jsRemoteObject = NAPI_ohos_rpc_CreateJsRemoteObject( - connectAbilityCB->cbBase.cbInfo.env, connectAbilityCB->abilityConnectionCB.connection); - result[PARAM1] = jsRemoteObject; - - napi_value callback = 0; - napi_value undefined = 0; - napi_get_undefined(connectAbilityCB->cbBase.cbInfo.env, &undefined); - napi_value callResult = 0; - napi_get_reference_value( - connectAbilityCB->cbBase.cbInfo.env, connectAbilityCB->cbBase.cbInfo.callback, &callback); - - napi_call_function( - connectAbilityCB->cbBase.cbInfo.env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); - if (connectAbilityCB->cbBase.cbInfo.callback != nullptr) { - napi_delete_reference(connectAbilityCB->cbBase.cbInfo.env, connectAbilityCB->cbBase.cbInfo.callback); - } - if (connectAbilityCB != nullptr) { - delete connectAbilityCB; - connectAbilityCB = nullptr; - } - if (work != nullptr) { - delete work; - work = nullptr; - } - HILOG_INFO("OnAbilityConnectDone, uv_queue_work end"); - }); - + int rev = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvWorkOnAbilityConnectDone); if (rev != 0) { if (connectAbilityCB != nullptr) { delete connectAbilityCB; @@ -3221,6 +3232,56 @@ void NAPIAbilityConnection::OnAbilityConnectDone( HILOG_INFO("%{public}s, end.", __func__); } +void UvWorkOnAbilityDisconnectDone(uv_work_t *work, int status) +{ + HILOG_INFO("UvWorkOnAbilityDisconnectDone, uv_queue_work"); + // JS Thread + ConnectAbilityCB *connectAbilityCB = static_cast(work->data); + napi_value result = nullptr; + result = + WrapElementName(connectAbilityCB->cbBase.cbInfo.env, connectAbilityCB->abilityConnectionCB.elementName); + + napi_value callback = 0; + napi_value undefined = 0; + napi_get_undefined(connectAbilityCB->cbBase.cbInfo.env, &undefined); + napi_value callResult = 0; + napi_get_reference_value( + connectAbilityCB->cbBase.cbInfo.env, connectAbilityCB->cbBase.cbInfo.callback, &callback); + + napi_call_function( + connectAbilityCB->cbBase.cbInfo.env, undefined, callback, ARGS_ONE, &result, &callResult); + if (connectAbilityCB->cbBase.cbInfo.callback != nullptr) { + napi_delete_reference(connectAbilityCB->cbBase.cbInfo.env, connectAbilityCB->cbBase.cbInfo.callback); + } + + // release connect + HILOG_INFO("UvWorkOnAbilityDisconnectDone connects_.size:%{public}zu", connects_.size()); + std::string bundleName = connectAbilityCB->abilityConnectionCB.elementName.GetBundleName(); + std::string abilityName = connectAbilityCB->abilityConnectionCB.elementName.GetAbilityName(); + auto item = std::find_if(connects_.begin(), + connects_.end(), + [bundleName, abilityName]( + const std::map>::value_type &obj) { + return (bundleName == obj.first.want.GetBundle()) && + (abilityName == obj.first.want.GetElement().GetAbilityName()); + }); + if (item != connects_.end()) { + // match bundlename && abilityname + connects_.erase(item); + HILOG_INFO("UvWorkOnAbilityDisconnectDone erase connects_.size:%{public}zu", connects_.size()); + } + + if (connectAbilityCB != nullptr) { + delete connectAbilityCB; + connectAbilityCB = nullptr; + } + if (work != nullptr) { + delete work; + work = nullptr; + } + HILOG_INFO("UvWorkOnAbilityDisconnectDone, uv_queue_work end"); +} + void NAPIAbilityConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) { HILOG_INFO("%{public}s, called.", __func__); @@ -3257,59 +3318,7 @@ void NAPIAbilityConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementNam connectAbilityCB->abilityConnectionCB.resultCode = resultCode; work->data = (void *)connectAbilityCB; - int rev = uv_queue_work( - loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - HILOG_INFO("OnAbilityDisconnectDone, uv_queue_work"); - // JS Thread - ConnectAbilityCB *connectAbilityCB = static_cast(work->data); - napi_value result = nullptr; - result = - WrapElementName(connectAbilityCB->cbBase.cbInfo.env, connectAbilityCB->abilityConnectionCB.elementName); - - napi_value callback = 0; - napi_value undefined = 0; - napi_get_undefined(connectAbilityCB->cbBase.cbInfo.env, &undefined); - napi_value callResult = 0; - napi_get_reference_value( - connectAbilityCB->cbBase.cbInfo.env, connectAbilityCB->cbBase.cbInfo.callback, &callback); - - napi_call_function( - connectAbilityCB->cbBase.cbInfo.env, undefined, callback, ARGS_ONE, &result, &callResult); - if (connectAbilityCB->cbBase.cbInfo.callback != nullptr) { - napi_delete_reference(connectAbilityCB->cbBase.cbInfo.env, connectAbilityCB->cbBase.cbInfo.callback); - } - - // release connect - HILOG_INFO("OnAbilityDisconnectDone connects_.size:%{public}zu", connects_.size()); - std::string bundleName = connectAbilityCB->abilityConnectionCB.elementName.GetBundleName(); - std::string abilityName = connectAbilityCB->abilityConnectionCB.elementName.GetAbilityName(); - auto item = std::find_if(connects_.begin(), - connects_.end(), - [bundleName, abilityName]( - const std::map>::value_type &obj) { - return (bundleName == obj.first.want.GetBundle()) && - (abilityName == obj.first.want.GetElement().GetAbilityName()); - }); - if (item != connects_.end()) { - // match bundlename && abilityname - connects_.erase(item); - HILOG_INFO("OnAbilityDisconnectDone erase connects_.size:%{public}zu", connects_.size()); - } - - if (connectAbilityCB != nullptr) { - delete connectAbilityCB; - connectAbilityCB = nullptr; - } - if (work != nullptr) { - delete work; - work = nullptr; - } - HILOG_INFO("OnAbilityDisconnectDone, uv_queue_work end"); - }); - + int rev = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvWorkOnAbilityDisconnectDone); if (rev != 0) { if (connectAbilityCB != nullptr) { delete connectAbilityCB; diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h old mode 100644 new mode 100755 index affc810409f..eb2b4b7268f --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h @@ -25,6 +25,7 @@ namespace AppExecFwk { const std::int32_t STR_MAX_SIZE = 128; napi_value *GetGlobalClassContext(void); +napi_value GetGlobalDataAbilityHelper(void); void SaveAppInfo(AppInfo_ &appInfo, const ApplicationInfo &appInfoOrg); napi_value WrapAppInfo(napi_env env, const AppInfo_ &appInfo); @@ -150,8 +151,6 @@ napi_value GetContinueAbilityOptionsInfoCommon( napi_value GetContinueAbilityOptionsReversible( const napi_env &env, const napi_value &value, ContinueAbilityOptionsInfo &info); -napi_value ConvertAbilityInfo(napi_env env, const AbilityInfo &abilityInfo); - /** * @brief Obtains the continue ability Info this application. * @@ -222,6 +221,8 @@ napi_value AcquireDataAbilityHelperWrap( */ napi_value NAPI_AcquireDataAbilityHelperCommon(napi_env env, napi_callback_info info, AbilityType abilityType); +napi_value ConvertAbilityInfo(napi_env env, const AbilityInfo &abilityInfo); + struct ConnecttionKey { Want want; int64_t id; diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.cpp b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.cpp index 743d5d180d6..a233839ca31 100755 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.cpp +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.cpp @@ -786,7 +786,7 @@ AsyncJSCallbackInfo *CreateAsyncJSCallbackInfo(napi_env env) Ability *ability = nullptr; NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); - AsyncJSCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncJSCallbackInfo{ + AsyncJSCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncJSCallbackInfo { .cbInfo.env = env, .cbInfo.callback = nullptr, .asyncWork = nullptr, diff --git a/interfaces/kits/napi/aafwk/particleAbility/native_module.cpp b/interfaces/kits/napi/aafwk/particleAbility/native_module.cpp index ef229427ace..fd1578e82d0 100755 --- a/interfaces/kits/napi/aafwk/particleAbility/native_module.cpp +++ b/interfaces/kits/napi/aafwk/particleAbility/native_module.cpp @@ -36,13 +36,15 @@ EXTERN_C_END /* * The module definition. */ -static napi_module _module = {.nm_version = 1, +static napi_module _module = { + .nm_version = 1, .nm_flags = 0, .nm_filename = nullptr, .nm_register_func = ParticleInit, .nm_modname = "ability.particleAbility", .nm_priv = ((void *)0), - .reserved = {0}}; + .reserved = {0} +}; /* * The module registration. diff --git a/interfaces/kits/napi/aafwk/wantConstant/native_module.cpp b/interfaces/kits/napi/aafwk/wantConstant/native_module.cpp index 5c076cf874b..b739218a78d 100644 --- a/interfaces/kits/napi/aafwk/wantConstant/native_module.cpp +++ b/interfaces/kits/napi/aafwk/wantConstant/native_module.cpp @@ -37,13 +37,15 @@ EXTERN_C_END /* * The module definition. */ -static napi_module _module = {.nm_version = 1, +static napi_module _module = { + .nm_version = 1, .nm_flags = 0, .nm_filename = nullptr, .nm_register_func = Init, .nm_modname = "ability.wantConstant", .nm_priv = ((void *)0), - .reserved = {0}}; + .reserved = {0} +}; /* * The module registration. diff --git a/services/abilitymgr/include/ability_manager_service.h b/services/abilitymgr/include/ability_manager_service.h index a7445d804af..38a3803ff91 100644 --- a/services/abilitymgr/include/ability_manager_service.h +++ b/services/abilitymgr/include/ability_manager_service.h @@ -576,7 +576,7 @@ private: void StartingLauncherAbility(); /** - *starting system ui abilites. + * starting system ui abilites. * */ void StartingSystemUiAbility(const SatrtUiMode &mode); diff --git a/services/abilitymgr/include/ability_record.h b/services/abilitymgr/include/ability_record.h index ddbaee7d923..cfb89faeb60 100644 --- a/services/abilitymgr/include/ability_record.h +++ b/services/abilitymgr/include/ability_record.h @@ -685,47 +685,47 @@ private: static int64_t abilityRecordId; int recordId_ = 0; // record id - Want want_; // want to start this ability - AppExecFwk::AbilityInfo abilityInfo_; // the ability info get from BMS - AppExecFwk::ApplicationInfo applicationInfo_; // the ability info get from BMS - sptr token_; // used to interact with kit and wms - std::weak_ptr missionRecord_; // mission of this ability - std::weak_ptr preAbilityRecord_; // who starts this ability record - std::weak_ptr nextAbilityRecord_; // ability that started by this ability - std::weak_ptr backAbilityRecord_; // who back to this ability record - std::unique_ptr lifecycleDeal_; // life manager used to schedule life + Want want_ = {}; // want to start this ability + AppExecFwk::AbilityInfo abilityInfo_ = {}; // the ability info get from BMS + AppExecFwk::ApplicationInfo applicationInfo_ = {}; // the ability info get from BMS + sptr token_ = {}; // used to interact with kit and wms + std::weak_ptr missionRecord_ = {}; // mission of this ability + std::weak_ptr preAbilityRecord_ = {}; // who starts this ability record + std::weak_ptr nextAbilityRecord_ = {}; // ability that started by this ability + std::weak_ptr backAbilityRecord_ = {}; // who back to this ability record + std::unique_ptr lifecycleDeal_ = {}; // life manager used to schedule life int64_t startTime_ = 0; // records first time of ability start bool isReady_ = false; // is ability thread attached? bool isWindowAttached_ = false; // Is window of this ability attached? bool isLauncherAbility_ = false; // is launcher? int64_t eventId_ = 0; // post event id static int64_t g_abilityRecordEventId_; - sptr scheduler_; // kit scheduler + sptr scheduler_ = {}; // kit scheduler bool isTerminating_ = false; // is terminating ? LifeCycleStateInfo lifeCycleStateInfo_; // target life state info - AbilityState currentState_; // current life state + AbilityState currentState_ = AbilityState::INITIAL; // current life state std::shared_ptr windowInfo_; // add window info bool isCreateByConnect_ = false; // is created by connect ability mode? bool isToEnd_ = false; // is to end ? int requestCode_ = -1; // requestCode_: >= 0 for-result start mode; <0 for normal start mode in default. - sptr schedulerDeathRecipient_; // scheduler binderDied Recipient + sptr schedulerDeathRecipient_ = {}; // scheduler binderDied Recipient /** * result_: ability starts with for-result mode will send result before being terminated. * Its caller will receive results before active. * Now we assume only one result generate when terminate. */ - std::shared_ptr result_; + std::shared_ptr result_ = {}; // service(ability) can be connected by multi-pages(abilites), so need to store this service's connections - std::list> connRecordList_; + std::list> connRecordList_ = {}; // service(ability) onConnect() return proxy of service ability - sptr connRemoteObject_; + sptr connRemoteObject_ = {}; int startId_ = 0; // service(ability) start id // page(ability) can be started by multi-pages(abilites), so need to store this ability's caller - std::list> callerList_; + std::list> callerList_ = {}; bool isUninstall_ = false; bool isForceTerminate_ = false; @@ -740,7 +740,7 @@ private: PacMap stateDatas_; // ability saved ability state data bool isRestarting_ = false; // is restarting ? bool isInMovingState_ = false; // whether complete multi window moving state. - AppState appState_; + AppState appState_ = AppState::BEGIN; }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/ams_configuration_parameter.h b/services/abilitymgr/include/ams_configuration_parameter.h index c16e10c8446..445f5c416fc 100644 --- a/services/abilitymgr/include/ams_configuration_parameter.h +++ b/services/abilitymgr/include/ams_configuration_parameter.h @@ -22,11 +22,11 @@ namespace OHOS { namespace AAFwk { namespace AmsConfig { -const std::string AMS_CONFIG_FILE_PATH{"/system/etc/ams_service_config.json"}; -const std::string SERVICE_ITEM_AMS{"service_startup_config"}; -const std::string STARTUP_LUNCHER{"startup_launcher"}; -const std::string STARTUP_STATUS_BAR{"startup_system_ui_status_bar"}; -const std::string STARTUP_NAVIGATION_BAR{"startup_system_ui_navigation_bar"}; +const std::string AMS_CONFIG_FILE_PATH {"/system/etc/ams_service_config.json"}; +const std::string SERVICE_ITEM_AMS {"service_startup_config"}; +const std::string STARTUP_LUNCHER {"startup_launcher"}; +const std::string STARTUP_STATUS_BAR {"startup_system_ui_status_bar"}; +const std::string STARTUP_NAVIGATION_BAR {"startup_system_ui_navigation_bar"}; } // namespace AmsConfig enum class SatrtUiMode { STATUSBAR = 1, NAVIGATIONBAR = 2, STARTUIBOTH = 3 }; @@ -70,10 +70,10 @@ private: int LoadAmsConfiguration(const std::string &filePath); private: - bool nonConfigFile{false}; - bool canStartLuncher{false}; - bool canStartUiStatusBar{false}; - bool canStartUiNavigationBar{false}; + bool nonConfigFile {false}; + bool canStartLuncher {false}; + bool canStartUiStatusBar {false}; + bool canStartUiNavigationBar {false}; }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_record.cpp b/services/abilitymgr/src/ability_record.cpp index 8345c501021..3ab940549b2 100644 --- a/services/abilitymgr/src/ability_record.cpp +++ b/services/abilitymgr/src/ability_record.cpp @@ -79,7 +79,6 @@ AbilityRecord::AbilityRecord(const Want &want, const AppExecFwk::AbilityInfo &ab : want_(want), abilityInfo_(abilityInfo), applicationInfo_(applicationInfo), requestCode_(requestCode) { recordId_ = abilityRecordId++; - currentState_ = AbilityState::INITIAL; } AbilityRecord::~AbilityRecord() diff --git a/services/abilitymgr/src/ability_scheduler_proxy.cpp b/services/abilitymgr/src/ability_scheduler_proxy.cpp index 8b283b98ff9..533c0545777 100644 --- a/services/abilitymgr/src/ability_scheduler_proxy.cpp +++ b/services/abilitymgr/src/ability_scheduler_proxy.cpp @@ -499,8 +499,6 @@ std::shared_ptr AbilitySchedulerProxy::Query( HILOG_ERROR("Query fail to SendRequest. err: %d", err); return nullptr; } - - HILOG_INFO("AbilitySchedulerProxy::Query end"); return OHOS::NativeRdb::ISharedResultSet::ReadFromParcel(reply); } diff --git a/services/abilitymgr/src/ability_scheduler_stub.cpp b/services/abilitymgr/src/ability_scheduler_stub.cpp index 8652c73dcdf..cddd0940eca 100644 --- a/services/abilitymgr/src/ability_scheduler_stub.cpp +++ b/services/abilitymgr/src/ability_scheduler_stub.cpp @@ -265,7 +265,8 @@ int AbilitySchedulerStub::UpdatetInner(MessageParcel &data, MessageParcel &reply HILOG_ERROR("ReadParcelable value is nullptr"); return ERR_INVALID_VALUE; } - std::shared_ptr predicates(data.ReadParcelable()); + std::shared_ptr predicates( + data.ReadParcelable()); if (predicates == nullptr) { HILOG_ERROR("ReadParcelable predicates is nullptr"); return ERR_INVALID_VALUE; @@ -285,7 +286,8 @@ int AbilitySchedulerStub::DeleteInner(MessageParcel &data, MessageParcel &reply) HILOG_ERROR("AbilitySchedulerStub uri is nullptr"); return ERR_INVALID_VALUE; } - std::shared_ptr predicates(data.ReadParcelable()); + std::shared_ptr predicates( + data.ReadParcelable()); if (predicates == nullptr) { HILOG_ERROR("ReadParcelable predicates is nullptr"); return ERR_INVALID_VALUE; @@ -310,7 +312,8 @@ int AbilitySchedulerStub::QueryInner(MessageParcel &data, MessageParcel &reply) HILOG_ERROR("fail to ReadStringVector columns"); return ERR_INVALID_VALUE; } - std::shared_ptr predicates(data.ReadParcelable()); + std::shared_ptr predicates( + data.ReadParcelable()); if (predicates == nullptr) { HILOG_ERROR("ReadParcelable predicates is nullptr"); return ERR_INVALID_VALUE; @@ -535,7 +538,6 @@ int AbilitySchedulerStub::ExecuteBatchInner(MessageParcel &data, MessageParcel & operations.push_back(dataAbilityOperation); } - //HILOG_ERROR("AbilitySchedulerStub::ExecuteBatchInner operations.size:%{public}d", operations.size()); std::vector> results = ExecuteBatch(operations); int total = results.size(); if (!reply.WriteInt32(total)) { diff --git a/services/abilitymgr/src/ability_stack_manager.cpp b/services/abilitymgr/src/ability_stack_manager.cpp index 25efc16aec0..2653933312a 100644 --- a/services/abilitymgr/src/ability_stack_manager.cpp +++ b/services/abilitymgr/src/ability_stack_manager.cpp @@ -2749,7 +2749,7 @@ int AbilityStackManager::CheckMultiWindowCondition( if (currentTopAbility && AbilityUtil::IsSystemDialogAbility( - currentTopAbility->GetAbilityInfo().bundleName, currentTopAbility->GetAbilityInfo().name)) { + currentTopAbility->GetAbilityInfo().bundleName, currentTopAbility->GetAbilityInfo().name)) { HILOG_ERROR("Top page ability is dialog type, cannot return to launcher."); return START_ABILITY_SETTING_FAILED; } diff --git a/services/abilitymgr/src/ability_start_setting.cpp b/services/abilitymgr/src/ability_start_setting.cpp index dee6862baf7..a429fcd2b58 100644 --- a/services/abilitymgr/src/ability_start_setting.cpp +++ b/services/abilitymgr/src/ability_start_setting.cpp @@ -56,7 +56,7 @@ AbilityStartSetting &AbilityStartSetting::operator=(const AbilityStartSetting &o */ std::shared_ptr AbilityStartSettingCreator() { - std::shared_ptr abilityStartSetting{new (std::nothrow) AbilityStartSetting()}; + std::shared_ptr abilityStartSetting {new (std::nothrow) AbilityStartSetting()}; return abilityStartSetting; } diff --git a/services/abilitymgr/src/data_ability_manager.cpp b/services/abilitymgr/src/data_ability_manager.cpp index d712d86833d..21c15566070 100644 --- a/services/abilitymgr/src/data_ability_manager.cpp +++ b/services/abilitymgr/src/data_ability_manager.cpp @@ -417,7 +417,7 @@ DataAbilityManager::DataAbilityRecordPtr DataAbilityManager::LoadLocked( return nullptr; } - auto insertResult = dataAbilityRecordsLoading_.insert({ name, dataAbilityRecord }); + auto insertResult = dataAbilityRecordsLoading_.insert( {name, dataAbilityRecord} ); if (!insertResult.second) { HILOG_ERROR("Failed to insert data ability to loading map."); return nullptr; diff --git a/services/abilitymgr/src/mission_record.cpp b/services/abilitymgr/src/mission_record.cpp index da0592ac902..5f324ba9869 100644 --- a/services/abilitymgr/src/mission_record.cpp +++ b/services/abilitymgr/src/mission_record.cpp @@ -334,7 +334,6 @@ void MissionRecord::Resume(const std::shared_ptr &backup) } ability->SetAbilityState(AbilityState::INITIAL); - // ability->ClearFlag(); diffAbilitys.emplace_back(ability); } diff --git a/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h b/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h index e3d2e166530..9163532c74a 100644 --- a/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h +++ b/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h @@ -77,7 +77,9 @@ public: Uri NormalizeUri(const Uri &uri) override; Uri DenormalizeUri(const Uri &uri) override; - void NotifyTopActiveAbilityChanged(bool flag) override{}; + void NotifyTopActiveAbilityChanged(bool flag) override + { + }; virtual bool ScheduleRegisterObserver(const Uri &uri, const sptr &dataObserver) override { return true; diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp index 4094428b823..ce8df131d7e 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp @@ -36,7 +36,7 @@ AppScheduler::~AppScheduler() bool AppScheduler::Init(const std::weak_ptr &callback) { HILOG_INFO("Test AppScheduler::Init()"); - if(!callback.lock()){ + if (!callback.lock()) { return false; } return true; @@ -46,7 +46,7 @@ int AppScheduler::LoadAbility(const sptr &token, const sptrGetStackManager() != nullptr); - // EXPECT_TRUE(abilityMs_->GetStackManager()->GetTopMissionRecord() != nullptr); - // EXPECT_TRUE(abilityMs_->GetStackManager()->GetTopMissionRecord()->GetTopAbilityRecord() != nullptr); - // auto launcherWant = abilityMs_->GetStackManager()->GetTopMissionRecord()->GetTopAbilityRecord()->GetWant(); + EXPECT_TRUE(abilityMs_->GetStackManager() != nullptr); + EXPECT_TRUE(abilityMs_->GetStackManager()->GetTopMissionRecord() != nullptr); + EXPECT_TRUE(abilityMs_->GetStackManager()->GetTopMissionRecord()->GetTopAbilityRecord() != nullptr); + auto launcherWant = abilityMs_->GetStackManager()->GetTopMissionRecord()->GetTopAbilityRecord()->GetWant(); - // EXPECT_EQ(abilityMs_->RemoveMission(-1), OHOS::ERR_INVALID_VALUE); + EXPECT_EQ(abilityMs_->RemoveMission(-1), OHOS::ERR_INVALID_VALUE); - // EXPECT_EQ(abilityMs_->RemoveMission(100), REMOVE_MISSION_ID_NOT_EXIST); + EXPECT_EQ(abilityMs_->RemoveMission(100), REMOVE_MISSION_ID_NOT_EXIST); - // auto topMissionId = abilityMs_->GetStackManager()->GetTopMissionRecord()->GetMissionRecordId(); - // EXPECT_EQ(abilityMs_->RemoveMission(topMissionId), REMOVE_MISSION_LAUNCHER_DENIED); - // GTEST_LOG_(INFO) << "topMissionId " << topMissionId; - // abilityMs_->GetStackManager()->GetCurrentTopAbility()->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); - // Want want; - // want.AddEntity(Want::ENTITY_HOME); - // ElementName element("device", "com.ix.music", "MusicAbility"); - // want.SetElement(element); - // auto result = StartAbility(want); - // WaitUntilTaskFinished(); - // EXPECT_EQ(OHOS::ERR_OK, result); + auto topMissionId = abilityMs_->GetStackManager()->GetTopMissionRecord()->GetMissionRecordId(); + EXPECT_EQ(abilityMs_->RemoveMission(topMissionId), REMOVE_MISSION_LAUNCHER_DENIED); + GTEST_LOG_(INFO) << "topMissionId " << topMissionId; + abilityMs_->GetStackManager()->GetCurrentTopAbility()->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); + Want want; + want.AddEntity(Want::ENTITY_HOME); + ElementName element("device", "com.ix.music", "MusicAbility"); + want.SetElement(element); + auto result = StartAbility(want); + WaitUntilTaskFinished(); + EXPECT_EQ(OHOS::ERR_OK, result); - // topMissionId = abilityMs_->GetStackManager()->GetTopMissionRecord()->GetMissionRecordId(); - // GTEST_LOG_(INFO) << "topMissionId " << topMissionId; - // EXPECT_FALSE(abilityMs_->GetStackManager()->IsLauncherMission(topMissionId)); - // EXPECT_EQ(abilityMs_->RemoveMission(topMissionId), ERR_OK); + topMissionId = abilityMs_->GetStackManager()->GetTopMissionRecord()->GetMissionRecordId(); + GTEST_LOG_(INFO) << "topMissionId " << topMissionId; + EXPECT_FALSE(abilityMs_->GetStackManager()->IsLauncherMission(topMissionId)); + EXPECT_EQ(abilityMs_->RemoveMission(topMissionId), ERR_OK); - // auto musicAbility = abilityMs_->GetStackManager()->GetCurrentTopAbility(); - // musicAbility->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); - // EXPECT_EQ(abilityMs_->RemoveMission(topMissionId), ERR_OK); + auto musicAbility = abilityMs_->GetStackManager()->GetCurrentTopAbility(); + musicAbility->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); + EXPECT_EQ(abilityMs_->RemoveMission(topMissionId), ERR_OK); - // auto result1 = StartAbility(launcherWant); - // WaitUntilTaskFinished(); - // EXPECT_EQ(OHOS::ERR_OK, result1); + auto result1 = StartAbility(launcherWant); + WaitUntilTaskFinished(); + EXPECT_EQ(OHOS::ERR_OK, result1); - // EXPECT_EQ(musicAbility->GetAbilityState(), OHOS::AAFwk::AbilityState::INACTIVATING); - // EXPECT_NE(topMissionId, abilityMs_->GetStackManager()->GetTopMissionRecord()->GetMissionRecordId()); - // musicAbility->SetAbilityState(OHOS::AAFwk::AbilityState::MOVING_BACKGROUND); + EXPECT_EQ(musicAbility->GetAbilityState(), OHOS::AAFwk::AbilityState::INACTIVATING); + EXPECT_NE(topMissionId, abilityMs_->GetStackManager()->GetTopMissionRecord()->GetMissionRecordId()); + musicAbility->SetAbilityState(OHOS::AAFwk::AbilityState::MOVING_BACKGROUND); - // EXPECT_EQ(abilityMs_->RemoveMission(topMissionId), 0); - // WaitUntilTaskFinished(); + EXPECT_EQ(abilityMs_->RemoveMission(topMissionId), 0); + WaitUntilTaskFinished(); } /* @@ -788,11 +788,6 @@ HWTEST_F(AbilityManagerServiceTest, Interface_020, TestSize.Level1) EXPECT_EQ(stackManage->GetCurrentMissionStack()->GetMissionRecordCount(), 1); EXPECT_EQ(abilityMs_->RemoveStack(1), ERR_OK); - // stackManage->GetCurrentTopAbility()->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); - // auto launcherWant = abilityMs_->GetStackManager()->GetTopMissionRecord()->GetTopAbilityRecord()->GetWant(); - // auto result2 = abilityMs_->StartAbility(launcherWant); - // WaitUntilTaskFinished(); - // EXPECT_EQ(OHOS::ERR_OK, result2); } /* diff --git a/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/ability_stack_manager_test.cpp b/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/ability_stack_manager_test.cpp index d3dcadada51..e98da047dc6 100644 --- a/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/ability_stack_manager_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_stack_manager_test/ability_stack_manager_test.cpp @@ -1840,7 +1840,6 @@ HWTEST_F(AbilityStackManagerTest, ability_stack_manager_operating_052, TestSize. EXPECT_EQ(0, result); auto musicMisionRecord = stackManager_->GetTopMissionRecord(); - // auto musicMisionRecordId = musicMisionRecord->GetMissionRecordId(); auto topAbilityRecord = stackManager_->GetCurrentTopAbility(); topAbilityRecord->SetAbilityState(OHOS::AAFwk::ACTIVE); diff --git a/services/abilitymgr/test/unittest/phone/app_scheduler_test/app_scheduler_test.cpp b/services/abilitymgr/test/unittest/phone/app_scheduler_test/app_scheduler_test.cpp index c870480684d..c0542777d59 100644 --- a/services/abilitymgr/test/unittest/phone/app_scheduler_test/app_scheduler_test.cpp +++ b/services/abilitymgr/test/unittest/phone/app_scheduler_test/app_scheduler_test.cpp @@ -172,7 +172,7 @@ HWTEST_F(AppSchedulerTest, AppScheduler_oprator_004, TestSize.Level0) */ HWTEST_F(AppSchedulerTest, AppScheduler_oprator_005, TestSize.Level0) { - // EXPECT_EQ(false, DelayedSingleton::GetInstance()->Init(appStateMock_)); + EXPECT_EQ(false, DelayedSingleton::GetInstance()->Init(appStateMock_)); } /* diff --git a/services/dataobsmgr/src/dataobs_mgr_service.cpp b/services/dataobsmgr/src/dataobs_mgr_service.cpp index 5f95f942fe3..44295c8de81 100644 --- a/services/dataobsmgr/src/dataobs_mgr_service.cpp +++ b/services/dataobsmgr/src/dataobs_mgr_service.cpp @@ -124,7 +124,7 @@ int DataObsMgrService::RegisterObserver(const Uri &uri, const sptr registerObserverFunc = + std::function registerObserverFunc = std::bind(&DataObsMgrInner::HandleRegisterObserver, dataObsMgrInner_, uri, dataObserver); dataObsMgrInner_->AtomicAddTaskCount(); @@ -160,7 +160,7 @@ int DataObsMgrService::UnregisterObserver(const Uri &uri, const sptr unregisterObserverFunc = + std::function unregisterObserverFunc = std::bind(&DataObsMgrInner::HandleUnregisterObserver, dataObsMgrInner_, uri, dataObserver); dataObsMgrInner_->AtomicAddTaskCount(); @@ -191,7 +191,7 @@ int DataObsMgrService::NotifyChange(const Uri &uri) return DATAOBS_SERVICE_TASK_LIMMIT; } - std::function notifyChangeFunc = std::bind(&DataObsMgrInner::HandleNotifyChange, dataObsMgrInner_, uri); + std::function notifyChangeFunc = std::bind(&DataObsMgrInner::HandleNotifyChange, dataObsMgrInner_, uri); dataObsMgrInner_->AtomicAddTaskCount(); bool ret = handler_->PostTask(notifyChangeFunc); diff --git a/services/dataobsmgr/test/unittest/phone/dataobs_mgr_client_test/mock_dataobs_mgr_client.h b/services/dataobsmgr/test/unittest/phone/dataobs_mgr_client_test/mock_dataobs_mgr_client.h index 09e753dd007..8d0b9dfd45e 100644 --- a/services/dataobsmgr/test/unittest/phone/dataobs_mgr_client_test/mock_dataobs_mgr_client.h +++ b/services/dataobsmgr/test/unittest/phone/dataobs_mgr_client_test/mock_dataobs_mgr_client.h @@ -41,7 +41,7 @@ std::shared_ptr MockDataObsMgrClient::GetInstance() { if (instance_ == nullptr) { if (instance_ == nullptr) { - std::shared_ptr client{new (std::nothrow) MockDataObsMgrClient()}; + std::shared_ptr client {new (std::nothrow) MockDataObsMgrClient()}; if (client != nullptr) { ((MockDataObsMgrClient *)client.get())->Connect(); } diff --git a/services/test/moduletest/ability_mgr_service_test/ability_mgr_module_test.cpp b/services/test/moduletest/ability_mgr_service_test/ability_mgr_module_test.cpp index 1a263430d8c..f22e3e32c4e 100644 --- a/services/test/moduletest/ability_mgr_service_test/ability_mgr_module_test.cpp +++ b/services/test/moduletest/ability_mgr_service_test/ability_mgr_module_test.cpp @@ -391,8 +391,9 @@ void AbilityMgrModuleTest::CheckTestRecord(std::shared_ptr &recor void AbilityMgrModuleTest::MockLoadHandlerInner(int &testId, sptr &scheduler) { auto handler = [&testId](const Want &want, bool restart, int startid) { testId = startid; }; + int counts = 3; EXPECT_CALL(*scheduler, ScheduleCommandAbility(_, _, _)) - .Times(3) + .Times(counts) .WillOnce(Invoke(handler)) .WillOnce(Invoke(handler)) .WillOnce(Invoke(handler)); diff --git a/services/test/moduletest/ability_stack_test/ability_stack_module_test.cpp b/services/test/moduletest/ability_stack_test/ability_stack_module_test.cpp index 67b85823857..726648174c3 100644 --- a/services/test/moduletest/ability_stack_test/ability_stack_module_test.cpp +++ b/services/test/moduletest/ability_stack_test/ability_stack_module_test.cpp @@ -79,8 +79,10 @@ void AbilityStackModuleTest::SetUpTestCase(void) if (!bundleObject_) { bundleObject_ = new (std::nothrow) BundleMgrService(); - OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( - OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject_); + if (bundleObject_) { + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( + OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject_); + } } } diff --git a/tools/zip/BUILD.gn b/tools/zip/BUILD.gn index 377642acffa..77de9bf92c5 100755 --- a/tools/zip/BUILD.gn +++ b/tools/zip/BUILD.gn @@ -66,7 +66,6 @@ ohos_shared_library("zlib") { "kits/napi/napi_zlib_common.cpp", "kits/napi/native_module.cpp", "src/file_path.cpp", - "src/utf.cpp", "src/zip.cpp", "src/zip_internal.cpp", "src/zip_reader.cpp", diff --git a/tools/zip/include/checked_cast.h b/tools/zip/include/checked_cast.h index 65d83e38322..8c67e4c0fb1 100755 --- a/tools/zip/include/checked_cast.h +++ b/tools/zip/include/checked_cast.h @@ -30,11 +30,11 @@ struct LookUpHelper {}; struct LookUpHelper2 : public hidden::LookUpHelper {}; // IsPtr - partial specialization only -template +template struct IsPtr { enum { value = false }; }; -template +template struct IsPtr { enum { value = true }; }; @@ -78,11 +78,11 @@ private: // implementation namespace hidden { -template +template struct checked_cast_impl; // pointer variant -template +template struct checked_cast_impl { static T cast(X &x, hidden::LookUpHelper2 const &) { @@ -113,21 +113,17 @@ struct checked_cast_impl { } }; -template +template struct checked_cast_impl { static T cast(X &x, hidden::LookUpHelper2 const &) { #ifdef CHECKED_CAST_SAFE_CONVERSATION - try { - T t = dynamic_cast(x); - - // check cross cast - if (&t != &static_cast(x)) - throw std::bad_cast(); - return t; - } catch (...) { - BAD_CHECKED_CAST(x, T); - } + T t = dynamic_cast(x); + // check cross cast + if (&t != &static_cast(x)) { + throw std::bad_cast(); + } + return t; #else return static_cast(x); #endif @@ -154,12 +150,12 @@ struct checked_cast_impl { } // namespace hidden -template +template inline T checked_cast(X &x) { return hidden::checked_cast_impl::value>::cast(x, hidden::LookUpHelper2()); } -template +template inline T checked_cast(X const &x) { return hidden::checked_cast_impl::value>::cast(x, hidden::LookUpHelper2()); diff --git a/tools/zip/include/file_path.h b/tools/zip/include/file_path.h index 007b43e4801..918a598288c 100755 --- a/tools/zip/include/file_path.h +++ b/tools/zip/include/file_path.h @@ -23,7 +23,7 @@ namespace LIBZIP { #define FILE_PATH_LITERAL(x) x #define PRFilePath "s" -template +template char (&ArraySizeHelper(T (&array)[N]))[N]; #define arraysize(array) (sizeof(ArraySizeHelper(array))) diff --git a/tools/zip/include/zip_reader.h b/tools/zip/include/zip_reader.h index 968bee301d6..4f92db6ec0c 100755 --- a/tools/zip/include/zip_reader.h +++ b/tools/zip/include/zip_reader.h @@ -49,23 +49,7 @@ public: virtual void SetTimeModified(const struct tm *modifiedTime) = 0; }; -// This class is used for reading zip files. A typical use case of this -// class is to scan entries in a zip file and extract them. The code will -// look like: -// -// ZipReader reader; -// reader.Open(zipFilePath); -// while (reader.HasMore()) { -// reader.OpenCurrentEntryInZip(); -// const base::FilePath& entry_path = -// reader.CurrentEntryInfo()->file_path(); -// auto writer = CreateFilePathWriterDelegate(extract_dir, entry_path); -// reader.ExtractCurrentEntry(writer, std::numeric_limits::max()); -// reader.AdvanceToNextEntry(); -// } -// -// For simplicity, error checking is omitted in the example code above. The -// production code should check return values from all of these functions. +// This class is used for reading zip files. class ZipReader { public: // A callback that is called when the operation is successful. @@ -73,9 +57,7 @@ public: using SuccessCallback = std::function; // A callback that is called when the operation fails. using FailureCallback = std::function; - // A callback that is called periodically during the operation with the number - // of bytes that have been processed so far. - // using ProgressCallback = base::RepeatingCallback; + using ProgressCallback = std::function; // This class represents information of an entry (file or directory) in @@ -129,11 +111,11 @@ public: private: FilePath filePath_; - int64_t originalSize_; + int64_t originalSize_ = 0; struct tm lastModified_; - bool isDirectory_; - bool isUnsafe_; - bool isEncrypted_; + bool isDirectory_ = false; + bool isUnsafe_ = false; + bool isEncrypted_ = false; DISALLOW_COPY_AND_ASSIGN(EntryInfo); }; @@ -183,20 +165,6 @@ public: // the entire file was extracted. bool ExtractCurrentEntry(WriterDelegate *delegate, uint64_t numBytesToExtract) const; - // Extracts the current entry into memory. If the current entry is a - // directory, the |output| parameter is set to the empty string. If the - // current entry is a file, the |output| parameter is filled with its - // contents. OpenCurrentEntryInZip() must be called beforehand. Note: the - // |output| parameter can be filled with a big amount of data, avoid passing - // it around by value, but by reference or pointer. Note: the value returned - // by EntryInfo::original_size() cannot be trusted, so the real size of the - // uncompressed contents can be different. |max_read_bytes| limits the ammount - // of memory used to carry the entry. Returns true if the entire content is - // read. If the entry is bigger than |max_read_bytes|, returns false and - // |output| is filled with |max_read_bytes| of data. If an error occurs, - // returns false, and |output| is set to the empty string. - // bool ExtractCurrentEntryToString(uint64_t max_read_bytes, std::string *output) const; - // Returns the current entry info. Returns NULL if the current entry is // not yet opened. OpenCurrentEntryInZip() must be called beforehand. EntryInfo *CurrentEntryInfo() const diff --git a/tools/zip/include/zip_utils.h b/tools/zip/include/zip_utils.h index de9582cfad2..b842fe810ae 100755 --- a/tools/zip/include/zip_utils.h +++ b/tools/zip/include/zip_utils.h @@ -41,7 +41,7 @@ using CALLBACK = std::function; #if !defined(DISALLOW_COPY_AND_ASSIGN) #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName &); \ - void operator=(const TypeName &) + void operator = (const TypeName &) #endif using PlatformFile = int; diff --git a/tools/zip/kits/js/@ohos.zlib.d.ts b/tools/zip/kits/js/@ohos.zlib.d.ts new file mode 100644 index 00000000000..2fc4a4dec04 --- /dev/null +++ b/tools/zip/kits/js/@ohos.zlib.d.ts @@ -0,0 +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. + */ + +import { AsyncCallback } from './basic'; + +declare namespace zlib { + //Zlib library constant definition + export enum FlushType { + FLUSH_TYPE_NO_FLUSH = 0, + FLUSH_TYPE_PARTIAL_FLUSH = 1, + FLUSH_TYPE_SYNC_FLUSH = 2, + FLUSH_TYPE_FULL_FLUSH = 3, + FLUSH_TYPE_FINISH = 4, + FLUSH_TYPE_BLOCK = 5, + FLUSH_TYPE_TREES = 6 + } + + // The return code of the compression and decompression function. + // A negative number indicates an error and a positive number indicates a normal event + // enum ErrorCode + export enum ErrorCode { + ERROR_CODE_OK = 0, + ERROR_CODE_STREAM_END = 1, + ERROR_CODE_NEED_DICT = 2, + ERROR_CODE_ERRNO = -1, + ERROR_CODE_STREAM_ERROR = -2, + ERROR_CODE_DATA_ERROR = -3, + ERROR_CODE_MEM_ERROR = -4, + ERROR_CODE_BUF_ERROR = -5, + ERROR_CODE_VERSION_ERROR = -6 + } + + //enum CompressLevel + export enum CompressLevel { + COMPRESS_LEVEL_NO_COMPRESSION = 0, + COMPRESS_LEVEL_BEST_SPEED = 1, + COMPRESS_LEVEL_BEST_COMPRESSION = 9, + COMPRESS_LEVEL_DEFAULT_COMPRESSION = -1 + } + + //enum CompressStrategy + export enum CompressStrategy { + COMPRESS_STRATEGY_DEFAULT_STRATEGY = 0, + COMPRESS_STRATEGY_FILTERED = 1, + COMPRESS_STRATEGY_HUFFMAN_ONLY = 2, + COMPRESS_STRATEGY_RLE = 3, + COMPRESS_STRATEGY_FIXED = 4 + } + + //enum MemLevel + export enum MemLevel { + MEM_LEVEL_MIN_MEMLEVEL = 1, + MEM_LEVEL_DEFAULT_MEMLEVEL = 8, + MEM_LEVEL_MAX_MEMLEVEL = 9 + } + + //zip options + interface Options { + flush?: FlushType; //corresponding zlib library macro + finishFlush?: FlushType; //corresponding zlib library macro #define Z_FINISH 4 + chunkSize?: number; //Buffer size,>64 + level?: CompressLevel; //Compression level. The compression level is a number from 0 to 9. + //0 has the fastest compression speed (compression process), 9 has the slowest compression speed, + // the largest compression rate, and 0 does not compress. + + memLevel?: MemLevel; //How much memory should be allocated for the specified internal compression state. + // Memlevel = 1 uses the minimum memory, but it is very slow, reducing the compression ratio; Memlevel = 9 uses the maximum memory to get the best speed. The default value is 8. + strategy?: CompressStrategy; //CompressStrategy + dictionary?: ArrayBuffer; //deflate/inflate only, empty dictionary by default + } + + + //The interface for compressing the specified file. There is only one callback callback interface + function zipFile(inFile:string, outFile:string, options: Options, callback: AsyncCallback): void; + function zipFile(inFile:string, outFile:string, options: Options): Promise; + + //The interface for decompressing the specified file. There is only one callback callback interface + function unzipFile(inFile:string, outFile:string, options: Options, callback: AsyncCallback): void; + function unzipFile(inFile:string, outFile:string, options: Options): Promise; +} diff --git a/tools/zip/kits/napi/napi_zlib.cpp b/tools/zip/kits/napi/napi_zlib.cpp index 06e12907f32..7f6b765750d 100755 --- a/tools/zip/kits/napi/napi_zlib.cpp +++ b/tools/zip/kits/napi/napi_zlib.cpp @@ -105,7 +105,7 @@ AsyncZipCallbackInfo *CreateZipAsyncCallbackInfo(napi_env env) HILOG_ERROR("%{public}s get_global=%{public}d err:%{public}s", __func__, ret, errorInfo->error_message); } - AsyncZipCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncZipCallbackInfo{ + AsyncZipCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncZipCallbackInfo { .asyncWork = nullptr, .aceCallback = nullptr, }; @@ -145,6 +145,11 @@ napi_value NAPI_ZipFile(napi_env env, napi_callback_info info) ret = ZipFileWrap(env, info, asyncZipCallbackInfo); if (ret == nullptr) { + + if (g_zipAceCallbackInfo!= nullptr) { + g_zipAceCallbackInfo.reset(); + g_zipAceCallbackInfo = nullptr; + } if (asyncZipCallbackInfo != nullptr) { delete asyncZipCallbackInfo; asyncZipCallbackInfo = nullptr; @@ -479,7 +484,19 @@ napi_value NAPI_UnzipFile(napi_env env, napi_callback_info info) } else { ret = UnzipFilePromise(env, asyncZipCallbackInfo); } + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if(g_unzipAceCallbackInfo!= nullptr){ + g_unzipAceCallbackInfo.reset(); + g_unzipAceCallbackInfo = nullptr; + } + if (asyncZipCallbackInfo != nullptr) { + delete asyncZipCallbackInfo; + asyncZipCallbackInfo = nullptr; + } + } + HILOG_INFO("%{public}s,end", __func__); return ret; } napi_value UnzipFilePromise(napi_env env, AsyncZipCallbackInfo *asyncZipCallbackInfo) @@ -605,7 +622,7 @@ void UnzipFilePromiseCallBack(int result) } ZipAndUnzipFileAsyncCallBack(g_unzipAceCallbackInfo, result); } -void ZipAndUnzipFileAsyncCallBackInnerJsThread(uv_work_t *work, int status) +void ZipAndUnzipFileAsyncCallBackInnerJsThread(uv_work_t *work) { // JS Thread ZlibCallbackInfo *asyncCallbackInfo = (ZlibCallbackInfo *)work->data; @@ -638,10 +655,6 @@ void ZipAndUnzipFileAsyncCallBackInnerJsThread(uv_work_t *work, int status) delete asyncCallbackInfo; asyncCallbackInfo = nullptr; } - if (work != nullptr) { - delete work; - work = nullptr; - } } void ZipAndUnzipFileAsyncCallBack(std::shared_ptr &zipAceCallbackInfo, int result) { @@ -662,6 +675,8 @@ void ZipAndUnzipFileAsyncCallBack(std::shared_ptr &zipAceCallb } ZlibCallbackInfo *asyncCallbackInfo = new (std::nothrow) ZlibCallbackInfo(); if (asyncCallbackInfo == nullptr) { + delete work; + work = nullptr; return; } asyncCallbackInfo->callbackResult = result; @@ -675,7 +690,7 @@ void ZipAndUnzipFileAsyncCallBack(std::shared_ptr &zipAceCallb [](uv_work_t *work) {}, [](uv_work_t *work, int status) { HILOG_INFO("ZipAndUnzipFileAsyncCallBack, uv_queue_work"); - ZipAndUnzipFileAsyncCallBackInnerJsThread(work, status); + ZipAndUnzipFileAsyncCallBackInnerJsThread(work); HILOG_INFO("ZipAndUnzipFileAsyncCallBack, uv_queue_work end."); }); if (rev != E_OK) { diff --git a/tools/zip/kits/napi/native_module.cpp b/tools/zip/kits/napi/native_module.cpp index f2db9797000..a9e751c508b 100755 --- a/tools/zip/kits/napi/native_module.cpp +++ b/tools/zip/kits/napi/native_module.cpp @@ -36,13 +36,15 @@ EXTERN_C_END /* * The module definition. */ -static napi_module _module = {.nm_version = 1, +static napi_module _module = { + .nm_version = 1, .nm_flags = 0, .nm_filename = nullptr, .nm_register_func = Init, .nm_modname = "zlib", .nm_priv = ((void *)0), - .reserved = {0}}; + .reserved = {0} +}; /* * The module registration. diff --git a/tools/zip/src/file_path.cpp b/tools/zip/src/file_path.cpp index e3a3b320bfc..bf85601fae8 100755 --- a/tools/zip/src/file_path.cpp +++ b/tools/zip/src/file_path.cpp @@ -125,16 +125,19 @@ FilePath FilePath::DirName() std::string::size_type letter = FindDriveLetter(newPath.path_); std::string::size_type lastSeparator = newPath.path_.find_last_of(kSeparators, std::string::npos, kSeparatorsLength - 1); + std::string::size_type one = 1; + std::string::size_type two = 2; + std::string::size_type three = 3; if (lastSeparator == std::string::npos) { // path_ is in the current directory. - newPath.path_.resize(letter + 1); - } else if (lastSeparator == letter + 1) { + newPath.path_.resize(letter + one); + } else if (lastSeparator == letter + one) { // path_ is in the root directory. - newPath.path_.resize(letter + 2); - } else if (lastSeparator == letter + 2 && IsSeparator(newPath.path_[letter + 1])) { + newPath.path_.resize(letter + two); + } else if (lastSeparator == letter + two && IsSeparator(newPath.path_[letter + one])) { // path_ is in "//" (possibly with a drive letter); leave the double // separator intact indicating alternate root. - newPath.path_.resize(letter + 3); + newPath.path_.resize(letter + three); } else if (lastSeparator != 0) { // path_ is somewhere else, trim the basename. newPath.path_.resize(lastSeparator); @@ -173,11 +176,13 @@ void FilePath::StripTrailingSeparatorsInternal() if (path_.size() == 0) { return; } - std::string::size_type start = FindDriveLetter(path_) + 2; + std::string::size_type one = 1; + std::string::size_type two = 2; + std::string::size_type start = FindDriveLetter(path_) + two; std::string::size_type lastStripped = std::string::npos; - for (std::string::size_type pos = path_.length(); pos > start && FilePath::IsSeparator(path_[pos - 1]); --pos) { - if (pos != start + 1 || lastStripped == start + 2 || !FilePath::IsSeparator(path_[start - 1])) { - path_.resize(pos - 1); + for (std::string::size_type pos = path_.length(); pos > start && FilePath::IsSeparator(path_[pos - one]); --pos) { + if (pos != start + one || lastStripped == start + two || !FilePath::IsSeparator(path_[start - one])) { + path_.resize(pos - one); lastStripped = pos; } } @@ -229,13 +234,13 @@ bool FilePath::CreateDirectory(const FilePath &fullPath) subpaths.push_back(path); lastPath = path; } - + mode_t rootMode= 0777; // Iterate through the parents and create the missing ones. for (std::vector::reverse_iterator i = subpaths.rbegin(); i != subpaths.rend(); ++i) { if (DirectoryExists(*i)) { continue; } - if (mkdir(i->Value().c_str(), 0777) == 0) { + if (mkdir(i->Value().c_str(), rootMode) == 0) { continue; } diff --git a/tools/zip/src/zip.cpp b/tools/zip/src/zip.cpp index b211562cd34..e67b2343840 100755 --- a/tools/zip/src/zip.cpp +++ b/tools/zip/src/zip.cpp @@ -124,12 +124,12 @@ bool Zip(const ZipParams ¶ms, const OPTIONS &options, CALLBACK callback) filesToAdd = &allRelativeFiles; std::list entries; if (endIsSeparator) { - entries.push_back(FileAccessor::DirectoryContentEntry(params.SrcDir(), true /* is directory*/)); + entries.push_back(FileAccessor::DirectoryContentEntry(params.SrcDir(), true)); FilterCallback filterCallback = params.GetFilterCallback(); for (auto iter = entries.begin(); iter != entries.end(); ++iter) { const FilePath &constEntryPath = iter->path; if (iter != entries.begin() && ((!params.GetIncludeHiddenFiles() && IsHiddenFile(constEntryPath)) || - (filterCallback && !filterCallback(constEntryPath)))) { + (filterCallback && !filterCallback(constEntryPath)))) { continue; } if (iter != entries.begin()) { @@ -270,7 +270,11 @@ bool Unzip(const FilePath &srcFile, const FilePath &destDir, const OPTIONS &opti destDirTemp.Value().c_str()); std::shared_ptr innerTask = std::make_shared([srcFile, destDir, options, callback]() { - UnzipParam unzipParam{.callback = callback, .filterCB = ExcludeNoFilesFilter, .logSkippedFiles = true}; + UnzipParam unzipParam{ + .callback = callback, + .filterCB = ExcludeNoFilesFilter, + .logSkippedFiles = true + }; UnzipWithFilterCallback(srcFile, destDir, options, unzipParam); }); diff --git a/tools/zip/src/zip_internal.cpp b/tools/zip/src/zip_internal.cpp index 4e2ee343f3e..3674e618134 100755 --- a/tools/zip/src/zip_internal.cpp +++ b/tools/zip/src/zip_internal.cpp @@ -32,8 +32,9 @@ struct tm GetTmDataFromTickts(int64_t sec) if (tmNow == nullptr) { return now; } + int baseYeaar = 1900; now = *tmNow; - now.tm_year += 1900; + now.tm_year += baseYeaar; now.tm_mon += 1; return now; } @@ -88,7 +89,7 @@ void FillFdOpenFileFunc(zlib_filefunc_def *pzlibFilefuncDef, PlatformFile fd) // a zip archive stored in memory directly. The following I/O API functions // expect their opaque parameters refer to this struct. struct ZipBuffer { - const char *data; // weak + const char *data; size_t length; size_t offset; }; @@ -99,7 +100,7 @@ struct ZipBuffer { // given opaque parameter and returns it because this parameter stores all // information needed for uncompressing data. (This function does not support // writing compressed data and it returns NULL for this case.) -void *OpenZipBuffer(void *opaque, const char * /*filename*/, int mode) +void *OpenZipBuffer(void *opaque, const char *, int mode) { uint32_t modeInner = static_cast(mode); if ((modeInner & ZLIB_FILEFUNC_MODE_READWRITEFILTER) != ZLIB_FILEFUNC_MODE_READ) { @@ -107,15 +108,16 @@ void *OpenZipBuffer(void *opaque, const char * /*filename*/, int mode) return NULL; } ZipBuffer *buffer = static_cast(opaque); - if (!buffer || !buffer->data || !buffer->length) + if (!buffer || !buffer->data || !buffer->length) { return NULL; + } buffer->offset = 0; return opaque; } // Reads compressed data from the specified stream. This function copies data // refered by the opaque parameter and returns the size actually copied. -uLong ReadZipBuffer(void *opaque, void * /*stream*/, void *buf, uLong size) +uLong ReadZipBuffer(void *opaque, void *, void *buf, uLong size) { ZipBuffer *buffer = static_cast(opaque); if (buffer == nullptr) { @@ -128,8 +130,9 @@ uLong ReadZipBuffer(void *opaque, void * /*stream*/, void *buf, uLong size) } size_t remaining_bytes = buffer->length - buffer->offset; - if (!buffer || !buffer->data || !remaining_bytes) + if (!buffer || !buffer->data || !remaining_bytes) { return 0; + } size = std::min(size, static_cast(remaining_bytes)); if (memcpy_s(buf, size, &buffer->data[buffer->offset], size) != EOK) { return 0; @@ -140,27 +143,29 @@ uLong ReadZipBuffer(void *opaque, void * /*stream*/, void *buf, uLong size) // Writes compressed data to the stream. This function always returns zero // because this implementation is only for reading compressed data. -uLong WriteZipBuffer(void * /*opaque*/, void * /*stream*/, const void * /*buf*/, uLong /*size*/) +uLong WriteZipBuffer(void *, void *, const void *, uLong) { HILOG_INFO("%{public}s called.", __func__); return 0; } // Returns the offset from the beginning of the data. -long GetOffsetOfZipBuffer(void *opaque, void * /*stream*/) +long GetOffsetOfZipBuffer(void *opaque, void *) { ZipBuffer *buffer = static_cast(opaque); - if (!buffer) + if (!buffer) { return -1; + } return static_cast(buffer->offset); } // Moves the current offset to the specified position. -long SeekZipBuffer(void *opaque, void * /*stream*/, uLong offset, int origin) +long SeekZipBuffer(void *opaque, void *, uLong offset, int origin) { ZipBuffer *buffer = static_cast(opaque); - if (!buffer) + if (!buffer) { return -1; + } if (origin == ZLIB_FILEFUNC_SEEK_CUR) { buffer->offset = std::min(buffer->offset + static_cast(offset), buffer->length); return 0; @@ -181,16 +186,17 @@ long SeekZipBuffer(void *opaque, void * /*stream*/, uLong offset, int origin) // uncompressing data. This function deletes the ZipBuffer object referred by // the opaque parameter since zlib deletes the unzFile object and it does not // use this object any longer. -int CloseZipBuffer(void *opaque, void * /*stream*/) +int CloseZipBuffer(void *opaque, void *) { - if (opaque) + if (opaque) { free(opaque); + } return 0; } // Returns the last error happened when reading or writing data. This function // always returns zero, which means there are not any errors. -int GetErrorOfZipBuffer(void * /*opaque*/, void * /*stream*/) +int GetErrorOfZipBuffer(void *, void *) { return 0; } @@ -226,9 +232,9 @@ unzFile OpenFdForUnzipping(int zipFD) // static unzFile PrepareMemoryForUnzipping(const std::string &data) { - if (data.empty()) + if (data.empty()) { return NULL; - + } ZipBuffer *buffer = static_cast(malloc(sizeof(ZipBuffer))); if (!buffer) return NULL; @@ -253,7 +259,7 @@ zipFile OpenForZipping(const std::string &fileNameUtf8, int appendFlag) zlib_filefunc_def *zipFuncPtrs = NULL; return zipOpen2(fileNameUtf8.c_str(), appendFlag, - NULL, // global comment + NULL, zipFuncPtrs); } @@ -272,24 +278,24 @@ bool ZipOpenNewFileInZip( zip_fileinfo fileInfo = {}; TimeToZipFileInfo(lastModifiedTime, fileInfo); - if (ZIP_OK != zipOpenNewFileInZip4(zipFile, // file - strPath.c_str(), // filename - &fileInfo, // zip_fileinfo - NULL, // extrafield_local, - 0u, // size_extrafield_local - NULL, // extrafield_global - 0u, // size_extrafield_global - NULL, // comment - Z_DEFLATED, // method - (int)options.level, // level:default Z_DEFAULT_COMPRESSION - 0, // raw - -MAX_WBITS, // windowBits - (int)options.memLevel, // memLevel: default DEF_MEM_LEVEL - (int)options.strategy, // strategy:default Z_DEFAULT_STRATEGY - NULL, // password - 0, // crcForCrypting - 0, // versionMadeBy - LANGUAGE_ENCODING_FLAG)) { // flagBase + if (ZIP_OK != zipOpenNewFileInZip4(zipFile, // file + strPath.c_str(), // filename + &fileInfo, // zip_fileinfo + NULL, // extrafield_local, + 0u, // size_extrafield_local + NULL, // extrafield_global + 0u, // size_extrafield_global + NULL, // comment + Z_DEFLATED, // method + (int)options.level, // level:default Z_DEFAULT_COMPRESSION + 0, // raw + -MAX_WBITS, // windowBits + (int)options.memLevel, // memLevel: default DEF_MEM_LEVEL + (int)options.strategy, // strategy:default Z_DEFAULT_STRATEGY + NULL, // password + 0, // crcForCrypting + 0, // versionMadeBy + LANGUAGE_ENCODING_FLAG)) { // flagBase return false; } return true; diff --git a/tools/zip/src/zip_reader.cpp b/tools/zip/src/zip_reader.cpp index 4d75383f7fa..af5677577d8 100755 --- a/tools/zip/src/zip_reader.cpp +++ b/tools/zip/src/zip_reader.cpp @@ -78,7 +78,6 @@ bool ZipReader::Open(FilePath &zipFilePath) // Use of "Unsafe" function does not look good, but there is no way to do // this safely on Linux. See file_util.h for details. - // zipFile_ = internal::OpenForUnzipping(zipFilePath.AsUTF8Unsafe()); std::string zipfile = zipFilePath.Value(); zipFile_ = OpenForUnzipping(zipfile); if (zipFile_ == nullptr) { diff --git a/tools/zip/src/zip_utils.cpp b/tools/zip/src/zip_utils.cpp index 67a84b37046..e3a141c352a 100755 --- a/tools/zip/src/zip_utils.cpp +++ b/tools/zip/src/zip_utils.cpp @@ -51,7 +51,8 @@ struct tm *GetCurrentSystemTime(void) if (time == nullptr) { return nullptr; } - time->tm_mday = time->tm_mday + 1900; + int baseYear = 1900; + time->tm_mday = time->tm_mday + baseYear; time->tm_mday = time->tm_mon + 1; return time; } diff --git a/tools/zip/test/unittest/testdata/zipdata/zip1/zip1-1/zip1-1.cpp b/tools/zip/test/unittest/testdata/zipdata/zip1/zip1-1/zip1-1.cpp deleted file mode 100755 index 56d25f2585e..00000000000 --- a/tools/zip/test/unittest/testdata/zipdata/zip1/zip1-1/zip1-1.cpp +++ /dev/null @@ -1,1222 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ability_context.h" -#include "ability_manager_client.h" -#include "app_log_wrapper.h" -#include "resource_manager.h" -#include "bundle_constants.h" -#include "iservice_registry.h" -#include "system_ability_definition.h" -#include "sys_mgr_client.h" - -namespace OHOS { -namespace AppExecFwk { - -int AbilityContext::ABILITY_CONTEXT_DEFAULT_REQUEST_CODE(0); - -/** - * @brief Starts a new ability. - * An ability using the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE template uses this method - * to start a specific ability. The system locates the target ability from installed abilities based on the value - * of the want parameter and then starts it. You can specify the ability to start using the want parameter. - * - * @param want Indicates the Want containing information about the target ability to start. - * - * @param requestCode Indicates the request code returned after the ability using the AbilityInfo.AbilityType.PAGE - * template is started. You can define the request code to identify the results returned by abilities. The value - * ranges from 0 to 65535. This parameter takes effect only on abilities using the AbilityInfo.AbilityType.PAGE - * template. - * - */ -void AbilityContext::StartAbility(const AAFwk::Want &want, int requestCode) -{ - APP_LOGI("AbilityContext::StartAbility called, requestCode = %{public}d", requestCode); - - AppExecFwk::AbilityType type = GetAbilityInfoType(); - if (type != AppExecFwk::AbilityType::PAGE && type != AppExecFwk::AbilityType::SERVICE) { - APP_LOGE("AbilityContext::StartAbility AbilityType = %{public}d", type); - return; - } - - if (CheckIfOperateRemote(want)) { - std::shared_ptr dms = GetDistributedSchedServiceProxy(); - if (dms != nullptr) { - AAFwk::Want innerWant; - APP_LOGI("AbilityContext::StartAbility. try to StartRemoteAbility"); - want.DumpInfo(0); - int result = dms->StartRemoteAbility(want, innerWant, requestCode); - if (result != ERR_NONE) { - APP_LOGE("AbilityContext::StartAbility start remote ability failed, the result is %{public}d", result); - } - } else { - APP_LOGE("AbilityContext::StartAbility failed. It wants to start a remote ability, but failed to get dms."); - return; - } - } else { - ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, token_, requestCode); - if (err != ERR_OK) { - APP_LOGE("AbilityContext::StartAbility is failed %{public}d", err); - } - } -} - -/** - * @brief Starts a new ability with special ability start setting. - * - * @param want Indicates the Want containing information about the target ability to start. - * @param requestCode Indicates the request code returned after the ability is started. You can define the request code - * to identify the results returned by abilities. The value ranges from 0 to 65535. - * @param abilityStartSetting Indicates the special start setting used in starting ability. - * - */ -void AbilityContext::StartAbility(const Want &want, int requestCode, const AbilityStartSetting &abilityStartSetting) -{ - AppExecFwk::AbilityType type = GetAbilityInfoType(); - if (AppExecFwk::AbilityType::PAGE != type && AppExecFwk::AbilityType::SERVICE != type) { - APP_LOGE("AbilityContext::StartAbility AbilityType = %{public}d", type); - return; - } -} - -/** - * @brief Destroys another ability you had previously started by calling Ability.startAbilityForResult - * (ohos.aafwk.content.Want, int, ohos.aafwk.ability.startsetting.AbilityStartSetting) with the same requestCode passed. - * - * @param requestCode Indicates the request code passed for starting the ability. - * - */ -void AbilityContext::TerminateAbility(int requestCode) -{ - ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->TerminateAbility(token_, requestCode); - if (err != ERR_OK) { - APP_LOGE("AbilityContext::TerminateAbility is failed %{public}d", err); - } -} - -/** - * @brief Destroys the current ability. - * - */ -void AbilityContext::TerminateAbility() -{ - std::shared_ptr info = GetAbilityInfo(); - if (info == nullptr) { - APP_LOGE("AbilityContext::TerminateAbility info == nullptr"); - return; - } - - ErrCode err = ERR_OK; - - switch (info->type) { - case AppExecFwk::AbilityType::PAGE: - err = AAFwk::AbilityManagerClient::GetInstance()->TerminateAbility(token_, resultCode_, &resultWant_); - break; - case AppExecFwk::AbilityType::SERVICE: - err = AAFwk::AbilityManagerClient::GetInstance()->TerminateAbility(token_, -1, nullptr); - break; - default: - APP_LOGE("AbilityContext::TerminateAbility info type error is %{public}d", info->type); - break; - } - - if (err != ERR_OK) { - APP_LOGE("AbilityContext::TerminateAbility is failed %{public}d", err); - } -} // namespace AppExecFwk - -/** - * @brief Obtains the bundle name of the ability that called the current ability. - * You can use the obtained bundle name to check whether the calling ability is allowed to receive the data you will - * send. If you did not use Ability.startAbilityForResult(ohos.aafwk.content.Want, int, - * ohos.aafwk.ability.startsetting.AbilityStartSetting) to start the calling ability, null is returned. - * - * @return Returns the bundle name of the calling ability; returns null if no calling ability is available. - */ -std::string AbilityContext::GetCallingBundle() -{ - return callingBundleName_; -} - -/** - * @brief Obtains the ohos.bundle.ElementName object of the current ability. - * - * @return Returns the ohos.bundle.ElementName object of the current ability. - */ -std::shared_ptr AbilityContext::GetElementName() -{ - std::shared_ptr info = GetAbilityInfo(); - if (info == nullptr) { - APP_LOGE("AbilityContext::GetElementName info == nullptr"); - return nullptr; - } - - std::shared_ptr elementName = std::make_shared(); - if (elementName == nullptr) { - APP_LOGE("AbilityContext::GetElementName elementName == nullptr"); - return nullptr; - } - elementName->SetAbilityName(info->name); - elementName->SetBundleName(info->bundleName); - elementName->SetDeviceID(info->deviceId); - return elementName; -} - -/** - * @brief Obtains the ElementName of the ability that called the current ability. - * - * @return Returns the ElementName of the calling ability; returns null if no calling ability is available. - */ -std::shared_ptr AbilityContext::GetCallingAbility() -{ - std::shared_ptr elementName = std::make_shared(); - - if (elementName == nullptr) { - APP_LOGE("AbilityContext::GetElementName elementName == nullptr"); - return nullptr; - } - elementName->SetAbilityName(callingAbilityName_); - elementName->SetBundleName(callingBundleName_); - elementName->SetDeviceID(callingDeviceId_); - return elementName; -} - -/** - * @brief Connects the current ability to an ability - * - * @param want Indicates the want containing information about the ability to connect - * - * @param conn Indicates the callback object when the target ability is connected. - * - * @return True means success and false means failure - */ -bool AbilityContext::ConnectAbility(const Want &want, const sptr &conn) -{ - APP_LOGD("AbilityContext::ConnectAbility called"); - - AppExecFwk::AbilityType type = GetAbilityInfoType(); - if (AppExecFwk::AbilityType::PAGE != type && AppExecFwk::AbilityType::SERVICE != type) { - APP_LOGE("AbilityContext::ConnectAbility AbilityType = %{public}d", type); - return false; - } - - ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(want, conn, token_); - bool value = ((ret == ERR_OK) ? true : false); - if (!value) { - APP_LOGE("AbilityContext::ConnectAbility ErrorCode = %{public}d", ret); - } - return value; -} - -/** - * - * @param conn Indicates the IAbilityConnection callback object passed by connectAbility after the connection - * is set up. The IAbilityConnection object uniquely identifies a connection between two abilities. - */ -void AbilityContext::DisconnectAbility(const sptr &conn) -{ - APP_LOGD("AbilityContext::DisconnectAbility called"); - - AppExecFwk::AbilityType type = GetAbilityInfoType(); - if (AppExecFwk::AbilityType::PAGE != type && AppExecFwk::AbilityType::SERVICE != type) { - APP_LOGE("AbilityContext::DisconnectAbility AbilityType = %{public}d", type); - return; - } - - ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(conn); - if (ret != ERR_OK) { - APP_LOGE("AbilityContext::DisconnectAbility error"); - } -} - -/** - * @brief Destroys another ability that uses the AbilityInfo.AbilityType.SERVICE template. - * The current ability using either the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE - * template can call this method to destroy another ability that uses the AbilityInfo.AbilityType.SERVICE - * template. The current ability itself can be destroyed by calling the terminateAbility() method. - * - * @param want Indicates the Want containing information about the ability to destroy. - * - * @return Returns true if the ability is destroyed successfully; returns false otherwise. - */ -bool AbilityContext::StopAbility(const AAFwk::Want &want) -{ - AppExecFwk::AbilityType type = GetAbilityInfoType(); - if (AppExecFwk::AbilityType::PAGE != type && AppExecFwk::AbilityType::SERVICE != type) { - APP_LOGE("AbilityContext::StopAbility AbilityType = %{public}d", type); - return false; - } - - ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StopServiceAbility(want); - if (err != ERR_OK) { - APP_LOGE("AbilityContext::StopAbility is failed %{public}d", err); - return false; - } - - return true; -} - -sptr AbilityContext::GetToken() -{ - return token_; -} - -/** - * @brief Obtains information about the current application. The returned application information includes basic - * information such as the application name and application permissions. - * - * @return Returns the ApplicationInfo for the current application. - */ -std::shared_ptr AbilityContext::GetApplicationInfo() const -{ - return ContextContainer::GetApplicationInfo(); -} - -/** - * @brief Obtains the application-specific cache directory on the device's internal storage. The system - * automatically deletes files from the cache directory if disk space is required elsewhere on the device. - * Older files are always deleted first. - * - * @return Returns the application-specific cache directory. - */ -std::string AbilityContext::GetCacheDir() -{ - return ContextContainer::GetCacheDir(); -} - -/** - * @brief Obtains the application-specific code-cache directory on the device's internal storage. - * The system will delete any files stored in this location both when your specific application is upgraded, - * and when the entire platform is upgraded. - * - * @return Returns the application-specific code-cache directory. - */ -std::string AbilityContext::GetCodeCacheDir() -{ - return ContextContainer::GetCodeCacheDir(); -} - -/** - * @brief Obtains the local database path. - * If the local database path does not exist, the system creates one and returns the created path. - * - * @return Returns the local database file. - */ -std::string AbilityContext::GetDatabaseDir() -{ - return ContextContainer::GetDatabaseDir(); -} - -/** - * @brief Obtains the absolute path where all private data files of this application are stored. - * - * @return Returns the absolute path storing all private data files of this application. - */ -std::string AbilityContext::GetDataDir() -{ - return ContextContainer::GetDataDir(); -} - -/** - * @brief Obtains the directory for storing custom data files of the application. - * You can use the returned File object to create and access files in this directory. The files - * can be accessible only by the current application. - * - * @param name Indicates the name of the directory to retrieve. This directory is created as part - * of your application data. - * @param mode Indicates the file operating mode. The value can be 0 or a combination of MODE_PRIVATE. - * - * @return Returns a File object for the requested directory. - */ -std::string AbilityContext::GetDir(const std::string &name, int mode) -{ - return ContextContainer::GetDir(name, mode); -} - -/** - * @brief Obtains an IBundleMgr instance. - * You can use this instance to obtain information about the application bundle. - * - * @return Returns an IBundleMgr instance. - */ -sptr AbilityContext::GetBundleManager() const -{ - return ContextContainer::GetBundleManager(); -} - -/** - * @brief Obtains the path of the package containing the current ability. The returned path contains the resources, - * source code, and configuration files of a module. - * - * @return Returns the path of the package file. - */ -std::string AbilityContext::GetBundleCodePath() -{ - return ContextContainer::GetBundleCodePath(); -} - -/** - * @brief Obtains the bundle name of the current ability. - * - * @return Returns the bundle name of the current ability. - */ -std::string AbilityContext::GetBundleName() -{ - return ContextContainer::GetBundleName(); -} - -/** - * @brief Obtains the path of the OHOS Ability Package (HAP} containing this ability. - * - * @return Returns the path of the HAP containing this ability. - */ -std::string AbilityContext::GetBundleResourcePath() -{ - return ContextContainer::GetBundleResourcePath(); -} - -/** - * @brief Obtains the Context object of the application. - * - * @return Returns the Context object of the application. - */ -std::shared_ptr AbilityContext::GetApplicationContext() const -{ - return ContextContainer::GetApplicationContext(); -} - -/** - * @brief Obtains the Context object of the application. - * - * @return Returns the Context object of the application. - */ -std::shared_ptr AbilityContext::GetContext() -{ - return ContextContainer::GetContext(); -} - -/** - * @brief Obtains an ability manager. - * The ability manager provides information about running processes and memory usage of an application. - * - * @return Returns an IAbilityManager instance. - */ -sptr AbilityContext::GetAbilityManager() -{ - return ContextContainer::GetAbilityManager(); -} - -/** - * Called when getting the ProcessInfo - * - * @return ProcessInfo - */ -std::shared_ptr AbilityContext::GetProcessInfo() const -{ - return ContextContainer::GetProcessInfo(); -} - -/** - * @brief Obtains the type of this application. - * - * @return Returns system if this application is a system application; - * returns normal if it is released in official AppGallery; - * returns other if it is released by a third-party vendor; - * returns an empty string if the query fails. - */ -std::string AbilityContext::GetAppType() -{ - return ContextContainer::GetAppType(); -} - -/** - * @brief Obtains information about the current ability. - * The returned information includes the class name, bundle name, and other information about the current ability. - * - * @return Returns the AbilityInfo object for the current ability. - */ -const std::shared_ptr AbilityContext::GetAbilityInfo() -{ - return ContextContainer::GetAbilityInfo(); -} - -/** - * @brief Obtains the HapModuleInfo object of the application. - * - * @return Returns the HapModuleInfo object of the application. - */ -std::shared_ptr AbilityContext::GetHapModuleInfo() -{ - return ContextContainer::GetHapModuleInfo(); -} - -/** - * @brief Get Current Ability Type - * - * @return Current Ability Type - */ -AppExecFwk::AbilityType AbilityContext::GetAbilityInfoType() -{ - std::shared_ptr info = GetAbilityInfo(); - if (info == nullptr) { - APP_LOGE("AbilityContext::GetAbilityInfoType info == nullptr"); - return AppExecFwk::AbilityType::UNKNOWN; - } - - return info->type; -} - -/** - * @brief Creates a Context object for an application with the given bundle name. - * - * @param bundleName Indicates the bundle name of the application. - * - * @param flag Indicates the flag for creating a Context object. It can be 0, any of - * the following values, or any combination of the following values: CONTEXT_IGNORE_SECURITY, - * CONTEXT_INCLUDE_CODE, and CONTEXT_RESTRICTED. The value 0 indicates that there is no restriction - * on creating contexts for applications. - * - * @return Returns a Context object created for the specified application. - */ -std::shared_ptr AbilityContext::CreateBundleContext(std::string bundleName, int flag) -{ - return ContextContainer::CreateBundleContext(bundleName, flag); -} - -/** - * @brief Obtains a resource manager. - * - * @return Returns a ResourceManager object. - */ -std::shared_ptr AbilityContext::GetResourceManager() const -{ - std::shared_ptr appcontext = GetApplicationContext(); - if (appcontext == nullptr) { - APP_LOGE("AbilityContext::GetResourceManager appcontext is nullptr"); - return nullptr; - } - - std::shared_ptr resourceManager = appcontext->GetResourceManager(); - if (resourceManager == nullptr) { - APP_LOGE("AbilityContext::GetResourceManager resourceManager is nullptr"); - return nullptr; - } - - return resourceManager; -} - -/** - * @brief Checks whether the current process has the given permission. - * You need to call requestPermissionsFromUser(java.lang.std::string[],int) to request a permission only - * if the current process does not have the specific permission. - * - * @param permission Indicates the permission to check. This parameter cannot be null. - * - * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; - * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. - */ -int AbilityContext::VerifySelfPermission(const std::string &permission) -{ - if (permission.empty()) { - APP_LOGE("VerifySelfPermission permission invalid"); - return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; - } - - std::string bundle_name = GetBundleName(); - if (bundle_name.empty()) { - APP_LOGE("VerifySelfPermission failed to get bundle name error"); - return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; - } - - sptr ptr = GetBundleManager(); - if (ptr == nullptr) { - APP_LOGE("VerifySelfPermission failed to get bundle manager service"); - return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; - } - - return ptr->CheckPermission(bundle_name, permission); -} - -/** - * @brief Checks whether the calling process for inter-process communication has the given permission. - * The calling process is not the current process. - * - * @param permission Indicates the permission to check. This parameter cannot be null. - * - * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the calling process has the permission; - * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. - */ -int AbilityContext::VerifyCallingPermission(const std::string &permission) -{ - if (permission.empty()) { - APP_LOGE("VerifyCallingPermission permission invalid"); - return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; - } - - std::string bundle_name = GetCallingBundle(); - if (bundle_name.empty()) { - APP_LOGE("VerifyCallingPermission failed to get bundle name by uid"); - return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; - } - - sptr ptr = GetBundleManager(); - if (ptr == nullptr) { - APP_LOGE("VerifyCallingPermission failed to get bundle manager service"); - return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; - } - return ptr->CheckPermission(bundle_name, permission); -} - -/** - * @brief Confirms with the permission management module to check whether a request prompt is required for granting a - * certain permission. You need to call the current method to check whether a prompt is required before calling - * requestPermissionsFromUser(java.lang.String[],int) to request a permission. If a prompt is not required, permission - * request will not be initiated. - * - * @param requestCode Indicates the permission to be queried. This parameter cannot be null. - * - * @return Returns true if the current application does not have the permission and the user does not turn off further - * requests; returns false if the current application already has the permission, the permission is rejected by the - * system, or the permission is denied by the user and the user has turned off further requests. - */ -bool AbilityContext::CanRequestPermission(const std::string &permission) -{ - if (permission.empty()) { - APP_LOGE("CanRequestPermission permission invalid"); - return true; - } - - std::string bundle_name = GetBundleName(); - if (bundle_name.empty()) { - APP_LOGE("CanRequestPermission failed to get bundle name error"); - return true; - } - - sptr ptr = GetBundleManager(); - if (ptr == nullptr) { - APP_LOGE("CanRequestPermission failed to get bundle manager service"); - return true; - } - - return ptr->CanRequestPermission(bundle_name, permission, 0); -} - -/** - * @brief When there is a remote call to check whether the remote has permission, otherwise check whether it has - * permission - * - * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. - * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; - * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. - */ -int AbilityContext::VerifyCallingOrSelfPermission(const std::string &permission) -{ - return VerifySelfPermission(permission); -} - -/** - * @brief Query whether the application of the specified PID and UID has been granted a certain permission - * - * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. - * @param pid Process id - * @param uid - * @return Returns 0 (IBundleManager.PERMISSION_GRANTED) if the current process has the permission; - * returns -1 (IBundleManager.PERMISSION_DENIED) otherwise. - */ -int AbilityContext::VerifyPermission(const std::string &permission, int pid, int uid) -{ - if (permission.empty()) { - APP_LOGE("VerifyPermission permission invalid"); - return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; - } - - sptr ptr = GetBundleManager(); - if (ptr == nullptr) { - APP_LOGE("VerifyPermission failed to get bundle manager service"); - return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; - } - - std::string bundle_name; - if (!ptr->GetBundleNameForUid(uid, bundle_name)) { - APP_LOGE("VerifyPermission failed to get bundle name by uid"); - return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; - } - - return ptr->CheckPermission(bundle_name, permission); -} - -void AbilityContext::GetPermissionDes(const std::string &permissionName, std::string &des) -{ - sptr ptr = GetBundleManager(); - if (ptr == nullptr) { - APP_LOGE("GetPermissionDes failed to get bundle manager service"); - return; - } - - PermissionDef permissionDef; - if (ptr->GetPermissionDef(permissionName, permissionDef)) { - des = permissionDef.description; - } -} - -/** - * @brief Requests certain permissions from the system. - * This method is called for permission request. This is an asynchronous method. When it is executed, - * the Ability.onRequestPermissionsFromUserResult(int, String[], int[]) method will be called back. - * - * @param permissions Indicates the list of permissions to be requested. This parameter cannot be null. - * @param requestCode Indicates the request code to be passed to the Ability.onRequestPermissionsFromUserResult(int, - * String[], int[]) callback method. This code cannot be a negative number. - */ -void AbilityContext::RequestPermissionsFromUser(std::vector &permissions, int requestCode) -{ - if (permissions.size() == 0) { - APP_LOGE("AbilityContext::RequestPermissionsFromUser permissions is empty"); - return; - } - - if (requestCode < 0) { - APP_LOGE("AbilityContext::RequestPermissionsFromUser requestCode should be >= 0"); - return; - } - - std::vector permissionDes; - std::string des; - for (size_t i = 0; i < permissions.size(); i++) { - des = ""; - GetPermissionDes(permissions[i], des); - permissionDes.push_back(des); - } - - AAFwk::Want want; - want.SetElementName(OHOS_REQUEST_PERMISSION_BUNDLENAME, OHOS_REQUEST_PERMISSION_ABILITY_NAME); - - want.SetParam(OHOS_REQUEST_PERMISSION_KEY, OHOS_REQUEST_PERMISSION_VALUE); - want.SetParam(OHOS_REQUEST_PERMISSIONS_LIST, permissions); - want.SetParam(OHOS_REQUEST_PERMISSIONS_DES_LIST, permissionDes); - want.SetParam(OHOS_REQUEST_CALLER_BUNDLERNAME, GetBundleName()); - - StartAbility(want, requestCode); -} - -/* @brief Deletes the specified private file associated with the application. - * - * @param fileName Indicates the name of the file to delete. The file name cannot contain path separators. - * - * @return Returns true if the file is deleted successfully; returns false otherwise. - */ -bool AbilityContext::DeleteFile(const std::string &fileName) -{ - return ContextContainer::DeleteFile(fileName); -} - -/** - * @brief Set deviceId/bundleName/abilityName of the calling ability - * - * @param deviceId deviceId of the calling ability - * - * @param deviceId bundleName of the calling ability - * - * @param deviceId abilityName of the calling ability - */ -void AbilityContext::SetCallingContext( - const std::string &deviceId, const std::string &bundleName, const std::string &abilityName) -{ - callingDeviceId_ = deviceId; - callingBundleName_ = bundleName; - callingAbilityName_ = abilityName; -} - -/** - * @brief Obtains information about the caller of this ability. - * - * @return Returns the caller information. - */ -Uri AbilityContext::GetCaller() -{ - return ContextContainer::GetCaller(); -} - -/** - * Attaches a Context object to the current ability. - * Generally, this method is called after Ability is loaded to provide the application context for the current - * ability. - * - * @param base Indicates a Context object. - */ -void AbilityContext::AttachBaseContext(const std::shared_ptr &base) -{ - ContextContainer::AttachBaseContext(base); -} - -/** - * @brief Obtains the absolute path to the application-specific cache directory - * on the primary external or shared storage device. - * - * @return Returns the absolute path to the application-specific cache directory on the external or - * shared storage device; returns null if the external or shared storage device is temporarily unavailable. - */ -std::string AbilityContext::GetExternalCacheDir() -{ - return ContextContainer::GetExternalCacheDir(); -} - -/** - * @brief Obtains the absolute path to the directory for storing files for the application on the - * primary external or shared storage device. - * - * @param type Indicates the type of the file directory to return - * - * @return Returns the absolute path to the application file directory on the external or shared storage - * device; returns null if the external or shared storage device is temporarily unavailable. - */ -std::string AbilityContext::GetExternalFilesDir(std::string &type) -{ - return ContextContainer::GetExternalFilesDir(type); -} - -/** - * @brief Obtains the directory for storing files for the application on the device's internal storage. - * - * @return Returns the application file directory. - */ -std::string AbilityContext::GetFilesDir() -{ - return ContextContainer::GetFilesDir(); -} - -/** - * @brief Obtains the absolute path which app created and will be excluded from automatic backup to remote storage. - * The returned path maybe changed if the application is moved to an adopted storage device. - * - * @return The path of the directory holding application files that will not be automatically backed up to remote - * storage. - */ -std::string AbilityContext::GetNoBackupFilesDir() -{ - return ContextContainer::GetNoBackupFilesDir(); -} - -/** - * @brief Remove permissions for all users who have access to specific permissions - * - * @param permission Indicates the permission to unauth. This parameter cannot be null. - * @param uri Indicates the URI to unauth. This parameter cannot be null. - * @param uid Indicates the UID of the unauth to check. - * - */ -void AbilityContext::UnauthUriPermission(const std::string &permission, const Uri &uri, int uid) -{ - ContextContainer::UnauthUriPermission(permission, uri, uid); -} - -/** - * @brief Obtains the distributed file path. - * If the distributed file path does not exist, the system creates one and returns the created path. This method is - * applicable only to the context of an ability rather than that of an application. - * - * @return Returns the distributed file. - */ -std::string AbilityContext::GetDistributedDir() -{ - return ContextContainer::GetDistributedDir(); -} - -/** - * @brief Sets the pattern of this Context based on the specified pattern ID. - * - * @param patternId Indicates the resource ID of the pattern to set. - */ -void AbilityContext::SetPattern(int patternId) -{ - ContextContainer::SetPattern(patternId); -} - -/** - * @brief Obtains the Context object of this ability. - * - * @return Returns the Context object of this ability. - */ -std::shared_ptr AbilityContext::GetAbilityPackageContext() -{ - return ContextContainer::GetAbilityPackageContext(); -} - -/** - * @brief Obtains the name of the current process. - * - * @return Returns the current process name. - */ -std::string AbilityContext::GetProcessName() -{ - return ContextContainer::GetProcessName(); -} - -/** - * @brief InitResourceManager - * - * @param bundleInfo BundleInfo - */ -void AbilityContext::InitResourceManager(BundleInfo &bundleInfo, std::shared_ptr &deal) -{ - ContextContainer::InitResourceManager(bundleInfo, deal); -} - -/** - * @brief Get the string of this Context based on the specified resource ID. - * - * @param resId Indicates the resource ID of the string to get. - * - * @return Returns the string of this Context. - */ -std::string AbilityContext::GetString(int resId) -{ - return ContextContainer::GetString(resId); -} - -/** - * @brief Get the string array of this Context based on the specified resource ID. - * - * @param resId Indicates the resource ID of the string array to get. - * - * @return Returns the string array of this Context. - */ -std::vector AbilityContext::GetStringArray(int resId) -{ - return ContextContainer::GetStringArray(resId); -} - -/** - * @brief Get the integer array of this Context based on the specified resource ID. - * - * @param resId Indicates the resource ID of the integer array to get. - * - * @return Returns the integer array of this Context. - */ -std::vector AbilityContext::GetIntArray(int resId) -{ - return ContextContainer::GetIntArray(resId); -} - -/** - * @brief Obtains the theme of this Context. - * - * @return theme Returns the theme of this Context. - */ -std::map AbilityContext::GetTheme() -{ - return ContextContainer::GetTheme(); -} - -/** - * @brief Sets the theme of this Context based on the specified theme ID. - * - * @param themeId Indicates the resource ID of the theme to set. - */ -void AbilityContext::SetTheme(int themeId) -{ - ContextContainer::SetTheme(themeId); -} - -/** - * @brief Obtains the pattern of this Context. - * - * @return getPattern in interface Context - */ -std::map AbilityContext::GetPattern() -{ - return ContextContainer::GetPattern(); -} - -/** - * @brief Get the color of this Context based on the specified resource ID. - * - * @param resId Indicates the resource ID of the color to get. - * - * @return Returns the color value of this Context. - */ -int AbilityContext::GetColor(int resId) -{ - return ContextContainer::GetColor(resId); -} - -/** - * @brief Obtains the theme id of this Context. - * - * @return int Returns the theme id of this Context. - */ -int AbilityContext::GetThemeId() -{ - return ContextContainer::GetThemeId(); -} - -/** - * @brief - * Destroys this Service ability if the number of times it has been started equals the number represented by the - * given {@code startId}. This method is the same as calling {@link #terminateAbility} to destroy this Service - * ability, except that this method helps you avoid destroying it if a client has requested a Service - * ability startup in {@link ohos.aafwk.ability.Ability#onCommand} but you are unaware of it. - * - * @param startId Indicates the number of startup times of this Service ability passed to - * {@link ohos.aafwk.ability.Ability#onCommand}. The {@code startId} is - * incremented by 1 every time this ability is started. For example, - * if this ability has been started for six times, the value of {@code startId} is {@code 6}. - * - * @return Returns {@code true} if the {@code startId} matches the number of startup times - * and this Service ability will be destroyed; returns {@code false} otherwise. - */ -bool AbilityContext::TerminateAbilityResult(int startId) -{ - auto abilityClient = AAFwk::AbilityManagerClient::GetInstance(); - if (abilityClient == nullptr) { - APP_LOGE("AbilityContext::TerminateAbilityResult abilityClient is nullptr"); - return false; - } - - ErrCode errval = abilityClient->TerminateAbilityResult(token_, startId); - if (errval != ERR_OK) { - APP_LOGE("AbilityContext::TerminateAbilityResult TerminateAbilityResult retval is %d", errval); - } - - return (errval == ERR_OK) ? true : false; -} - -/** - * @brief Obtains the current display orientation of this ability. - * - * @return Returns the current display orientation. - */ -int AbilityContext::GetDisplayOrientation() -{ - return ContextContainer::GetDisplayOrientation(); -} - -/** - * @brief Obtains the path storing the preference file of the application. - * If the preference file path does not exist, the system creates one and returns the created path. - * - * @return Returns the preference file path . - */ -std::string AbilityContext::GetPreferencesDir() -{ - return ContextContainer::GetPreferencesDir(); -} - -/** - * @brief Set color mode - * - * @param the value of color mode. - */ -void AbilityContext::SetColorMode(int mode) -{ - ContextContainer::SetColorMode(mode); -} - -/** - * @brief Obtains color mode. - * - * @return Returns the color mode value. - */ -int AbilityContext::GetColorMode() -{ - return ContextContainer::GetColorMode(); -} - -/** - * @brief Obtains the unique ID of the mission containing this ability. - * - * @return Returns the unique mission ID. - */ -int AbilityContext::GetMissionId() -{ - return ContextContainer::GetMissionId(); -} - -/** - * @brief Call this when your ability should be closed and the mission should be completely removed as a part of - * finishing the root ability of the mission. - */ -void AbilityContext::TerminateAndRemoveMission() -{ - ContextContainer::TerminateAndRemoveMission(); -} - -/** - * @brief Starts multiple abilities. - * - * @param wants Indicates the Want containing information array about the target ability to start. - */ -void AbilityContext::StartAbilities(const std::vector &wants) -{ - for (auto want : wants) { - StartAbility(want, ABILITY_CONTEXT_DEFAULT_REQUEST_CODE); - } -} - -/** - * @brief Checks whether this ability is the first ability in a mission. - * - * @return Returns true is first in Mission. - */ -bool AbilityContext::IsFirstInMission() -{ - auto abilityClient = AAFwk::AbilityManagerClient::GetInstance(); - if (abilityClient == nullptr) { - APP_LOGE("AbilityContext::IsFirstInMission abilityClient is nullptr"); - return false; - } - ErrCode errval = abilityClient->IsFirstInMission(token_); - if (errval != ERR_OK) { - APP_LOGE("AbilityContext::IsFirstInMission IsFirstInMission retval is %d", errval); - } - - return (errval == ERR_OK) ? true : false; -} - -/** - * @brief Check whether it wants to operate a remote ability - * - * @param want Indicates the Want containing information about the ability to start. - * - * @return return true if it wamts to operate a remote ability, ohterwise return false. - */ -bool AbilityContext::CheckIfOperateRemote(const Want &want) -{ - if (want.GetElement().GetDeviceID() != "") { - return true; - } - return false; -} - -/** - * @brief Obtains a distributedSchedService. - * - * @return Returns an IDistributedSched proxy. - */ -std::shared_ptr AbilityContext::GetDistributedSchedServiceProxy() -{ - auto remoteObject = OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(DISTRIBUTED_SCHED_SA_ID); - if (remoteObject == nullptr) { - APP_LOGE("failed to get dms service"); - return nullptr; - } - - APP_LOGI("get dms proxy success."); - std::shared_ptr proxy = nullptr; - proxy = std::make_shared(remoteObject); - return proxy; -} - -/** - * @brief Obtains a task dispatcher that is bound to the UI thread. - * - * @return Returns the task dispatcher that is bound to the UI thread. - */ -std::shared_ptr AbilityContext::GetUITaskDispatcher() -{ - return ContextContainer::GetUITaskDispatcher(); -} - -/** - * @brief Obtains a task dispatcher that is bound to the application main thread. - * - * @return Returns the task dispatcher that is bound to the application main thread. - */ -std::shared_ptr AbilityContext::GetMainTaskDispatcher() -{ - return ContextContainer::GetMainTaskDispatcher(); -} -/** - * @brief Creates a parallel task dispatcher with a specified priority. - * - * @param name Indicates the task dispatcher name. This parameter is used to locate problems. - * @param priority Indicates the priority of all tasks dispatched by the parallel task dispatcher. - * - * @return Returns a parallel task dispatcher. - */ -std::shared_ptr AbilityContext::CreateParallelTaskDispatcher( - const std::string &name, const TaskPriority &priority) -{ - return ContextContainer::CreateParallelTaskDispatcher(name, priority); -} - -/** - * @brief Creates a serial task dispatcher with a specified priority. - * - * @param name Indicates the task dispatcher name. This parameter is used to locate problems. - * @param priority Indicates the priority of all tasks dispatched by the created task dispatcher. - * - * @return Returns a serial task dispatcher. - */ -std::shared_ptr AbilityContext::CreateSerialTaskDispatcher( - const std::string &name, const TaskPriority &priority) -{ - return ContextContainer::CreateSerialTaskDispatcher(name, priority); -} - -/** - * @brief Obtains a global task dispatcher with a specified priority. - * - * @param priority Indicates the priority of all tasks dispatched by the global task dispatcher. - * - * @return Returns a global task dispatcher. - */ -std::shared_ptr AbilityContext::GetGlobalTaskDispatcher(const TaskPriority &priority) -{ - return ContextContainer::GetGlobalTaskDispatcher(priority); -} - -/** - * @brief Requires that tasks associated with a given capability token be moved to the background - * - * @param nonFirst If nonfirst is false and not the lowest ability of the mission, you cannot move mission to end - * - * @return Returns true on success, others on failure. - */ -bool AbilityContext::MoveMissionToEnd(bool nonFirst) -{ - return ContextContainer::MoveMissionToEnd(nonFirst); -} - -/** - * @brief Sets the application to start its ability in lock mission mode. - */ -void AbilityContext::LockMission() -{ - ContextContainer::LockMission(); -} - -/** - * @brief Unlocks this ability by exiting the lock mission mode. - */ -void AbilityContext::UnlockMission() -{ - ContextContainer::UnlockMission(); -} - -/** - * @brief Sets description information about the mission containing this ability. - * - * @param MissionInformation Indicates the object containing information about the - * mission. This parameter cannot be null. - * @return Returns true on success, others on failure. - */ -bool AbilityContext::SetMissionInformation(const MissionInformation &missionInformation) -{ - return ContextContainer::SetMissionInformation(missionInformation); -} - -} // namespace AppExecFwk -} // namespace OHOS diff --git a/tools/zip/test/unittest/testdata/zipdata/zip1/zip1-2/zip1-2.cpp b/tools/zip/test/unittest/testdata/zipdata/zip1/zip1-2/zip1-2.cpp deleted file mode 100755 index 9a1ecd067b4..00000000000 --- a/tools/zip/test/unittest/testdata/zipdata/zip1/zip1-2/zip1-2.cpp +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ability_handler.h" - -namespace OHOS { -namespace AppExecFwk { -AbilityHandler::AbilityHandler(const std::shared_ptr &runner, const sptr &server) - : EventHandler(runner), server_(server) -{} - -/** - * Process the event. Developers should override this method. - * - * @param event The event should be processed. - */ -void AbilityHandler::ProcessEvent([[maybe_unused]] const InnerEvent::Pointer &event) -{} -} // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file diff --git a/tools/zip/test/unittest/testdata/zipdata/zip2/zip2-1/zip2-1.cpp b/tools/zip/test/unittest/testdata/zipdata/zip2/zip2-1/zip2-1.cpp deleted file mode 100755 index 99ce20cc32f..00000000000 --- a/tools/zip/test/unittest/testdata/zipdata/zip2/zip2-1/zip2-1.cpp +++ /dev/null @@ -1,588 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ability_impl.h" -#include "app_log_wrapper.h" - -namespace OHOS { -namespace AppExecFwk { -void AbilityImpl::Init(std::shared_ptr &application, const std::shared_ptr &record, - std::shared_ptr &ability, std::shared_ptr &handler, const sptr &token, - std::shared_ptr &contextDeal) -{ - APP_LOGI("AbilityImpl::init begin"); - - if ((token == nullptr) || (application == nullptr) || (handler == nullptr) || (record == nullptr) || - ability == nullptr || contextDeal == nullptr) { - APP_LOGE("AbilityImpl::init failed, token is nullptr, application is nullptr, handler is nullptr, record is " - "nullptr, ability is nullptr, contextDeal is nullptr"); - return; - } - - token_ = record->GetToken(); - record->SetAbilityImpl(shared_from_this()); - ability_ = ability; - ability_->Init(record->GetAbilityInfo(), application, handler, token); - lifecycleState_ = AAFwk::ABILITY_STATE_INITIAL; - abilityLifecycleCallbacks_ = application; - contextDeal_ = contextDeal; - - APP_LOGI("AbilityImpl::init end"); -} - -/** - * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INACTIVE. And notifies the application - * that it belongs to of the lifecycle status. - * - * @param want The Want object to switch the life cycle. - */ -void AbilityImpl::Start(const Want &want) -{ - if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) { - APP_LOGE("AbilityImpl::Start ability_ or abilityLifecycleCallbacks_ is nullptr"); - return; - } - - APP_LOGI("AbilityImpl::Start"); - ability_->OnStart(want); - if (ability_->GetAbilityInfo()->type == AbilityType::DATA) { - lifecycleState_ = AAFwk::ABILITY_STATE_ACTIVE; - } else { - lifecycleState_ = AAFwk::ABILITY_STATE_INACTIVE; - } - - abilityLifecycleCallbacks_->OnAbilityStart(ability_); -} - -/** - * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INITIAL. And notifies the application - * that it belongs to of the lifecycle status. - * - */ -void AbilityImpl::Stop() -{ - if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) { - APP_LOGE("AbilityImpl::Stop ability_ or abilityLifecycleCallbacks_ is nullptr"); - return; - } - - APP_LOGD("AbilityImpl::Stop"); - ability_->OnStop(); - lifecycleState_ = AAFwk::ABILITY_STATE_INITIAL; - abilityLifecycleCallbacks_->OnAbilityStop(ability_); -} - -/** - * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_ACTIVE. And notifies the application - * that it belongs to of the lifecycle status. - * - */ -void AbilityImpl::Active() -{ - if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) { - APP_LOGE("AbilityImpl::Active ability_ or abilityLifecycleCallbacks_ is nullptr"); - return; - } - - APP_LOGD("AbilityImpl::Active"); - ability_->OnActive(); - - if ((lifecycleState_ == AAFwk::ABILITY_STATE_INACTIVE) && (ability_->GetAbilityInfo()->type == AbilityType::PAGE)) { - ability_->OnTopActiveAbilityChanged(true); - ability_->OnWindowFocusChanged(true); - } - - lifecycleState_ = AAFwk::ABILITY_STATE_ACTIVE; - abilityLifecycleCallbacks_->OnAbilityActive(ability_); -} - -/** - * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INACTIVE. And notifies the application - * that it belongs to of the lifecycle status. - * - */ -void AbilityImpl::Inactive() -{ - if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) { - APP_LOGE("AbilityImpl::Inactive ability_ or abilityLifecycleCallbacks_ is nullptr"); - return; - } - - APP_LOGD("AbilityImpl::Inactive"); - ability_->OnInactive(); - - if ((lifecycleState_ == AAFwk::ABILITY_STATE_ACTIVE) && (ability_->GetAbilityInfo()->type == AbilityType::PAGE)) { - ability_->OnTopActiveAbilityChanged(false); - ability_->OnWindowFocusChanged(false); - } - - lifecycleState_ = AAFwk::ABILITY_STATE_INACTIVE; - abilityLifecycleCallbacks_->OnAbilityInactive(ability_); -} - -/** - * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_INACTIVE. And notifies the application - * that it belongs to of the lifecycle status. - * - * @param want The Want object to switch the life cycle. - */ -void AbilityImpl::Foreground(const Want &want) -{ - if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) { - APP_LOGE("AbilityImpl::Foreground ability_ or abilityLifecycleCallbacks_ is nullptr"); - return; - } - - APP_LOGD("AbilityImpl::Foreground"); - ability_->OnForeground(want); - lifecycleState_ = AAFwk::ABILITY_STATE_INACTIVE; - abilityLifecycleCallbacks_->OnAbilityForeground(ability_); -} - -/** - * @brief Toggles the lifecycle status of Ability to AAFwk::ABILITY_STATE_BACKGROUND. And notifies the application - * that it belongs to of the lifecycle status. - * - */ -void AbilityImpl::Background() -{ - if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) { - APP_LOGE("AbilityImpl::Background ability_ or abilityLifecycleCallbacks_ is nullptr"); - return; - } - - APP_LOGD("AbilityImpl::Background"); - ability_->OnLeaveForeground(); - ability_->OnBackground(); - lifecycleState_ = AAFwk::ABILITY_STATE_BACKGROUND; - abilityLifecycleCallbacks_->OnAbilityBackground(ability_); -} - -/** - * @brief Save data and states of an ability when it is restored by the system. and Calling information back to Ability. - * This method should be implemented by a Page ability. - * @param instate The Want object to connect to. - * - */ -void AbilityImpl::DispatchSaveAbilityState(PacMap &outState) -{ - if (ability_ == nullptr || abilityLifecycleCallbacks_ == nullptr) { - APP_LOGE("AbilityImpl::DispatchSaveAbilityState ability_ or abilityLifecycleCallbacks_ is nullptr"); - return; - } - - APP_LOGD("AbilityImpl::DispatchSaveAbilityState"); - ability_->OnSaveAbilityState(outState); - abilityLifecycleCallbacks_->OnAbilitySaveState(outState); -} - -/** - * @brief Restores data and states of an ability when it is restored by the system. and Calling information back to - * Ability. This method should be implemented by a Page ability. - * @param instate The Want object to connect to. - * - */ -void AbilityImpl::DispatchRestoreAbilityState(const PacMap &inState) -{ - if (ability_ == nullptr) { - APP_LOGE("AbilityImpl::DispatchRestoreAbilityState ability_ is nullptr"); - return; - } - - APP_LOGD("AbilityImpl:: DispatchRestoreAbilityState"); - ability_->OnRestoreAbilityState(inState); -} - -void AbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState) -{} - -/** - * @brief Connect the ability. and Calling information back to Ability. - * - * @param want The Want object to connect to. - * - */ -sptr AbilityImpl::ConnectAbility(const Want &want) -{ - if (ability_ == nullptr) { - APP_LOGE("AbilityImpl::ConnectAbility ability_ is nullptr"); - return nullptr; - } - - APP_LOGD("AbilityImpl:: ConnectAbility"); - sptr object = ability_->OnConnect(want); - lifecycleState_ = AAFwk::ABILITY_STATE_ACTIVE; - abilityLifecycleCallbacks_->OnAbilityActive(ability_); - - return object; -} - -/** - * @brief Disconnects the connected object. - * - * @param want The Want object to disconnect to. - */ -void AbilityImpl::DisconnectAbility(const Want &want) -{ - if (ability_ == nullptr) { - APP_LOGE("AbilityImpl::DisconnectAbility ability_ is nullptr"); - return; - } - - ability_->OnDisconnect(want); -} - -/** - * @brief Command the ability. and Calling information back to Ability. - * - * @param want The Want object to command to. - * - * * @param restart Indicates the startup mode. The value true indicates that Service is restarted after being - * destroyed, and the value false indicates a normal startup. - * - * @param startId Indicates the number of times the Service ability has been started. The startId is incremented by 1 - * every time the ability is started. For example, if the ability has been started for six times, the value of startId - * is 6. - */ -void AbilityImpl::CommandAbility(const Want &want, bool restart, int startId) -{ - if (ability_ == nullptr) { - APP_LOGE("AbilityImpl::CommandAbility ability_ is nullptr"); - return; - } - - APP_LOGD("AbilityImpl:: CommandAbility"); - ability_->OnCommand(want, restart, startId); - lifecycleState_ = AAFwk::ABILITY_STATE_ACTIVE; - abilityLifecycleCallbacks_->OnAbilityActive(ability_); -} - -/** - * @brief Gets the current Ability status. - * - */ -int AbilityImpl::GetCurrentState() -{ - return lifecycleState_; -} - -/** - * @brief Execution the KeyDown callback of the ability - * @param keyCode Indicates the code of the key pressed. - * @param keyEvent Indicates the key-down event. - * - * @return Returns true if this event is handled and will not be passed further; returns false if this event is - * not handled and should be passed to other handlers. - * - */ -bool AbilityImpl::DoKeyDown(int keyCode, const KeyEvent &keyEvent) -{ - APP_LOGD("AbilityImpl::DoKeyDown called"); - return false; -} - -/** - * @brief Execution the KeyUp callback of the ability - * @param keyCode Indicates the code of the key released. - * @param keyEvent Indicates the key-up event. - * - * @return Returns true if this event is handled and will not be passed further; returns false if this event is - * not handled and should be passed to other handlers. - * - */ -bool AbilityImpl::DoKeyUp(int keyCode, const KeyEvent &keyEvent) -{ - APP_LOGD("AbilityImpl::DoKeyUp called"); - return false; -} - -/** - * @brief Called when a touch event is dispatched to this ability. The default implementation of this callback - * does nothing and returns false. - * @param touchEvent Indicates information about the touch event. - * - * @return Returns true if the event is handled; returns false otherwise. - * - */ -bool AbilityImpl::DoTouchEvent(const TouchEvent &touchEvent) -{ - APP_LOGD("AbilityImpl::DoTouchEvent called"); - return false; -} - -/** - * @brief Send the result code and data to be returned by this Page ability to the caller. - * When a Page ability is destroyed, the caller overrides the AbilitySlice#onAbilityResult(int, int, Want) method to - * receive the result set in the current method. This method can be called only after the ability has been initialized. - * - * @param requestCode Indicates the request code. - * @param resultCode Indicates the result code returned after the ability is destroyed. You can define the result code - * to identify an error. - * @param resultData Indicates the data returned after the ability is destroyed. You can define the data returned. This - * parameter can be null. - */ -void AbilityImpl::SendResult(int requestCode, int resultCode, const Want &resultData) -{ - if (ability_ == nullptr) { - APP_LOGE("AbilityImpl::SendResult ability_ is nullptr"); - return; - } - - if (resultData.HasParameter(OHOS_RESULT_PERMISSION_KEY) && resultData.HasParameter(OHOS_RESULT_PERMISSIONS_LIST) && - resultData.HasParameter(OHOS_RESULT_CALLER_BUNDLERNAME)) { - - if (resultCode > 0) { - std::vector permissions = resultData.GetStringArrayParam(OHOS_RESULT_PERMISSIONS_LIST); - std::vector grantYes = resultData.GetStringArrayParam(OHOS_RESULT_PERMISSIONS_LIST_YES); - std::vector grantNo = resultData.GetStringArrayParam(OHOS_RESULT_PERMISSIONS_LIST_NO); - std::vector grantResult; - int intOK = 0; - for (size_t i = 0; i < permissions.size(); i++) { - intOK = 0; - for (size_t j = 0; j < grantYes.size(); j++) { - if (permissions[i] == grantYes[j]) { - intOK = 1; - break; - } - } - grantResult.push_back(intOK); - } - ability_->OnRequestPermissionsFromUserResult(requestCode, permissions, grantResult); - } else { - APP_LOGE("AbilityImpl::SendResult user cancel permissions"); - } - } else { - ability_->OnAbilityResult(requestCode, resultCode, resultData); - } -} - -/** - * @brief Called when the launch mode of an ability is set to singleInstance. This happens when you re-launch - * an ability that has been at the top of the ability stack. - * - * @param want Indicates the new Want containing information about the ability. - */ -void AbilityImpl::NewWant(const Want &want) -{ - if (ability_ == nullptr) { - APP_LOGE("AbilityImpl::NewWant ability_ is nullptr"); - return; - } - ability_->SetWant(want); - ability_->OnNewWant(want); -} - -/** - * @brief Obtains the MIME types of files supported. - * - * @param uri Indicates the path of the files to obtain. - * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. - * - * @return Returns the matched MIME types. If there is no match, null is returned. - */ -std::vector AbilityImpl::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) -{ - std::vector types; - return types; -} - -/** - * @brief Opens a file in a specified remote path. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data, - * or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the file descriptor. - */ -int AbilityImpl::OpenFile(const Uri &uri, const std::string &mode) -{ - return -1; -} - -/** - * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets - * inside of their .hap. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing - * data, or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the RawFileDescriptor object containing file descriptor. - */ -int AbilityImpl::OpenRawFile(const Uri &uri, const std::string &mode) -{ - return -1; -} - -/** - * @brief Inserts a single data record into the database. - * - * @param uri Indicates the path of the data to operate. - * @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted. - * - * @return Returns the index of the inserted data record. - */ -int AbilityImpl::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) -{ - return -1; -} - -/** - * @brief Updates data records in the database. - * - * @param uri Indicates the path of data to update. - * @param value Indicates the data to update. This parameter can be null. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the number of data records updated. - */ -int AbilityImpl::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) -{ - return -1; -} - -/** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of the data to operate. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the number of data records deleted. - */ -int AbilityImpl::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) -{ - return -1; -} - -/** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of data to query. - * @param columns Indicates the columns to query. If this parameter is null, all columns are queried. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the query result. - */ -std::shared_ptr AbilityImpl::Query( - const Uri &uri, std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) -{ - return nullptr; -} - -/** - * @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be - * implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG. - * - * @param uri Indicates the URI of the data. - * - * @return Returns the MIME type that matches the data specified by uri. - */ -std::string AbilityImpl::GetType(const Uri &uri) -{ - return ""; -} - -/** - * @brief Reloads data in the database. - * - * @param uri Indicates the position where the data is to reload. This parameter is mandatory. - * @param extras Indicates the PacMap object containing the additional parameters to be passed in this call. This - * parameter can be null. If a custom Sequenceable object is put in the PacMap object and will be transferred across - * processes, you must call BasePacMap.setClassLoader(ClassLoader) to set a class loader for the custom object. - * - * @return Returns true if the data is successfully reloaded; returns false otherwise. - */ -bool AbilityImpl::Reload(const Uri &uri, const PacMap &extras) -{ - return false; -} - -/** - * @brief Inserts multiple data records into the database. - * - * @param uri Indicates the path of the data to operate. - * @param values Indicates the data records to insert. - * - * @return Returns the number of data records inserted. - */ -int AbilityImpl::BatchInsert(const Uri &uri, const std::vector &values) -{ - return -1; -} - -/** - * @brief SerUriString - */ -void AbilityImpl::SerUriString(const std::string &uri) -{ - if (contextDeal_ == nullptr) { - APP_LOGE("AbilityImpl::SerUriString contextDeal_ is nullptr"); - return; - } - contextDeal_->SerUriString(uri); -} - -/** - * @brief Set the LifeCycleStateInfo to the deal. - * - * @param info the info to set. - */ -void AbilityImpl::SetLifeCycleStateInfo(const AAFwk::LifeCycleStateInfo &info) -{ - if (contextDeal_ == nullptr) { - APP_LOGE("AbilityImpl::SetLifeCycleStateInfo contextDeal_ is nullptr"); - return; - } - contextDeal_->SetLifeCycleStateInfo(info); -} - -/** - * @brief Set deviceId/bundleName/abilityName of the calling ability - * - * @param deviceId deviceId of the calling ability - * - * @param deviceId bundleName of the calling ability - * - * @param deviceId abilityName of the calling ability - */ -void AbilityImpl::SetCallingContext( - const std::string &deviceId, const std::string &bundleName, const std::string &abilityName) -{ - if (ability_ != nullptr) { - ability_->SetCallingContext(deviceId, bundleName, abilityName); - } -} - -/* - * @brief ScheduleUpdateConfiguration, scheduling update configuration. - */ -void AbilityImpl::ScheduleUpdateConfiguration(const AAFwk::GlobalConfiguration &config) -{ - if (ability_ == nullptr) { - APP_LOGE("AbilityImpl::ScheduleUpdateConfiguration ability_ is nullptr"); - } - - Configuration configtest; - ability_->OnConfigurationUpdated(configtest); - // ability_->OnConfigurationUpdated(config); -} - -} // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file diff --git a/tools/zip/test/unittest/testdata/zipdata/zip2/zip2-2/zip2-2.cpp b/tools/zip/test/unittest/testdata/zipdata/zip2/zip2-2/zip2-2.cpp deleted file mode 100755 index b08a8bd8731..00000000000 --- a/tools/zip/test/unittest/testdata/zipdata/zip2/zip2-2/zip2-2.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ability_impl_factory.h" -#include "app_log_wrapper.h" -#include "data_ability_impl.h" -#include "page_ability_impl.h" -#include "service_ability_impl.h" - -namespace OHOS { -namespace AppExecFwk { -/** - * - * default constructor - * - */ -AbilityImplFactory::AbilityImplFactory() -{} - -/** - * - * default Destructor - * - */ -AbilityImplFactory::~AbilityImplFactory() -{} - -/** - * @brief Create impl object based on abilitytype - * - * @param type AbilityType:PAGE/SERVICE/PROVIDER - * - * @return AbilityImpl object - */ -std::shared_ptr AbilityImplFactory::MakeAbilityImplObject(const std::shared_ptr &info) -{ - if (info == nullptr) { - APP_LOGE("AbilityImplFactory::MakeAbilityImplObject is error nullptr == info "); - return nullptr; - } - - std::shared_ptr abilityImpl = nullptr; - APP_LOGI("AbilityImplFactory::MakeAbilityImplObject type:%{public}d", info->type); - - switch (info->type) { - case AppExecFwk::AbilityType::PAGE: - abilityImpl = std::make_shared(); - break; - case AppExecFwk::AbilityType::SERVICE: - abilityImpl = std::make_shared(); - break; - case AppExecFwk::AbilityType::DATA: - abilityImpl = std::make_shared(); - break; - default: - APP_LOGE("AbilityImplFactory::MakeAbilityImplObject is error"); - break; - } - - return abilityImpl; -} -} // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file -- Gitee From 98797625001543de706c7bd176f55dade3d28952 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Sun, 26 Sep 2021 18:28:33 +0800 Subject: [PATCH 2/2] delete useless files Signed-off-by: zhaoyuan17 --- tools/zip/include/utf.h | 357 --------------------------------- tools/zip/src/utf.cpp | 427 ---------------------------------------- 2 files changed, 784 deletions(-) delete mode 100755 tools/zip/include/utf.h delete mode 100755 tools/zip/src/utf.cpp diff --git a/tools/zip/include/utf.h b/tools/zip/include/utf.h deleted file mode 100755 index bd1163789fd..00000000000 --- a/tools/zip/include/utf.h +++ /dev/null @@ -1,357 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef FOUNDATION_AAFWK_STANDARD_TOOLS_UTF_H -#define FOUNDATION_AAFWK_STANDARD_TOOLS_UTF_H - -#include - -namespace OHOS { -namespace AAFwk { -namespace LIBZIP { - -using UChar32 = int32_t; -using UChar = uint16_t; -using UBool = int8_t; -/** - * This value is intended for sentinel values for APIs that - * (take or) return single code points (UChar32). - * It is outside of the Unicode code point range 0..0x10ffff. - * - * For example, a "done" or "error" value in a new API - * could be indicated with CBU_SENTINEL. - * - * ICU APIs designed before ICU 2.4 usually define service-specific "done" - * values, mostly 0xffff. - * Those may need to be distinguished from - * actual U+ffff text contents by calling functions like - * CharacterIterator::hasNext() or UnicodeString::length(). - * - * @return -1 - * @see UChar32 - */ -#define UTF_SENTINEL (-1) - -/** - * Is this code point a Unicode noncharacter? - * @param c 32-bit code point - * @return TRUE or FALSE - */ -#define UTF_IS_UNICODE_NONCHAR(c) \ - ((c) >= 0xfdd0 && ((uint32_t)(c) <= 0xfdef || ((c)&0xfffe) == 0xfffe) && (uint32_t)(c) <= 0x10ffff) - -/** - * Is c a Unicode code point value (0..U+10ffff) - * that can be assigned a character? - * - * Code points that are not characters include: - * - single surrogate code points (U+d800..U+dfff, 2048 code points) - * - the last two code points on each plane (U+__fffe and U+__ffff, 34 code points) - * - U+fdd0..U+fdef (new with Unicode 3.1, 32 code points) - * - the highest Unicode code point value is U+10ffff - * - * This means that all code points below U+d800 are character code points, - * and that boundary is tested first for performance. - * - * @param c 32-bit code point - * @return TRUE or FALSE - */ -#define UTF_IS_UNICODE_CHAR(c) \ - ((uint32_t)(c) < 0xd800 || ((uint32_t)(c) > 0xdfff && (uint32_t)(c) <= 0x10ffff && !UTF_IS_UNICODE_NONCHAR(c))) - -/** - * Is this code point a surrogate (U+d800..U+dfff)? - * @param c 32-bit code point - * @return TRUE or FALSE - */ -#define UTF_IS_SURROGATE(c) (((c)&0xfffff800) == 0xd800) - -/** - * Assuming c is a surrogate code point (U_IS_SURROGATE(c)), - * is it a lead surrogate? - * @param c 32-bit code point - * @return TRUE or FALSE - */ -#define UTF_IS_SURROGATE_LEAD(c) (((c)&0x400) == 0) - -// UTF-8 macros -// from utf8.h - -extern const uint8_t utf8_countTrailBytes[256]; - -/** - * Count the trail bytes for a UTF-8 lead byte. - * @internal - */ -#define UTF8_COUNT_TRAIL_BYTES(leadByte) (utf8_countTrailBytes[(uint8_t)leadByte]) - -/** - * Mask a UTF-8 lead byte, leave only the lower bits that form part of the code point value. - * @internal - */ -#define UTF8_MASK_LEAD_BYTE(leadByte, countTrailBytes) ((leadByte) &= (1 << (6 - (countTrailBytes))) - 1) - -/** - * Does this code unit (byte) encode a code point by itself (US-ASCII 0..0x7f)? - * @param c 8-bit code unit (byte) - * @return TRUE or FALSE - */ -#define UTF8_IS_SINGLE(c) (((c)&0x80) == 0) - -/** - * Is this code unit (byte) a UTF-8 lead byte? - * @param c 8-bit code unit (byte) - * @return TRUE or FALSE - */ -#define UTF8_IS_LEAD(c) ((uint8_t)((c)-0xc0) < 0x3e) - -/** - * Is this code unit (byte) a UTF-8 trail byte? - * @param c 8-bit code unit (byte) - * @return TRUE or FALSE - */ -#define UTF8_IS_TRAIL(c) (((c)&0xc0) == 0x80) - -/** - * How many code units (bytes) are used for the UTF-8 encoding - * of this Unicode code point? - * @param c 32-bit code point - * @return 1..4, or 0 if c is a surrogate or not a Unicode code point - */ -#define UTF8_LENGTH(c) \ - ((uint32_t)(c) <= 0x7f ? 1 \ - : ((uint32_t)(c) <= 0x7ff \ - ? 2 \ - : ((uint32_t)(c) <= 0xd7ff ? 3 \ - : ((uint32_t)(c) <= 0xdfff || (uint32_t)(c) > 0x10ffff \ - ? 0 \ - : ((uint32_t)(c) <= 0xffff ? 3 : 4))))) - -/** - * The maximum number of UTF-8 code units (bytes) per Unicode code point (U+0000..U+10ffff). - * @return 4 - */ -#define UTF8_MAX_LENGTH 4 - -/** - * Function for handling "next code point" with error-checking. - * @internal - */ -UChar32 Utf8NextCharSafeBody(const uint8_t *s, int32_t *pi, int32_t length, UChar32 c, UBool strict); - -/** - * Get a code point from a string at a code point boundary offset, - * and advance the offset to the next code point boundary. - * (Post-incrementing forward iteration.) - * "Safe" macro, checks for illegal sequences and for string boundaries. - * - * The offset may point to the lead byte of a multi-byte sequence, - * in which case the macro will read the whole sequence. - * If the offset points to a trail byte or an illegal UTF-8 sequence, then - * c is set to a negative value. - * - * @param s const uint8_t * string - * @param i string offset, i= 0x80) { \ - if (UTF8_IS_LEAD(c)) { \ - (c) = Utf8NextCharSafeBody((const uint8_t *)s, &(i), (int32_t)(length), c, -1); \ - } else { \ - (c) = UTF_SENTINEL; \ - } \ - } \ - } - -/** - * Append a code point to a string, overwriting 1 to 4 bytes. - * The offset points to the current end of the string contents - * and is advanced (post-increment). - * "Unsafe" macro, assumes a valid code point and sufficient space in the - * string. - * Otherwise, the result is undefined. - * - * @param s const uint8_t * string buffer - * @param i string offset - * @param c code point to append - * @see UTF8_APPEND - */ -#define UTF8_APPEND_UNSAFE(s, i, c) \ - { \ - if ((uint32_t)(c) <= 0x7f) { \ - (s)[(i)++] = (uint8_t)(c); \ - } else { \ - if ((uint32_t)(c) <= 0x7ff) { \ - (s)[(i)++] = (uint8_t)(((c) >> 6) | 0xc0); \ - } else { \ - if ((uint32_t)(c) <= 0xffff) { \ - (s)[(i)++] = (uint8_t)(((c) >> 12) | 0xe0); \ - } else { \ - (s)[(i)++] = (uint8_t)(((c) >> 18) | 0xf0); \ - (s)[(i)++] = (uint8_t)((((c) >> 12) & 0x3f) | 0x80); \ - } \ - (s)[(i)++] = (uint8_t)((((c) >> 6) & 0x3f) | 0x80); \ - } \ - (s)[(i)++] = (uint8_t)(((c)&0x3f) | 0x80); \ - } \ - } - -// UTF-16 macros -// from utf16.h - -/** - * Does this code unit alone encode a code point (BMP, not a surrogate)? - * @param c 16-bit code unit - * @return TRUE or FALSE - */ -#define UTF16_IS_SINGLE(c) !UTF_IS_SURROGATE(c) - -/** - * Is this code unit a lead surrogate (U+d800..U+dbff)? - * @param c 16-bit code unit - * @return TRUE or FALSE - */ -#define UTF16_IS_LEAD(c) (((c)&0xfffffc00) == 0xd800) - -/** - * Is this code unit a trail surrogate (U+dc00..U+dfff)? - * @param c 16-bit code unit - * @return TRUE or FALSE - */ -#define UTF16_IS_TRAIL(c) (((c)&0xfffffc00) == 0xdc00) - -/** - * Is this code unit a surrogate (U+d800..U+dfff)? - * @param c 16-bit code unit - * @return TRUE or FALSE - */ -#define UTF16_IS_SURROGATE(c) UTF_IS_SURROGATE(c) - -/** - * Assuming c is a surrogate code point (U16_IS_SURROGATE(c)), - * is it a lead surrogate? - * @param c 16-bit code unit - * @return TRUE or FALSE - */ -#define UTF16_IS_SURROGATE_LEAD(c) (((c)&0x400) == 0) - -/** - * Helper constant for UTF16_GET_SUPPLEMENTARY. - * @internal - */ -#define UTF16_SURROGATE_OFFSET ((0xd800 << 10UL) + 0xdc00 - 0x10000) - -/** - * Get a supplementary code point value (U+10000..U+10ffff) - * from its lead and trail surrogates. - * The result is undefined if the input values are not - * lead and trail surrogates. - * - * @param lead lead surrogate (U+d800..U+dbff) - * @param trail trail surrogate (U+dc00..U+dfff) - * @return supplementary code point (U+10000..U+10ffff) - */ -#define UTF16_GET_SUPPLEMENTARY(lead, trail) (((UChar32)(lead) << 10UL) + (UChar32)(trail)-UTF16_SURROGATE_OFFSET) - -/** - * Get the lead surrogate (0xd800..0xdbff) for a - * supplementary code point (0x10000..0x10ffff). - * @param supplementary 32-bit code point (U+10000..U+10ffff) - * @return lead surrogate (U+d800..U+dbff) for supplementary - */ -#define UTF16_LEAD(supplementary) (UChar)(((supplementary) >> 10) + 0xd7c0) - -/** - * Get the trail surrogate (0xdc00..0xdfff) for a - * supplementary code point (0x10000..0x10ffff). - * @param supplementary 32-bit code point (U+10000..U+10ffff) - * @return trail surrogate (U+dc00..U+dfff) for supplementary - */ -#define UTF16_TRAIL(supplementary) (base_icu::UChar)(((supplementary)&0x3ff) | 0xdc00) - -/** - * How many 16-bit code units are used to encode this Unicode code point? (1 or 2) - * The result is not defined if c is not a Unicode code point (U+0000..U+10ffff). - * @param c 32-bit code point - * @return 1 or 2 - */ -#define UTF16_LENGTH(c) ((uint32_t)(c) <= 0xffff ? 1 : 2) - -/** - * The maximum number of 16-bit code units per Unicode code point (U+0000..U+10ffff). - * @return 2 - */ -#define UTF16_MAX_LENGTH 2 - -/** - * Get a code point from a string at a code point boundary offset, - * and advance the offset to the next code point boundary. - * (Post-incrementing forward iteration.) - * "Safe" macro, handles unpaired surrogates and checks for string boundaries. - * - * The offset may point to the lead surrogate unit - * for a supplementary code point, in which case the macro will read - * the following trail surrogate as well. - * If the offset points to a trail surrogate or - * to a single, unpaired lead surrogate, then that itself - * will be returned as the code point. - * - * @param s const UChar * string - * @param i string offset, i> 10) + 0xd7c0); \ - (s)[(i)++] = (uint16_t)(((c)&0x3ff) | 0xdc00); \ - } \ - } - -} // namespace LIBZIP -} // namespace AAFwk -} // namespace OHOS -#endif // FOUNDATION_AAFWK_STANDARD_TOOLS_UTF_H diff --git a/tools/zip/src/utf.cpp b/tools/zip/src/utf.cpp deleted file mode 100755 index dc96040025e..00000000000 --- a/tools/zip/src/utf.cpp +++ /dev/null @@ -1,427 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "utf.h" - -namespace OHOS { -namespace AAFwk { -namespace LIBZIP { -#define UTFTF8_ERROR_VALUE_1 0x15 -#define UTFTF8_ERROR_VALUE_2 0x9f -#define UTFTF_ERROR_VALUE 0xffff -/* - * This table could be replaced on many machines by - * a few lines of assembler code using an - * "index of first 0-bit from msb" instruction and - * one or two more integer instructions. - * - * For example, on an i386, do something like - * - MOV AL, leadByte - * - NOT AL (8-bit, leave b15..b8==0..0, reverse only b7..b0) - * - MOV AH, 0 - * - BSR BX, AX (16-bit) - * - MOV AX, 6 (result) - * - JZ finish (ZF==1 if leadByte==0xff) - * - SUB AX, BX (result) - * -finish: - * (BSR: Bit Scan Reverse, scans for a 1-bit, starting from the MSB) - * - * In Unicode, all UTF-8 byte sequences with more than 4 bytes are illegal; - * lead bytes above 0xf4 are illegal. - * We keep them in this table for skipping long ISO 10646-UTF-8 sequences. - */ -const uint8_t utf8_countTrailBytes[256] = { - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - - 2, - 2, - 2, - 2, - 2, - 2, - 2, - 2, - 2, - 2, - 2, - 2, - 2, - 2, - 2, - 2, - 3, - 3, - 3, - 3, - 3, - 3, - 3, - 3, /* illegal in Unicode */ - 4, - 4, - 4, - 4, /* illegal in Unicode */ - 5, - 5, /* illegal in Unicode */ - 0, - 0 /* illegal bytes 0xfe and 0xff */ -}; - -static const UChar32 utf8_minLegal[4] = {0, 0x80, 0x800, 0x10000}; - -static const UChar32 utf8_errorValue[6] = { - UTFTF8_ERROR_VALUE_1, UTFTF8_ERROR_VALUE_2, UTFTF_ERROR_VALUE, 0x10ffff, 0x3ffffff, 0x7fffffff}; - -/* - * Handle the non-inline part of the U8_NEXT() macro and its obsolete sibling - * UTF8_NEXT_CHAR_SAFE(). - * - * The "strict" parameter controls the error behavior: - * <0 "Safe" behavior of U8_NEXT(): All illegal byte sequences yield a negative - * code point result. - * 0 Obsolete "safe" behavior of UTF8_NEXT_CHAR_SAFE(..., FALSE): - * All illegal byte sequences yield a positive code point such that this - * result code point would be encoded with the same number of bytes as - * the illegal sequence. - * >0 Obsolete "strict" behavior of UTF8_NEXT_CHAR_SAFE(..., TRUE): - * Same as the obsolete "safe" behavior, but non-characters are also treated - * like illegal sequences. - * - * The special negative (<0) value -2 is used for lenient treatment of surrogate - * code points as legal. Some implementations use this for roundtripping of - * Unicode 16-bit strings that are not well-formed UTF-16, that is, they - * contain unpaired surrogates. - * - * Note that a UBool is the same as an int8_t. - */ -UChar32 Utf8NextCharSafeBody(const uint8_t *s, int32_t *pi, int32_t length, UChar32 c, UBool strict) -{ - int32_t i = *pi; - uint8_t count = UTF8_COUNT_TRAIL_BYTES(c); - if ((i) + count <= (length)) { - uint8_t trail, illegal = 0; - - UTF8_MASK_LEAD_BYTE((c), count); - /* count==0 for illegally leading trail bytes and the illegal bytes 0xfe and 0xff */ - switch (count) { - /* each branch falls through to the next one */ - case 5: - case 4: - /* count>=4 is always illegal: no more than 3 trail bytes in Unicode's UTF-8 */ - illegal = 1; - break; - case 3: - trail = s[(i)++]; - (c) = ((c) << 6) | (trail & 0x3f); - if (c < 0x110) { - illegal |= (trail & 0xc0) ^ 0x80; - } else { - /* code point>0x10ffff, outside Unicode */ - illegal = 1; - break; - } - case 2: - trail = s[(i)++]; - (c) = ((c) << 6) | (trail & 0x3f); - illegal |= (trail & 0xc0) ^ 0x80; - case 1: - trail = s[(i)++]; - (c) = ((c) << 6) | (trail & 0x3f); - illegal |= (trail & 0xc0) ^ 0x80; - break; - case 0: - if (strict >= 0) { - return UTFTF8_ERROR_VALUE_1; - } else { - return UTF_SENTINEL; - } - /* no default branch to optimize switch() - all values are covered */ - } - - /* - * All the error handling should return a value - * that needs count bytes so that UTF8_GET_CHAR_SAFE() works right. - * - * Starting with Unicode 3.0.1, non-shortest forms are illegal. - * Starting with Unicode 3.2, surrogate code points must not be - * encoded in UTF-8, and there are no irregular sequences any more. - * - * U8_ macros (new in ICU 2.4) return negative values for error conditions. - */ - - /* correct sequence - all trail bytes have (b7..b6)==(10)? */ - /* illegal is also set if count>=4 */ - if (illegal || (c) < utf8_minLegal[count] || (UTF_IS_SURROGATE(c) && strict != -2)) { - /* error handling */ - uint8_t errorCount = count; - /* don't go beyond this sequence */ - i = *pi; - while (count > 0 && UTF8_IS_TRAIL(s[i])) { - ++(i); - --count; - } - if (strict >= 0) { - c = utf8_errorValue[errorCount - count]; - } else { - c = UTF_SENTINEL; - } - } else if ((strict) > 0 && UTF_IS_UNICODE_NONCHAR(c)) { - /* strict: forbid non-characters like U+fffe */ - c = utf8_errorValue[count]; - } - } else /* too few bytes left */ { - /* error handling */ - int32_t i0 = i; - /* don't just set (i)=(length) in case there is an illegal sequence */ - while ((i) < (length) && UTF8_IS_TRAIL(s[i])) { - ++(i); - } - if (strict >= 0) { - c = utf8_errorValue[i - i0]; - } else { - c = UTF_SENTINEL; - } - } - *pi = i; - return c; -} -} // namespace LIBZIP -} // namespace AAFwk -} // namespace OHOS -- Gitee