From ed52669970c9577f7531e3f216e4ab46c2b5202e Mon Sep 17 00:00:00 2001 From: dy_study Date: Mon, 20 Dec 2021 17:07:06 +0800 Subject: [PATCH 1/6] =?UTF-8?q?=E5=9B=9E=E5=90=88=E8=BF=90=E8=A1=8C?= =?UTF-8?q?=E7=AE=A1=E7=90=86=E7=9B=B8=E5=85=B3=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: dy_study --- OAT.xml | 2 +- .../common_perf_profile_test.cpp | 2 +- .../appexecfwk_base/include/form_constants.h | 2 +- .../appexecfwk_base/include/form_js_info.h | 2 +- .../appexecfwk_base/src/form_info.cpp | 273 ++++- .../appexecfwk_base/src/form_js_info.cpp | 4 +- .../src/form_provider_data.cpp | 4 +- .../src/form_provider_info.cpp | 3 +- interfaces/innerkits/appexecfwk_core/BUILD.gn | 1 + .../include/appmgr/app_mgr_constants.h | 1 + .../src/appmgr/ams_mgr_proxy.cpp | 4 +- .../src/appmgr/ams_mgr_stub.cpp | 14 +- .../src/appmgr/app_mgr_client.cpp | 2 +- .../src/appmgr/app_mgr_stub.cpp | 18 +- .../src/appmgr/app_scheduler_host.cpp | 17 +- .../src/appmgr/app_scheduler_proxy.cpp | 5 +- .../src/appmgr/app_service_manager.cpp | 4 +- .../src/appmgr/app_state_callback_host.cpp | 6 +- .../src/appmgr/configuration.cpp | 10 +- .../src/appmgr/process_info.cpp | 3 +- .../src/formmgr/form_mgr_proxy.cpp | 22 +- .../src/formmgr/form_mgr_stub.cpp | 2 +- .../src/formmgr/provider_connect_proxy.cpp | 2 +- .../src/formmgr/provider_connect_stub.cpp | 2 +- .../native_interface_eventhandler.cpp | 3 +- .../fmskit/native/include/form_mgr.h | 11 +- .../innerkits/fmskit/native/src/form_mgr.cpp | 18 +- interfaces/innerkits/libeventhandler/BUILD.gn | 5 +- .../libeventhandler/include/inner_event.h | 24 + interfaces/innerkits/napi/BUILD.gn | 20 + .../innerkits/napi/eventhandler/BUILD.gn | 50 + .../eventhandler/include/events_emitter.h | 89 ++ .../napi/eventhandler/src/events_emitter.cpp | 474 +++++++++ .../innerkits/napi/eventhandler/src/init.cpp | 44 + .../parallel_task_dispatcher_base.cpp | 3 +- .../src/threading/task_executor.cpp | 4 +- .../src/threading/worker_pool.cpp | 5 +- .../base_task_dispatcher_test.cpp | 9 +- .../serial_task_dispatcher_test.cpp | 6 +- .../spec_task_dispatcher_test.cpp | 16 +- .../sync_task_test/sync_task_test.cpp | 6 +- .../task_dispatcher_context_test.cpp | 4 +- .../work_thread_test/work_thread_test.cpp | 6 +- kits/BUILD.gn | 76 +- kits/appkit/napi/BUILD.gn | 4 + kits/appkit/napi/ability_stage/BUILD.gn | 49 + .../napi/ability_stage/ability_stage.js | 21 + .../ability_stage/ability_stage_module.cpp | 57 + .../napi/ability_stage_context/BUILD.gn | 49 + .../ability_stage_context.js | 26 + .../ability_stage_context_module.cpp | 57 + kits/appkit/napi/appMgr/app_mgr.cpp | 6 +- kits/appkit/napi/appMgr/app_mgr.h | 6 +- kits/appkit/napi/context/BUILD.gn | 49 + kits/appkit/napi/context/context.js | 39 + kits/appkit/napi/context/context_module.cpp | 57 + kits/appkit/napi/launchermgr/BUILD.gn | 54 + .../launchermgr/bundle_status_callback.cpp | 68 ++ .../napi/launchermgr/bundle_status_callback.h | 46 + kits/appkit/napi/launchermgr/js_launcher.cpp | 983 ++++++++++++++++++ .../napi/launchermgr/js_launcher_mgr.cpp | 33 + .../appkit/napi/launchermgr/js_launcher_mgr.h | 42 + .../ability_runtime/app/ability_stage.cpp | 90 ++ .../ability_runtime/app/ability_stage.h | 56 + .../ability_runtime/app/js_ability_stage.cpp | 111 ++ .../ability_runtime/app/js_ability_stage.h | 44 + .../native/ability_runtime/context/bindable.h | 86 ++ .../native/ability_runtime/context/context.h | 146 +++ .../ability_runtime/context/context_impl.cpp | 322 ++++++ .../ability_runtime/context/context_impl.h | 205 ++++ .../context/js_context_utils.cpp | 158 +++ .../context/js_context_utils.h | 32 + .../context/js_hap_module_info_utils.cpp | 71 ++ .../context/js_hap_module_info_utils.h | 31 + .../context/js_resource_manager_utils.cpp | 100 ++ .../context/js_resource_manager_utils.h | 32 + .../ability_runtime/extension_context.cpp | 31 + .../ability_runtime/extension_context.h | 46 + .../service_extension_context.cpp | 95 ++ .../service_extension_context.h | 100 ++ kits/appkit/native/app/include/context.h | 2 +- kits/appkit/native/app/include/main_thread.h | 3 +- .../native/app/include/ohos_application.h | 56 +- .../appkit/native/app/src/ability_manager.cpp | 2 +- .../native/app/src/application_impl.cpp | 3 +- .../native/app/src/context_container.cpp | 5 +- kits/appkit/native/app/src/context_deal.cpp | 14 +- kits/appkit/native/app/src/main_thread.cpp | 118 ++- .../native/app/src/ohos_application.cpp | 114 +- kits/appkit/native/app/src/sys_mgr_client.cpp | 2 +- kits/appkit/native/test/BUILD.gn | 9 + .../mock_ability_manager_client_interface1.h | 10 +- .../test/unittest/ability_stage_test.cpp | 211 ++++ .../context_deal_for_task_dispacher_test.cpp | 2 +- .../unittest/context_deal_interface1_test.cpp | 8 +- .../test/unittest/context_impl_test.cpp | 164 +++ kits/appkit/test/BUILD.gn | 4 + .../Mock/include/mock_bundle_mgr_service.h | 1 + ...k_appkit_native_app_module_test_fourth.cpp | 8 +- ...wk_appkit_native_app_module_test_third.cpp | 8 +- libs/libeventhandler/BUILD.gn | 1 + libs/libeventhandler/src/epoll_io_waiter.h | 2 +- libs/libeventhandler/src/event_handler.cpp | 33 + .../libeventhandler/src/event_handler_utils.h | 26 + libs/libeventhandler/src/event_runner.cpp | 2 +- libs/libeventhandler/src/inner_event.cpp | 25 + libs/libeventhandler/test/BUILD.gn | 39 +- .../unittest/lib_event_handler_trace_test.cpp | 586 +++++++++++ .../moduletest/common/event_handler/BUILD.gn | 35 +- mgit.info | 1 + ohos.build | 14 +- sa_profile/BUILD.gn | 6 +- services/appmgr/BUILD.gn | 1 + .../main_client.cpp | 6 +- .../appmgr/include/app_mgr_service_inner.h | 10 + services/appmgr/src/ams_mgr_scheduler.cpp | 22 +- services/appmgr/src/app_death_recipient.cpp | 2 +- services/appmgr/src/app_mgr_service.cpp | 26 +- services/appmgr/src/app_mgr_service_inner.cpp | 69 +- services/appmgr/src/app_process_manager.cpp | 1 + services/appmgr/src/app_running_manager.cpp | 4 +- services/appmgr/src/app_running_record.cpp | 4 +- services/appmgr/src/cgroup_manager.cpp | 2 +- ...ory_Info.h => kernel_system_memory_info.h} | 26 +- services/appmgr/src/lmks/lmks_server.cpp | 4 +- services/appmgr/src/lmks/lmks_utils.cpp | 4 +- services/appmgr/src/process_optimizer.cpp | 4 +- services/appmgr/src/start_via_asan.cpp | 3 +- .../src/system_environment_information.cpp | 41 +- .../src/system_environment_information.h | 2 +- services/appmgr/test/BUILD.gn | 2 + .../test/mock/src/sys_mgr_client_mock.cpp | 2 +- .../ams_ability_running_record_test/BUILD.gn | 1 + .../ams_app_death_recipient_test/BUILD.gn | 1 + .../unittest/ams_app_life_cycle_test/BUILD.gn | 1 + .../ams_app_mgr_client_test.cpp | 4 +- .../ams_app_running_record_test/BUILD.gn | 1 + .../ams_app_state_callback_test/BUILD.gn | 1 + .../unittest/ams_app_workflow_test/BUILD.gn | 1 + .../ams_workflow_test.cpp | 8 +- .../ams_mgr_scheduler_test.cpp | 4 +- .../ams_recent_app_list_test/BUILD.gn | 1 + .../BUILD.gn | 1 + ...ams_service_app_spawn_msg_wrapper_test.cpp | 2 +- .../ams_service_app_spawn_socket_test.cpp | 5 +- .../ams_service_event_drive_test/BUILD.gn | 1 + .../ams_service_event_drive_test.cpp | 3 +- .../BUILD.gn | 1 + .../ams_service_startup_test/BUILD.gn | 1 + .../BUILD.gn | 1 + .../test/mock/include/mock_ability_mgr_host.h | 12 + services/formmgr/include/form_data_mgr.h | 2 +- services/formmgr/include/form_db_cache.h | 2 +- services/formmgr/include/form_db_info.h | 12 +- services/formmgr/include/form_mgr_adapter.h | 8 +- services/formmgr/include/form_timer_mgr.h | 10 +- services/formmgr/src/form_ams_helper.cpp | 4 +- services/formmgr/src/form_bms_helper.cpp | 4 +- services/formmgr/src/form_data_mgr.cpp | 1 + services/formmgr/src/form_db_info.cpp | 89 +- services/formmgr/src/form_mgr_adapter.cpp | 36 +- services/formmgr/src/form_mgr_service.cpp | 12 +- services/formmgr/src/form_provider_mgr.cpp | 4 +- services/formmgr/src/form_storage_mgr.cpp | 18 +- .../formmgr/src/form_sys_event_receiver.cpp | 4 +- services/formmgr/src/form_timer_mgr.cpp | 20 +- services/formmgr/src/form_util.cpp | 2 +- .../test/mock/include/mock_ability_manager.h | 22 + .../fms_form_data_mgr_test.cpp | 3 +- .../fms_form_host_record_test.cpp | 2 +- .../fms_form_mgr_add_form_test.cpp | 2 +- .../fms_form_mgr_cast_temp_form_test.cpp | 1 + .../fms_form_mgr_lifecycle_update_test.cpp | 7 +- ...fms_form_mgr_notify_visible_forms_test.cpp | 8 +- .../fms_form_mgr_release_form_test.cpp | 4 +- .../fms_form_provider_data_test.cpp | 2 +- .../fms_form_set_next_refresh_test.cpp | 8 +- .../fms_form_sys_event_receiver_test.cpp | 4 +- .../test/mock/include/mock_ability_mgr_host.h | 12 + .../test/mock/src/system_ability_helper.cpp | 2 +- services/test/moduletest/common/ams/BUILD.gn | 2 + .../ams_app_mgr_service_module_test.cpp | 4 +- .../ams_ipc_ams_mgr_module_test.cpp | 15 +- .../ams_ipc_app_scheduler_module_test.cpp | 6 +- .../ams_service_event_drive_module_test.cpp | 5 +- .../include/ams_st_data_ability_data_a.h | 3 +- .../src/ams_st_data_ability_data_a.cpp | 26 +- .../src/ams_st_data_ability_data_c1.cpp | 10 +- .../amsKitSystemTest/src/fifth_ability.cpp | 10 +- .../amsKitSystemTest/src/second_ability.cpp | 15 +- .../include/ams_st_kit_data_ability_data_a1.h | 1 + .../include/ams_st_kit_data_ability_data_a2.h | 1 + .../include/ams_st_kit_data_ability_data_a3.h | 1 + .../src/ams_st_kit_data_ability_data_a1.cpp | 10 +- .../src/ams_st_kit_data_ability_data_a2.cpp | 10 +- .../src/ams_st_kit_data_ability_data_a3.cpp | 10 +- .../src/ams_st_kit_data_ability_page_a.cpp | 2 +- .../include/ams_st_kit_data_ability_data_b.h | 1 + .../src/ams_st_kit_data_ability_data_b.cpp | 10 +- .../include/form_ability_performance.h | 2 +- .../include/form_ability_stress.h | 2 +- .../include/form_ability_a.h | 2 +- .../include/form_ability_deleteform.h | 2 +- .../include/form_ability_releaseform.h | 2 +- .../include/form_ability_b.h | 6 +- .../fmsSystemTestHostNormalC/config.json | 2 +- .../include/form_ability_c.h | 4 +- .../fmsSystemTestHostNotSys/config.json | 2 +- .../selfStartingTestHostA/config.json | 2 +- .../include/form_ability_self_starting_a.h | 2 +- .../selfStartingTestHostB/config.json | 2 +- .../include/form_ability_self_starting_b.h | 4 +- .../src/form_st_service_ability_A.cpp | 2 +- .../src/form_st_service_ability_B.cpp | 4 +- .../src/form_st_service_ability_D.cpp | 4 +- .../src/form_st_service_ability_E.cpp | 4 +- test/systemtest/BUILD.gn | 2 +- .../ams_ability_append_test.cpp | 4 +- .../ams/ams_app_process_manage_test/BUILD.gn | 2 + .../ams_data_ability_test.cpp | 2 +- .../ams_kit_test/acts_ams_kit_data_test.cpp | 2 +- .../ams_service_ability_test.cpp | 118 +-- .../ams_service_ability_test_def.h | 2 +- .../common/ams/tool/include/st_ability_util.h | 3 +- test/systemtest/common/ems/BUILD.gn | 2 +- .../ems/ems_dumper_system_test/BUILD.gn | 2 +- .../ems_event_handler_system_test/BUILD.gn | 2 +- .../ems/ems_event_queue_system_test/BUILD.gn | 2 +- .../ems/ems_event_runner_system_test/BUILD.gn | 2 +- .../ems/ems_inner_event_system_test/BUILD.gn | 2 +- .../ems/ems_logger_system_test/BUILD.gn | 2 +- .../fms/common/src/system_test_form_util.cpp | 2 +- .../fms_acquire_form_test.cpp | 6 +- .../fms_acquire_form_test_batch.cpp | 8 +- .../fms_acquire_form_test_max.cpp | 8 +- .../fms_delete_form_test.cpp | 6 +- .../fms_fuzz_test_config/config.json | 54 +- .../fms_release_form_test.cpp | 10 +- .../fms_self_starting_test/FMS_Start_0100.sh | 6 +- .../fms_self_starting_test/FMS_Start_0200.sh | 9 +- .../fms_self_starting_test/FMS_Start_0300.sh | 4 +- .../fms_self_starting_test/FMS_Start_0400.sh | 9 +- .../fms_self_starting_test.cpp | 6 +- .../self_starting_test_config_parser.h | 6 +- .../common/fms/fms_stress_test/BUILD.gn | 3 +- tools/fm/src/fms_command.cpp | 2 +- tools/test/BUILD.gn | 2 +- tools/test/mock/mock_bundle_mgr_host.h | 13 +- 248 files changed, 6629 insertions(+), 648 deletions(-) create mode 100644 interfaces/innerkits/napi/BUILD.gn create mode 100644 interfaces/innerkits/napi/eventhandler/BUILD.gn create mode 100644 interfaces/innerkits/napi/eventhandler/include/events_emitter.h create mode 100644 interfaces/innerkits/napi/eventhandler/src/events_emitter.cpp create mode 100644 interfaces/innerkits/napi/eventhandler/src/init.cpp create mode 100644 kits/appkit/napi/ability_stage/BUILD.gn create mode 100644 kits/appkit/napi/ability_stage/ability_stage.js create mode 100644 kits/appkit/napi/ability_stage/ability_stage_module.cpp create mode 100644 kits/appkit/napi/ability_stage_context/BUILD.gn create mode 100644 kits/appkit/napi/ability_stage_context/ability_stage_context.js create mode 100644 kits/appkit/napi/ability_stage_context/ability_stage_context_module.cpp create mode 100644 kits/appkit/napi/context/BUILD.gn create mode 100644 kits/appkit/napi/context/context.js create mode 100644 kits/appkit/napi/context/context_module.cpp create mode 100644 kits/appkit/napi/launchermgr/BUILD.gn create mode 100644 kits/appkit/napi/launchermgr/bundle_status_callback.cpp create mode 100644 kits/appkit/napi/launchermgr/bundle_status_callback.h create mode 100644 kits/appkit/napi/launchermgr/js_launcher.cpp create mode 100644 kits/appkit/napi/launchermgr/js_launcher_mgr.cpp create mode 100644 kits/appkit/napi/launchermgr/js_launcher_mgr.h create mode 100644 kits/appkit/native/ability_runtime/app/ability_stage.cpp create mode 100644 kits/appkit/native/ability_runtime/app/ability_stage.h create mode 100644 kits/appkit/native/ability_runtime/app/js_ability_stage.cpp create mode 100644 kits/appkit/native/ability_runtime/app/js_ability_stage.h create mode 100644 kits/appkit/native/ability_runtime/context/bindable.h create mode 100644 kits/appkit/native/ability_runtime/context/context.h create mode 100644 kits/appkit/native/ability_runtime/context/context_impl.cpp create mode 100644 kits/appkit/native/ability_runtime/context/context_impl.h create mode 100644 kits/appkit/native/ability_runtime/context/js_context_utils.cpp create mode 100644 kits/appkit/native/ability_runtime/context/js_context_utils.h create mode 100644 kits/appkit/native/ability_runtime/context/js_hap_module_info_utils.cpp create mode 100644 kits/appkit/native/ability_runtime/context/js_hap_module_info_utils.h create mode 100644 kits/appkit/native/ability_runtime/context/js_resource_manager_utils.cpp create mode 100644 kits/appkit/native/ability_runtime/context/js_resource_manager_utils.h create mode 100644 kits/appkit/native/ability_runtime/extension_context.cpp create mode 100644 kits/appkit/native/ability_runtime/extension_context.h create mode 100644 kits/appkit/native/ability_runtime/service_extension_context.cpp create mode 100644 kits/appkit/native/ability_runtime/service_extension_context.h create mode 100644 kits/appkit/native/test/unittest/ability_stage_test.cpp create mode 100644 kits/appkit/native/test/unittest/context_impl_test.cpp create mode 100644 libs/libeventhandler/test/unittest/lib_event_handler_trace_test.cpp create mode 100644 mgit.info rename services/appmgr/src/{kernal_system_memory_Info.h => kernel_system_memory_info.h} (66%) diff --git a/OAT.xml b/OAT.xml index 75afe1595f..f50b452b4e 100644 --- a/OAT.xml +++ b/OAT.xml @@ -61,7 +61,7 @@ Note:If the text contains special characters, please escape them according to th - + diff --git a/common/test/unittest/common_perf_profile_test/common_perf_profile_test.cpp b/common/test/unittest/common_perf_profile_test/common_perf_profile_test.cpp index d262dbff5e..ebf39ea89a 100644 --- a/common/test/unittest/common_perf_profile_test/common_perf_profile_test.cpp +++ b/common/test/unittest/common_perf_profile_test/common_perf_profile_test.cpp @@ -746,4 +746,4 @@ HWTEST_F(CommonPerfProfileTest, PerfProfileEnable_001, TestSize.Level0) PerfProfile::GetInstance().Reset(); profileFlag = PerfProfile::GetInstance().GetPerfProfileEnabled(); ASSERT_TRUE(profileFlag); -} +} \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_base/include/form_constants.h b/interfaces/innerkits/appexecfwk_base/include/form_constants.h index cfd1fc11dc..fb8b4e262e 100644 --- a/interfaces/innerkits/appexecfwk_base/include/form_constants.h +++ b/interfaces/innerkits/appexecfwk_base/include/form_constants.h @@ -94,7 +94,7 @@ namespace Constants { const std::string PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY = "form_manager_service_bundlename"; // PROVIDER_FLAG false:ProviderFormInfo is null;true: ProviderFormInfo not null - const std::string PROVIDER_FLAG = "provider_flag"; + const std::string PROVIDER_FLAG = "provider_flag"; const std::string FORM_CONNECT_ID = "form_connect_id"; const std::string FORM_SUPPLY_INFO = "form_supply_info"; diff --git a/interfaces/innerkits/appexecfwk_base/include/form_js_info.h b/interfaces/innerkits/appexecfwk_base/include/form_js_info.h index ac079d6bde..eb6d2e884a 100644 --- a/interfaces/innerkits/appexecfwk_base/include/form_js_info.h +++ b/interfaces/innerkits/appexecfwk_base/include/form_js_info.h @@ -41,7 +41,7 @@ struct FormJsInfo : public Parcelable { std::string cssPath; std::string jsPath; std::string fileReousePath; - + bool ReadFromParcel(Parcel &parcel); virtual bool Marshalling(Parcel &parcel) const override; static FormJsInfo *Unmarshalling(Parcel &parcel); diff --git a/interfaces/innerkits/appexecfwk_base/src/form_info.cpp b/interfaces/innerkits/appexecfwk_base/src/form_info.cpp index 526d55f3b1..b6aa9f6f6c 100644 --- a/interfaces/innerkits/appexecfwk_base/src/form_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/form_info.cpp @@ -15,17 +15,16 @@ #include "form_info.h" -#include -#include #include +#include #include -#include "json_serializer.h" +#include + +#include "bundle_constants.h" +#include "json_util.h" #include "nlohmann/json.hpp" -#include "string_ex.h" #include "parcel_macro.h" -#include "app_log_wrapper.h" -#include "nlohmann/json.hpp" -#include "bundle_constants.h" +#include "string_ex.h" namespace OHOS { namespace AppExecFwk { @@ -197,7 +196,7 @@ bool FormInfo::Marshalling(Parcel &parcel) const void to_json(nlohmann::json &jsonObject, const FormCustomizeData &customizeDatas) { - jsonObject = nlohmann::json{ + jsonObject = nlohmann::json { {JSON_KEY_NAME, customizeDatas.name}, {JSON_KEY_VALUE, customizeDatas.value} }; @@ -211,7 +210,7 @@ void to_json(nlohmann::json &jsonObject, const FormWindow &formWindow) void to_json(nlohmann::json &jsonObject, const FormInfo &formInfo) { - jsonObject = nlohmann::json{ + jsonObject = nlohmann::json { {JSON_KEY_NAME, formInfo.name}, {JSON_KEY_PACKAGE, formInfo.package}, {JSON_KEY_BUNDLE_NAME, formInfo.bundleName}, @@ -243,8 +242,24 @@ void to_json(nlohmann::json &jsonObject, const FormInfo &formInfo) void from_json(const nlohmann::json &jsonObject, FormCustomizeData &customizeDatas) { - customizeDatas.name = jsonObject.at(JSON_KEY_NAME).get(); - customizeDatas.value = jsonObject.at(JSON_KEY_VALUE).get(); + const auto &jsonObjectEnd = jsonObject.end(); + int32_t parseResult = ERR_OK; + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_NAME, + customizeDatas.name, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_VALUE, + customizeDatas.value, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); } void from_json(const nlohmann::json &jsonObject, FormWindow &formWindow) @@ -255,32 +270,216 @@ void from_json(const nlohmann::json &jsonObject, FormWindow &formWindow) void from_json(const nlohmann::json &jsonObject, FormInfo &formInfo) { - formInfo.bundleName = jsonObject.at(JSON_KEY_BUNDLE_NAME).get(); - formInfo.package = jsonObject.at(JSON_KEY_PACKAGE).get(); - formInfo.moduleName = jsonObject.at(JSON_KEY_MODULE_NAME).get(); - formInfo.abilityName = jsonObject.at(JSON_KEY_ABILITY_NAME).get(); - formInfo.name = jsonObject.at(JSON_KEY_NAME).get(); - formInfo.description = jsonObject.at(JSON_KEY_DESCRIPTION).get(); - formInfo.relatedBundleName = jsonObject.at(JSON_KEY_RELATED_BUNDLE_NAME).get(); - formInfo.jsComponentName = jsonObject.at(JSON_KEY_JS_COMPONENT_NAME).get(); - formInfo.deepLink = jsonObject.at(JSON_KEY_DEEP_LINK).get(); - formInfo.formConfigAbility = jsonObject.at(JSON_KEY_FORMCONFIG_ABILITY).get(); - formInfo.scheduledUpateTime = jsonObject.at(JSON_KEY_SCHEDULED_UPDATE_TIME).get(); - formInfo.src = jsonObject.at(JSON_KEY_SRC).get(); - formInfo.originalBundleName = jsonObject.at(JSON_KEY_ORIGINAL_BUNDLE_NAME).get(); - formInfo.descriptionId = jsonObject.at(JSON_KEY_DESCRIPTION_ID).get(); - formInfo.updateDuration = jsonObject.at(JSON_KEY_UPDATE_DURATION).get(); - formInfo.defaultDimension = jsonObject.at(JSON_KEY_DEFAULT_DIMENSION).get(); - formInfo.defaultFlag = jsonObject.at(JSON_KEY_DEFAULT_FLAG).get(); - formInfo.formVisibleNotify = jsonObject.at(JSON_KEY_FORM_VISIBLE_NOTIFY).get(); - formInfo.updateEnabled = jsonObject.at(JSON_KEY_UPDATE_ENABLED).get(); - formInfo.type = jsonObject.at(JSON_KEY_TYPE).get(); - formInfo.colorMode = jsonObject.at(JSON_KEY_COLOR_MODE).get(); - formInfo.supportDimensions = jsonObject.at(JSON_KEY_SUPPORT_DIMENSIONS).get>(); - formInfo.customizeDatas = jsonObject.at(JSON_KEY_CUSTOMIZE_DATA).get>(); - formInfo.landscapeLayouts = jsonObject.at(JSON_KEY_LANDSCAPE_LAYOUTS).get>(); - formInfo.portraitLayouts = jsonObject.at(JSON_KEY_PORTRAIT_LAYOUTS).get>(); - formInfo.window = jsonObject.at(JSON_KEY_WINDOW).get(); + const auto &jsonObjectEnd = jsonObject.end(); + int32_t parseResult = ERR_OK; + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_BUNDLE_NAME, + formInfo.bundleName, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_PACKAGE, + formInfo.package, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_MODULE_NAME, + formInfo.moduleName, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_ABILITY_NAME, + formInfo.abilityName, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_NAME, + formInfo.name, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_DESCRIPTION, + formInfo.description, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_RELATED_BUNDLE_NAME, + formInfo.relatedBundleName, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_JS_COMPONENT_NAME, + formInfo.jsComponentName, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_DEEP_LINK, + formInfo.deepLink, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_FORMCONFIG_ABILITY, + formInfo.formConfigAbility, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_SCHEDULED_UPDATE_TIME, + formInfo.scheduledUpateTime, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_SRC, + formInfo.src, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_ORIGINAL_BUNDLE_NAME, + formInfo.originalBundleName, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_DESCRIPTION_ID, + formInfo.descriptionId, + JsonType::NUMBER, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_UPDATE_DURATION, + formInfo.updateDuration, + JsonType::NUMBER, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_DEFAULT_DIMENSION, + formInfo.defaultDimension, + JsonType::NUMBER, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_DEFAULT_FLAG, + formInfo.defaultFlag, + JsonType::BOOLEAN, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_FORM_VISIBLE_NOTIFY, + formInfo.formVisibleNotify, + JsonType::BOOLEAN, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_UPDATE_ENABLED, + formInfo.updateEnabled, + JsonType::BOOLEAN, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_TYPE, + formInfo.type, + JsonType::NUMBER, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_COLOR_MODE, + formInfo.colorMode, + JsonType::NUMBER, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey>(jsonObject, + jsonObjectEnd, + JSON_KEY_SUPPORT_DIMENSIONS, + formInfo.supportDimensions, + JsonType::ARRAY, + false, + parseResult, + ArrayType::NUMBER); + GetValueIfFindKey>(jsonObject, + jsonObjectEnd, + JSON_KEY_CUSTOMIZE_DATA, + formInfo.customizeDatas, + JsonType::ARRAY, + false, + parseResult, + ArrayType::OBJECT); + GetValueIfFindKey>(jsonObject, + jsonObjectEnd, + JSON_KEY_LANDSCAPE_LAYOUTS, + formInfo.landscapeLayouts, + JsonType::ARRAY, + false, + parseResult, + ArrayType::STRING); + GetValueIfFindKey>(jsonObject, + jsonObjectEnd, + JSON_KEY_PORTRAIT_LAYOUTS, + formInfo.portraitLayouts, + JsonType::ARRAY, + false, + parseResult, + ArrayType::STRING); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + JSON_KEY_WINDOW, + formInfo.window, + JsonType::OBJECT, + false, + parseResult, + ArrayType::NOT_ARRAY); } } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_base/src/form_js_info.cpp b/interfaces/innerkits/appexecfwk_base/src/form_js_info.cpp index d78ff08a84..0b02ae316c 100644 --- a/interfaces/innerkits/appexecfwk_base/src/form_js_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/form_js_info.cpp @@ -30,10 +30,10 @@ bool FormJsInfo::ReadFromParcel(Parcel &parcel) formData = Str16ToStr8(parcel.ReadString16()); auto bindingData = parcel.ReadParcelable(); - formProviderData = *bindingData; - if (nullptr == bindingData) { + if (nullptr == bindingData){ return false; } + formProviderData = *bindingData; return true; } diff --git a/interfaces/innerkits/appexecfwk_base/src/form_provider_data.cpp b/interfaces/innerkits/appexecfwk_base/src/form_provider_data.cpp index c929b6ec8e..66a186f811 100644 --- a/interfaces/innerkits/appexecfwk_base/src/form_provider_data.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/form_provider_data.cpp @@ -266,7 +266,7 @@ bool FormProviderData::Marshalling(Parcel &parcel) const * @brief Unmarshals this {@code FormProviderData} object from a {@link ohos.utils.Parcel} object. * @param parcel Indicates the {@code Parcel} object for unmarshalling. * @return FormProviderData. - */ + */ FormProviderData* FormProviderData::Unmarshalling(Parcel &parcel) { std::unique_ptr formProviderData = std::make_unique(); @@ -278,7 +278,7 @@ FormProviderData* FormProviderData::Unmarshalling(Parcel &parcel) /** * @brief Clear imageDataMap, rawImageBytesMap_, imageDataState_ and jsonFormProviderData_. - */ + */ void FormProviderData::ClearData() { jsonFormProviderData_.clear(); diff --git a/interfaces/innerkits/appexecfwk_base/src/form_provider_info.cpp b/interfaces/innerkits/appexecfwk_base/src/form_provider_info.cpp index e7824e24f3..0af60cc163 100644 --- a/interfaces/innerkits/appexecfwk_base/src/form_provider_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/form_provider_info.cpp @@ -39,7 +39,6 @@ bool FormProviderInfo::Marshalling(Parcel &parcel) const if (!parcel.WriteParcelable(&jsBindingData_)) { return false; } - return true; } void FormProviderInfo::SetFormDataString(std::string &dataString) @@ -49,7 +48,7 @@ void FormProviderInfo::SetFormDataString(std::string &dataString) /** * @brief Merge new data to FormProviderData. * @param addJsonData data to merge to FormProviderData - */ + */ void FormProviderInfo::MergeData(nlohmann::json &addJsonData) { jsBindingData_.MergeData(addJsonData); diff --git a/interfaces/innerkits/appexecfwk_core/BUILD.gn b/interfaces/innerkits/appexecfwk_core/BUILD.gn index 2447b3f308..d49be1ae50 100644 --- a/interfaces/innerkits/appexecfwk_core/BUILD.gn +++ b/interfaces/innerkits/appexecfwk_core/BUILD.gn @@ -119,6 +119,7 @@ ohos_shared_library("appexecfwk_core") { "hiviewdfx_hilog_native:libhilog", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "bytrace_standard:bytrace_core", ] subsystem_name = "appexecfwk" diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_constants.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_constants.h index eedab3f619..a23c835dc1 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_constants.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_constants.h @@ -20,6 +20,7 @@ namespace OHOS { namespace AppExecFwk { namespace Constants { const std::string APP_MGR_SERVICE_NAME = "AppMgrService"; +const std::string USER_ID = "UserId"; } // namespace Constants enum class ApplicationState { diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_proxy.cpp index b08eeb80ee..e95c555652 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_proxy.cpp @@ -14,12 +14,12 @@ */ #include "ams_mgr_proxy.h" -#include "string_ex.h" #include "ipc_types.h" #include "iremote_object.h" +#include "string_ex.h" -#include "appexecfwk_errors.h" #include "app_log_wrapper.h" +#include "appexecfwk_errors.h" namespace OHOS { namespace AppExecFwk { diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_stub.cpp index 2633911ce7..371e558174 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_stub.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_stub.cpp @@ -20,10 +20,11 @@ #include "iremote_object.h" #include "ability_info.h" -#include "appexecfwk_errors.h" #include "app_log_wrapper.h" #include "app_mgr_proxy.h" #include "app_scheduler_interface.h" +#include "appexecfwk_errors.h" +#include "bytrace.h" #include "iapp_state_callback.h" namespace OHOS { @@ -80,6 +81,7 @@ int AmsMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParce ErrCode AmsMgrStub::HandleLoadAbility(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); sptr token = data.ReadParcelable(); sptr preToke = data.ReadParcelable(); std::shared_ptr abilityInfo(data.ReadParcelable()); @@ -100,6 +102,7 @@ ErrCode AmsMgrStub::HandleLoadAbility(MessageParcel &data, MessageParcel &reply) ErrCode AmsMgrStub::HandleTerminateAbility(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); sptr token = data.ReadParcelable(); TerminateAbility(token); return NO_ERROR; @@ -107,6 +110,7 @@ ErrCode AmsMgrStub::HandleTerminateAbility(MessageParcel &data, MessageParcel &r ErrCode AmsMgrStub::HandleUpdateAbilityState(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); sptr token = data.ReadParcelable(); int32_t state = data.ReadInt32(); UpdateAbilityState(token, static_cast(state)); @@ -115,6 +119,7 @@ ErrCode AmsMgrStub::HandleUpdateAbilityState(MessageParcel &data, MessageParcel ErrCode AmsMgrStub::HandleRegisterAppStateCallback(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); sptr obj = data.ReadParcelable(); sptr callback = iface_cast(obj); RegisterAppStateCallback(callback); @@ -123,12 +128,14 @@ ErrCode AmsMgrStub::HandleRegisterAppStateCallback(MessageParcel &data, MessageP ErrCode AmsMgrStub::HandleReset(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); Reset(); return NO_ERROR; } ErrCode AmsMgrStub::HandleAbilityBehaviorAnalysis(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); sptr token = data.ReadParcelable(); sptr preToke = data.ReadParcelable(); int32_t visibility = data.ReadInt32(); @@ -141,6 +148,7 @@ ErrCode AmsMgrStub::HandleAbilityBehaviorAnalysis(MessageParcel &data, MessagePa ErrCode AmsMgrStub::HandleKillProcessByAbilityToken(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); sptr token = data.ReadParcelable(); KillProcessByAbilityToken(token); @@ -149,6 +157,7 @@ ErrCode AmsMgrStub::HandleKillProcessByAbilityToken(MessageParcel &data, Message ErrCode AmsMgrStub::HandleKillApplication(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); std::string bundleName = data.ReadString(); int32_t result = KillApplication(bundleName); reply.WriteInt32(result); @@ -157,6 +166,7 @@ ErrCode AmsMgrStub::HandleKillApplication(MessageParcel &data, MessageParcel &re ErrCode AmsMgrStub::HandleKillApplicationByUid(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); std::string bundleName = data.ReadString(); int uid = data.ReadInt32(); int32_t result = KillApplicationByUid(bundleName, uid); @@ -166,6 +176,7 @@ ErrCode AmsMgrStub::HandleKillApplicationByUid(MessageParcel &data, MessageParce int32_t AmsMgrStub::HandleAbilityAttachTimeOut(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); sptr token = data.ReadParcelable(); AbilityAttachTimeOut(token); return NO_ERROR; @@ -173,6 +184,7 @@ int32_t AmsMgrStub::HandleAbilityAttachTimeOut(MessageParcel &data, MessageParce int32_t AmsMgrStub::HandleCompelVerifyPermission(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); auto permission = Str16ToStr8(data.ReadString16()); auto pid = data.ReadInt32(); auto uid = data.ReadInt32(); diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_client.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_client.cpp index f6a1b22d35..198006e7e3 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_client.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_client.cpp @@ -22,9 +22,9 @@ #include "if_system_ability_manager.h" #include "ipc_skeleton.h" +#include "app_log_wrapper.h" #include "app_mgr_interface.h" #include "app_service_manager.h" -#include "app_log_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_stub.cpp index 32cb6e4974..97b54695c0 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_stub.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_stub.cpp @@ -20,10 +20,11 @@ #include "iremote_object.h" #include "ability_info.h" -#include "appexecfwk_errors.h" #include "app_log_wrapper.h" #include "app_mgr_proxy.h" #include "app_scheduler_interface.h" +#include "appexecfwk_errors.h" +#include "bytrace.h" #include "iapp_state_callback.h" namespace OHOS { @@ -88,6 +89,7 @@ int AppMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParce int32_t AppMgrStub::HandleAttachApplication(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); sptr client = data.ReadParcelable(); AttachApplication(client); return NO_ERROR; @@ -95,24 +97,28 @@ int32_t AppMgrStub::HandleAttachApplication(MessageParcel &data, MessageParcel & int32_t AppMgrStub::HandleApplicationForegrounded(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); ApplicationForegrounded(data.ReadInt32()); return NO_ERROR; } int32_t AppMgrStub::HandleApplicationBackgrounded(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); ApplicationBackgrounded(data.ReadInt32()); return NO_ERROR; } int32_t AppMgrStub::HandleApplicationTerminated(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); ApplicationTerminated(data.ReadInt32()); return NO_ERROR; } int32_t AppMgrStub::HandleCheckPermission(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); int32_t recordId = data.ReadInt32(); std::string permission = data.ReadString(); int32_t result = CheckPermission(recordId, permission); @@ -122,6 +128,7 @@ int32_t AppMgrStub::HandleCheckPermission(MessageParcel &data, MessageParcel &re int32_t AppMgrStub::HandleAbilityCleaned(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); sptr token = data.ReadParcelable(); AbilityCleaned(token); return NO_ERROR; @@ -129,6 +136,7 @@ int32_t AppMgrStub::HandleAbilityCleaned(MessageParcel &data, MessageParcel &rep int32_t AppMgrStub::HandleGetAmsMgr(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); int32_t result = NO_ERROR; sptr amsMgr = GetAmsMgr(); if (!amsMgr) { @@ -146,6 +154,7 @@ int32_t AppMgrStub::HandleGetAmsMgr(MessageParcel &data, MessageParcel &reply) int32_t AppMgrStub::HandleClearUpApplicationData(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); std::string bundleName = data.ReadString(); int32_t result = ClearUpApplicationData(bundleName); reply.WriteInt32(result); @@ -154,6 +163,7 @@ int32_t AppMgrStub::HandleClearUpApplicationData(MessageParcel &data, MessagePar int32_t AppMgrStub::HandleIsBackgroundRunningRestricted(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); std::string bundleName = data.ReadString(); int32_t result = IsBackgroundRunningRestricted(bundleName); reply.WriteInt32(result); @@ -162,6 +172,7 @@ int32_t AppMgrStub::HandleIsBackgroundRunningRestricted(MessageParcel &data, Mes int32_t AppMgrStub::HandleGetAllRunningProcesses(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); std::vector info; auto result = GetAllRunningProcesses(info); reply.WriteInt32(info.size()); @@ -178,12 +189,14 @@ int32_t AppMgrStub::HandleGetAllRunningProcesses(MessageParcel &data, MessagePar int32_t AppMgrStub::HandleSetAppFreezingTime(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); SetAppFreezingTime(data.ReadInt32()); return NO_ERROR; } int32_t AppMgrStub::HandleGetAppFreezingTime(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); int time = 0; GetAppFreezingTime(time); reply.WriteInt32(time); @@ -192,6 +205,7 @@ int32_t AppMgrStub::HandleGetAppFreezingTime(MessageParcel &data, MessageParcel int32_t AppMgrStub::HandleGetSystemMemoryAttr(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); SystemMemoryAttr memoryInfo; std::string strConfig; data.ReadString(strConfig); @@ -205,6 +219,7 @@ int32_t AppMgrStub::HandleGetSystemMemoryAttr(MessageParcel &data, MessageParcel int32_t AppMgrStub::HandleAddAbilityStageDone(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); int32_t recordId = data.ReadInt32(); AddAbilityStageDone(recordId); return NO_ERROR; @@ -212,6 +227,7 @@ int32_t AppMgrStub::HandleAddAbilityStageDone(MessageParcel &data, MessageParcel int32_t AppMgrStub::HandleStartupResidentProcess(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); StartupResidentProcess(); return NO_ERROR; } diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_scheduler_host.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_scheduler_host.cpp index 08eb60495c..3b331932b9 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_scheduler_host.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_scheduler_host.cpp @@ -14,10 +14,11 @@ */ #include "app_scheduler_host.h" -#include "ipc_types.h" #include "ability_info.h" -#include "appexecfwk_errors.h" #include "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "bytrace.h" +#include "ipc_types.h" namespace OHOS { namespace AppExecFwk { @@ -76,36 +77,42 @@ int AppSchedulerHost::OnRemoteRequest(uint32_t code, MessageParcel &data, Messag int32_t AppSchedulerHost::HandleScheduleForegroundApplication(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); ScheduleForegroundApplication(); return NO_ERROR; } int32_t AppSchedulerHost::HandleScheduleBackgroundApplication(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); ScheduleBackgroundApplication(); return NO_ERROR; } int32_t AppSchedulerHost::HandleScheduleTerminateApplication(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); ScheduleTerminateApplication(); return NO_ERROR; } int32_t AppSchedulerHost::HandleScheduleLowMemory(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); ScheduleLowMemory(); return NO_ERROR; } int32_t AppSchedulerHost::HandleScheduleShrinkMemory(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); ScheduleShrinkMemory(data.ReadInt32()); return NO_ERROR; } int32_t AppSchedulerHost::HandleScheduleLaunchAbility(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); std::unique_ptr abilityInfo(data.ReadParcelable()); if (!abilityInfo) { APP_LOGE("ReadParcelable failed"); @@ -119,6 +126,7 @@ int32_t AppSchedulerHost::HandleScheduleLaunchAbility(MessageParcel &data, Messa int32_t AppSchedulerHost::HandleScheduleCleanAbility(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); sptr token = data.ReadParcelable(); ScheduleCleanAbility(token); return NO_ERROR; @@ -126,6 +134,7 @@ int32_t AppSchedulerHost::HandleScheduleCleanAbility(MessageParcel &data, Messag int32_t AppSchedulerHost::HandleScheduleLaunchApplication(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); std::unique_ptr launchData(data.ReadParcelable()); if (!launchData) { @@ -139,6 +148,7 @@ int32_t AppSchedulerHost::HandleScheduleLaunchApplication(MessageParcel &data, M int32_t AppSchedulerHost::HandleScheduleAbilityStageInfo(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); std::unique_ptr appResidentProcessInfo(data.ReadParcelable()); if (!appResidentProcessInfo) { APP_LOGE("ReadParcelable failed"); @@ -151,6 +161,7 @@ int32_t AppSchedulerHost::HandleScheduleAbilityStageInfo(MessageParcel &data, Me int32_t AppSchedulerHost::HandleScheduleProfileChanged(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); std::unique_ptr profile(data.ReadParcelable()); if (!profile) { APP_LOGE("ReadParcelable failed"); @@ -163,6 +174,7 @@ int32_t AppSchedulerHost::HandleScheduleProfileChanged(MessageParcel &data, Mess int32_t AppSchedulerHost::HandleScheduleConfigurationUpdated(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); std::unique_ptr configuration(data.ReadParcelable()); if (!configuration) { APP_LOGE("ReadParcelable failed"); @@ -175,6 +187,7 @@ int32_t AppSchedulerHost::HandleScheduleConfigurationUpdated(MessageParcel &data int32_t AppSchedulerHost::HandleScheduleProcessSecurityExit(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); ScheduleProcessSecurityExit(); return NO_ERROR; } diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_scheduler_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_scheduler_proxy.cpp index d259562ea3..cefaac1f29 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_scheduler_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_scheduler_proxy.cpp @@ -15,10 +15,9 @@ #include "app_scheduler_proxy.h" -#include "iremote_object.h" -#include "ipc_types.h" - #include "app_log_wrapper.h" +#include "ipc_types.h" +#include "iremote_object.h" namespace OHOS { namespace AppExecFwk { diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_service_manager.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_service_manager.cpp index 86e7bafb9e..ef8c513f7f 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_service_manager.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_service_manager.cpp @@ -15,12 +15,12 @@ #include "app_service_manager.h" +#include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "system_ability_definition.h" -#include "if_system_ability_manager.h" -#include "iservice_registry.h" #include "app_mgr_constants.h" +#include "iservice_registry.h" namespace OHOS { namespace AppExecFwk { diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_state_callback_host.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_state_callback_host.cpp index fded57e6c9..2a953aff5b 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_state_callback_host.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_state_callback_host.cpp @@ -15,9 +15,9 @@ #include "app_state_callback_host.h" -#include "appexecfwk_errors.h" #include "app_log_wrapper.h" - +#include "appexecfwk_errors.h" +#include "bytrace.h" #include "ipc_types.h" #include "iremote_object.h" @@ -71,6 +71,7 @@ void AppStateCallbackHost::OnAppStateChanged(const AppProcessData &) int32_t AppStateCallbackHost::HandleOnAppStateChanged(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); std::unique_ptr processData(data.ReadParcelable()); if (!processData) { APP_LOGE("ReadParcelable failed"); @@ -83,6 +84,7 @@ int32_t AppStateCallbackHost::HandleOnAppStateChanged(MessageParcel &data, Messa int32_t AppStateCallbackHost::HandleOnAbilityRequestDone(MessageParcel &data, MessageParcel &reply) { + BYTRACE(BYTRACE_TAG_APP); sptr obj = data.ReadParcelable(); int32_t state = data.ReadInt32(); OnAbilityRequestDone(obj, static_cast(state)); diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/configuration.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/configuration.cpp index 5bb183a980..1e80e4fa4c 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/configuration.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/configuration.cpp @@ -13,11 +13,13 @@ * limitations under the License. */ +#include "configuration.h" + #include -#include "string_ex.h" + #include "app_log_wrapper.h" -#include "configuration.h" -namespace ConfigurationInner { +#include "string_ex.h" +namespace { const std::string CONNECTION_SYMBOL {"#"}; const std::string EMPTY_STRING {""}; @@ -138,7 +140,7 @@ std::string Configuration::GetValue(const std::string &key) const void Configuration::CompareDifferent(std::vector &diffKeyV, const Configuration &other) { if (other.GetItemSize() == 0) { - return ; + return; } diffKeyV.clear(); diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp index e57d51f60f..de768ed077 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp @@ -14,8 +14,9 @@ */ #include "process_info.h" -#include "string_ex.h" + #include "app_log_wrapper.h" +#include "string_ex.h" namespace OHOS { namespace AppExecFwk { diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_proxy.cpp index cf1bb6dd82..acbd26b85b 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_proxy.cpp @@ -379,10 +379,10 @@ int FormMgrProxy::CastTempForm(const int64_t formId, const sptr & MessageOption option; int error = Remote()->SendRequest( static_cast( - IFormMgr::Message::FORM_MGR_CAST_TEMP_FORM), - data, - reply, - option); + IFormMgr::Message::FORM_MGR_CAST_TEMP_FORM), + data, + reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; @@ -455,7 +455,7 @@ int FormMgrProxy::DumpFormInfoByFormId(const std::int64_t formId, std::string &f int error = GetStringInfo(IFormMgr::Message::FORM_MGR_FORM_INFOS_BY_ID, data, formInfo); if (error != ERR_OK) { - APP_LOGE("%{public}s, failed to GetStringInfo: %{public}d", __func__, error); + APP_LOGE("%{public}s, failed to GetStringInfo: %{public}d", __func__, error); } return error; @@ -480,7 +480,7 @@ int FormMgrProxy::DumpFormTimerByFormId(const std::int64_t formId, std::string & int error = GetStringInfo(IFormMgr::Message::FORM_MGR_FORM_TIMER_INFO_BY_ID, data, isTimingService); if (error != ERR_OK) { - APP_LOGE("%{public}s, failed to GetStringInfo: %{public}d", __func__, error); + APP_LOGE("%{public}s, failed to GetStringInfo: %{public}d", __func__, error); } return error; @@ -512,13 +512,13 @@ int FormMgrProxy::MessageEvent(const int64_t formId, const Want &want, const spt APP_LOGE("%{public}s, failed to write callerToken", __func__); return ERR_APPEXECFWK_PARCEL_ERROR; } - + MessageParcel reply; MessageOption option; int error = Remote()->SendRequest( - static_cast(IFormMgr::Message::FORM_MGR_MESSAGE_EVENT), - data, - reply, + static_cast(IFormMgr::Message::FORM_MGR_MESSAGE_EVENT), + data, + reply, option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); @@ -636,7 +636,7 @@ int FormMgrProxy::SendTransactCmd(IFormMgr::Message code, MessageParcel &data, M int32_t result = remote->SendRequest(static_cast(code), data, reply, option); if (result != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d, cmd: %{public}d", __func__, result, code); - return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; } return ERR_OK; } diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_stub.cpp index cb6d0ed4fb..a5855a2000 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_stub.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_stub.cpp @@ -409,7 +409,7 @@ int32_t FormMgrStub::HandleMessageEvent(MessageParcel &data, MessageParcel &repl APP_LOGE("%{public}s, failed to ReadParcelable", __func__); return ERR_APPEXECFWK_PARCEL_ERROR; } - + int32_t result = MessageEvent(formId, *want, client); reply.WriteInt32(result); return result; diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_proxy.cpp index eb433ebd4e..cb20797726 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_proxy.cpp @@ -47,7 +47,7 @@ void ProviderConnectProxy::OnAbilityConnectDone( return; } - if (!data.WriteParcelable(remoteObject)) { + if (!data.WriteRemoteObject(remoteObject)) { APP_LOGE("%{public}s, failed to write remote object ", __func__); return; } diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_stub.cpp index cee0890826..d925c349a3 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_stub.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_stub.cpp @@ -46,7 +46,7 @@ int ProviderConnectStub::OnRemoteRequest( APP_LOGE("%{public}s failed, callback stub receive element is nullptr", __func__); return ERR_APPEXECFWK_PARCEL_ERROR; } - auto remoteObject = data.ReadParcelable(); + auto remoteObject = data.ReadRemoteObject(); auto resultCode = data.ReadInt32(); OnAbilityConnectDone(*element, remoteObject, resultCode); delete element; diff --git a/interfaces/innerkits/eventhandler_native/eventhandler/native_interface_eventhandler.cpp b/interfaces/innerkits/eventhandler_native/eventhandler/native_interface_eventhandler.cpp index 317e0b630e..83b2bd62da 100644 --- a/interfaces/innerkits/eventhandler_native/eventhandler/native_interface_eventhandler.cpp +++ b/interfaces/innerkits/eventhandler_native/eventhandler/native_interface_eventhandler.cpp @@ -14,8 +14,9 @@ */ #include "native_interface_eventhandler.h" -#include "native_implement_eventhandler.h" #include "hilog/log.h" +#include "native_implement_eventhandler.h" + #include using OHOS::ErrCode; diff --git a/interfaces/innerkits/fmskit/native/include/form_mgr.h b/interfaces/innerkits/fmskit/native/include/form_mgr.h index 8c979be3a3..a6d60915b0 100644 --- a/interfaces/innerkits/fmskit/native/include/form_mgr.h +++ b/interfaces/innerkits/fmskit/native/include/form_mgr.h @@ -42,7 +42,6 @@ class FormMgr final : public DelayedRefSingleton { DECLARE_DELAYED_REF_SINGLETON(FormMgr) public: DISALLOW_COPY_AND_MOVE(FormMgr); - /** * @brief Add form with want, send want to form manager service. * @param formId The Id of the forms to add. @@ -61,7 +60,7 @@ public: * @return Returns ERR_OK on success, others on failure. */ int DeleteForm(const int64_t formId, const sptr &callerToken); - + /** * @brief Release forms with formIds, send formIds to form manager service. * @param formId The Id of the forms to release. @@ -162,7 +161,7 @@ public: /** * @brief UnRegister death callback. - * + * * @param formDeathCallback The death callback. */ void UnRegisterDeathCallback(const std::shared_ptr &formDeathCallback); @@ -183,8 +182,8 @@ public: * @param updateType Next refresh time. * @return Returns ERR_OK on success, others on failure. */ - int LifecycleUpdate(const std::vector &formIds, const sptr &callerToken, - const int32_t updateType); + int LifecycleUpdate(const std::vector &formIds, const sptr &callerToken, + const int32_t updateType); /** * @brief Set fms recoverStatus. @@ -213,7 +212,7 @@ public: /** * @brief Get the error message content. - * + * * @param errCode Error code. * @return Message content. */ diff --git a/interfaces/innerkits/fmskit/native/src/form_mgr.cpp b/interfaces/innerkits/fmskit/native/src/form_mgr.cpp index b70daef0f4..e7f3b4f5b0 100644 --- a/interfaces/innerkits/fmskit/native/src/form_mgr.cpp +++ b/interfaces/innerkits/fmskit/native/src/form_mgr.cpp @@ -13,11 +13,13 @@ * limitations under the License. */ +#include "form_mgr.h" + #include -#include "appexecfwk_errors.h" + #include "app_log_wrapper.h" +#include "appexecfwk_errors.h" #include "form_errors.h" -#include "form_mgr.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "iservice_registry.h" @@ -218,7 +220,7 @@ int FormMgr::DumpFormInfoByFormId(const std::int64_t formId, std::string &formIn if (errCode != ERR_OK) { return errCode; } - + return remoteProxy_->DumpFormInfoByFormId(formId, formInfo); } /** @@ -233,7 +235,7 @@ int FormMgr::DumpFormTimerByFormId(const std::int64_t formId, std::string &isTim if (errCode != ERR_OK) { return errCode; } - + return remoteProxy_->DumpFormTimerByFormId(formId, isTimingService); } /** @@ -249,7 +251,7 @@ int FormMgr::MessageEvent(const int64_t formId, const Want &want, const sptrMessageEvent(formId, want, callerToken); } @@ -265,7 +267,7 @@ int FormMgr::SetNextRefreshTime(const int64_t formId, const int64_t nextTime) if (errCode != ERR_OK) { return errCode; } - + return remoteProxy_->SetNextRefreshTime(formId, nextTime); } @@ -526,7 +528,7 @@ void FormMgr::SetFormMgrService(sptr formMgrService) int FormMgr::DistributedDataAddForm(const Want &want) { APP_LOGI("%{public}s called.", __func__); - + int errCode = Connect(); if (errCode != ERR_OK) { return errCode; @@ -543,7 +545,7 @@ int FormMgr::DistributedDataAddForm(const Want &want) int FormMgr::DistributedDataDeleteForm(const std::string &formId) { APP_LOGI("%{public}s called.", __func__); - + int errCode = Connect(); if (errCode != ERR_OK) { return errCode; diff --git a/interfaces/innerkits/libeventhandler/BUILD.gn b/interfaces/innerkits/libeventhandler/BUILD.gn index f956eb3087..d0eff1bb38 100644 --- a/interfaces/innerkits/libeventhandler/BUILD.gn +++ b/interfaces/innerkits/libeventhandler/BUILD.gn @@ -32,7 +32,10 @@ ohos_shared_library("libeventhandler") { public_configs = [ ":public_libeventhandler_config" ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "hitrace_native:libhitrace", + ] subsystem_name = "appexecfwk" part_name = "appexecfwk_standard" } diff --git a/interfaces/innerkits/libeventhandler/include/inner_event.h b/interfaces/innerkits/libeventhandler/include/inner_event.h index 0cd2e3f1ae..e05a7c0497 100644 --- a/interfaces/innerkits/libeventhandler/include/inner_event.h +++ b/interfaces/innerkits/libeventhandler/include/inner_event.h @@ -26,7 +26,13 @@ #include "nocopyable.h" namespace OHOS { +namespace HiviewDFX { +class HiTraceId; +} + namespace AppExecFwk { +using HiTraceId = OHOS::HiviewDFX::HiTraceId; + class EventHandler; const std::string LINE_SEPARATOR = "\n"; @@ -425,6 +431,21 @@ private: smartPtrTypeId_ = CalculateSmartPtrTypeId(object); } + /** + * if event has trace id ,return trace id, else create span id, + * store it in event and return. + * + * @return return hiTrace Id. + */ + const std::shared_ptr GetOrCreateTraceId(); + + /** + * return trace id. + * + * @return return hiTrace Id. + */ + const std::shared_ptr GetTraceId(); + /* * Calculate the type id for different smart pointers. */ @@ -499,6 +520,9 @@ private: // Used for synchronized event. std::shared_ptr waiter_; + + // use to store hitrace Id + std::shared_ptr hiTraceId_; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/napi/BUILD.gn b/interfaces/innerkits/napi/BUILD.gn new file mode 100644 index 0000000000..b6bcbe472b --- /dev/null +++ b/interfaces/innerkits/napi/BUILD.gn @@ -0,0 +1,20 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +group("napi_packages") { + deps = [ + "${innerkits_path}/napi/eventhandler:emitter", + ] +} diff --git a/interfaces/innerkits/napi/eventhandler/BUILD.gn b/interfaces/innerkits/napi/eventhandler/BUILD.gn new file mode 100644 index 0000000000..4844c477ee --- /dev/null +++ b/interfaces/innerkits/napi/eventhandler/BUILD.gn @@ -0,0 +1,50 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//build/ohos/ace/ace.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +config("native_module_config") { + include_dirs = [ "include" ] +} + +ohos_shared_library("emitter") { + include_dirs = [ + "${innerkits_path}/libeventhandler/include", + "//third_party/node/src", + "//third_party/libuv/include", + ] + + configs = [ ":native_module_config" ] + + sources = [ + "src/events_emitter.cpp", + "src/init.cpp", + ] + + deps = [ + "${innerkits_path}/libeventhandler:libeventhandler", + "//third_party/libuv:uv_static", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + ] + + relative_install_dir = "module" + subsystem_name = "appexecfwk" + part_name = "appexecfwk_standard" +} diff --git a/interfaces/innerkits/napi/eventhandler/include/events_emitter.h b/interfaces/innerkits/napi/eventhandler/include/events_emitter.h new file mode 100644 index 0000000000..70c7a84564 --- /dev/null +++ b/interfaces/innerkits/napi/eventhandler/include/events_emitter.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_NAPI_EVENTHANDLER_JS_EMITTER_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_NAPI_EVENTHANDLER_JS_EMITTER_H + +#include +#include +#include +#include + +#include "event_handler.h" +#include "event_runner.h" +#include "event_queue.h" +#include "inner_event.h" + +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace AppExecFwk { +using Priority = EventQueue::Priority; +static const int32_t ARGC_NUM = 2; +static const int32_t NAPI_VALUE_STRING_LEN = 10240; +class EventHandlerInstance : public EventHandler { +public: + EventHandlerInstance(const std::shared_ptr& runner); + static std::shared_ptr GetInstance(); + ~EventHandlerInstance(); + void ProcessEvent(const InnerEvent::Pointer& event) override; +}; + +enum class DataType: uint32_t { + BOOL = 0, + INT, + STRING, +}; + +struct Val { + DataType type; + + union { + bool bValue; + int32_t nValue; + char cValue[NAPI_VALUE_STRING_LEN] = {0}; + } value; +}; + +struct EventData { + std::map data; +}; + +struct AsyncCallbackInfo { + napi_env env; + bool once = false; + bool isDeleted = false; + napi_ref callback = 0; +}; + +struct CallbackInfos { + std::vector asyncCallbackInfo; +}; + +struct EventDataWorker { + EventData data; + AsyncCallbackInfo* callbackInfo; +}; + +napi_value EmitterInit(napi_env env, napi_value exports); +napi_value JS_On(napi_env env, napi_callback_info cbinfo); +napi_value JS_Off(napi_env env, napi_callback_info cbinfo); +napi_value JS_Once(napi_env env, napi_callback_info cbinfo); +napi_value JS_Emit(napi_env env, napi_callback_info cbinfo); +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_NAPI_EVENTHANDLER_JS_EMITTER_H \ No newline at end of file diff --git a/interfaces/innerkits/napi/eventhandler/src/events_emitter.cpp b/interfaces/innerkits/napi/eventhandler/src/events_emitter.cpp new file mode 100644 index 0000000000..bf639b7fee --- /dev/null +++ b/interfaces/innerkits/napi/eventhandler/src/events_emitter.cpp @@ -0,0 +1,474 @@ +/* + * 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 "hilog/log.h" +#include "events_emitter.h" + +#include + +#define DEFINE_HILOG_LABEL(name) \ +static constexpr OHOS::HiviewDFX::HiLogLabel LOG_LABEL = { LOG_CORE, LOG_DOMAIN, name } + +#define HILOGE(...) OHOS::HiviewDFX::HiLog::Error(LOG_LABEL, ##__VA_ARGS__) +#define HILOGW(...) OHOS::HiviewDFX::HiLog::Warn(LOG_LABEL, ##__VA_ARGS__) +#define HILOGI(...) OHOS::HiviewDFX::HiLog::Info(LOG_LABEL, ##__VA_ARGS__) +#define HILOGD(...) OHOS::HiviewDFX::HiLog::Debug(LOG_LABEL, ##__VA_ARGS__) + +DEFINE_HILOG_LABEL("events_emitter"); +using namespace std; +namespace OHOS { +namespace AppExecFwk { + static map emitterInstances; + std::shared_ptr eventHandler; + EventHandlerInstance::EventHandlerInstance(const std::shared_ptr& runner): EventHandler(runner) + { + HILOGI("EventHandlerInstance::EventHandlerInstance constructed"); + } + EventHandlerInstance::~EventHandlerInstance() + { + HILOGI("EventHandlerInstance::EventHandlerInstance de-constructed"); + } + std::shared_ptr EventHandlerInstance::GetInstance() + { + static auto runner = EventRunner::Create("events_emitter"); + if (runner.get() == nullptr) { + HILOGE("failed to create EventRunner events_emitter"); + return nullptr; + } + static auto instance = std::make_shared(runner); + return instance; + } + + void TransToEventData(napi_env env, EventData eventData, napi_value resultData) + { + napi_value data = nullptr; + napi_create_object(env, &data); + for (map::iterator it = eventData.data.begin(); it != eventData.data.end(); it++) { + string key = it->first; + Val val = it->second; + napi_value napiValue = nullptr; + switch (val.type) { + case DataType::BOOL: + HILOGD("ProcessEvent key:%{public}s value:%{public}d", key.c_str(), val.value.bValue); + napi_get_boolean(env, val.value.bValue, &napiValue); + break; + case DataType::INT: + HILOGD("ProcessEvent key:%{public}s value:%{public}d", key.c_str(), val.value.nValue); + napi_create_int32(env, val.value.nValue, &napiValue); + break; + case DataType::STRING: + HILOGD("ProcessEvent key:%{public}s value:%{public}s", key.c_str(), val.value.cValue); + napi_create_string_utf8(env, val.value.cValue, NAPI_AUTO_LENGTH, &napiValue); + break; + default: + HILOGE("ProcessEvent unsupport type data"); + break; + } + napi_set_named_property(env, data, key.c_str(), napiValue); + } + napi_set_named_property(env, resultData, "data", data); + } + + void ProcessCallback(const EventDataWorker* eventDataInner) + { + if (eventDataInner == nullptr) { + HILOGW("EventDataWorkder instance(uv_work_t) is nullptr"); + return; + } + AsyncCallbackInfo* callbackInner = eventDataInner->callbackInfo; + if (callbackInner->isDeleted) { + HILOGI("ProcessEvent isDeleted callbackInfo = %{public}p", callbackInner); + napi_delete_reference(callbackInner->env, callbackInner->callback); + } else { + napi_value resultData = nullptr; + napi_create_object(callbackInner->env, &resultData); + TransToEventData(callbackInner->env, eventDataInner->data, resultData); + + napi_value callback = nullptr; + napi_value returnVal = nullptr; + napi_get_reference_value(callbackInner->env, callbackInner->callback, &callback); + napi_call_function(callbackInner->env, nullptr, callback, 1, &resultData, &returnVal); + if (callbackInner->once) { + HILOGI("ProcessEvent delete once callback callbackInfo = %{public}p", callbackInner); + napi_delete_reference(callbackInner->env, callbackInner->callback); + } + } + } + + void EventHandlerInstance::ProcessEvent([[maybe_unused]] const InnerEvent::Pointer& event) + { + uint32_t eventId = event->GetInnerEventId(); + HILOGI("ProcessEvent, eventId = %d", eventId); + auto subscribe = emitterInstances.find(eventId); + if (subscribe == emitterInstances.end()) { + HILOGW("ProcessEvent has no callback"); + return; + } + + CallbackInfos callbackInfos = subscribe->second; + HILOGI("ProcessEvent, size = %zu", callbackInfos.asyncCallbackInfo.size()); + EventData eventData = *(event->GetUniqueObject()); + for (auto iter = callbackInfos.asyncCallbackInfo.begin(); iter != callbackInfos.asyncCallbackInfo.end();) { + AsyncCallbackInfo* callbackInfo = *iter; + EventDataWorker* eventDataWorker = new EventDataWorker(); + eventDataWorker->data = eventData; + eventDataWorker->callbackInfo = callbackInfo; + + uv_loop_s *loop = nullptr; + napi_get_uv_event_loop(callbackInfo->env, &loop); + uv_work_t *work = new uv_work_t; + if (work == nullptr) { + HILOGI("uv_work_t instance is nullptr"); + return; + } + work->data = (void *)eventDataWorker; + uv_queue_work(loop, work, [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + EventDataWorker* eventDataInner = (EventDataWorker*)work->data; + ProcessCallback(eventDataInner); + delete eventDataInner; + eventDataInner = nullptr; + delete work; + work = nullptr; + }); + if (callbackInfo->once || callbackInfo->isDeleted) { + HILOGI("ProcessEvent once callback or isDeleted callback"); + iter = callbackInfos.asyncCallbackInfo.erase(iter); + if (callbackInfos.asyncCallbackInfo.begin() == callbackInfos.asyncCallbackInfo.end()) { + emitterInstances.erase(eventId); + HILOGI("ProcessEvent delete the last callback"); + break; + } + } else { + ++iter; + } + } + HILOGI("ProcessEvent end"); + } + + bool IsExistSameCallback(napi_env env, uint32_t eventIdValue, napi_value argv, bool once) + { + auto subscribe = emitterInstances.find(eventIdValue); + if (subscribe == emitterInstances.end()) { + return false; + } + vector callbackInfo = subscribe->second.asyncCallbackInfo; + size_t callbackSize = callbackInfo.size(); + napi_value callback = nullptr; + for (size_t i = 0; i < callbackSize; i++) { + if (callbackInfo[i]->isDeleted) { + continue; + } + if (callbackInfo[i]->env != env) { + continue; + } + napi_get_reference_value(callbackInfo[i]->env, callbackInfo[i]->callback, &callback); + bool isEq = false; + napi_strict_equals(env, argv, callback, &isEq); + if (!isEq) { + continue; + } + if (!once) { + if (callbackInfo[i]->once) { + HILOGI("JS_On change once to on"); + callbackInfo[i]->once = false; + } else { + HILOGI("JS_On already on"); + } + } else { + if (callbackInfo[i]->once) { + HILOGI("JS_Once already once"); + } else { + HILOGI("JS_Once change on to once"); + callbackInfo[i]->once = true; + } + } + return true; + } + return false; + } + + napi_value OnOrOnce(napi_env env, napi_callback_info cbinfo, bool once) + { + size_t argc = ARGC_NUM; + napi_value argv[ARGC_NUM] = {0}; + NAPI_CALL(env, napi_get_cb_info(env, cbinfo, &argc, argv, NULL, NULL)); + NAPI_ASSERT(env, argc >= ARGC_NUM, "requires 2 parameter"); + + napi_valuetype eventValueType; + napi_typeof(env, argv[0], &eventValueType); + NAPI_ASSERT(env, eventValueType == napi_object, "type mismatch for parameter 1"); + + napi_valuetype eventHandleType; + napi_typeof(env, argv[1], &eventHandleType); + NAPI_ASSERT(env, eventHandleType == napi_function, "type mismatch for parameter 2"); + + bool hasEventId = false; + napi_value eventId; + napi_has_named_property(env, argv[0], "eventId", &hasEventId); + NAPI_ASSERT(env, hasEventId, "Wrong argument 1"); + napi_get_named_property(env, argv[0], "eventId", &eventId); + uint32_t eventIdValue; + napi_get_value_uint32(env, eventId, &eventIdValue); + HILOGI("OnOrOnce eventIdValue:%{public}d", eventIdValue); + + if (!IsExistSameCallback(env, eventIdValue, argv[1], once)) { + AsyncCallbackInfo* callbackInfo = new AsyncCallbackInfo(); + callbackInfo->env = env; + callbackInfo->once = once; + napi_create_reference(env, argv[1], 1, &callbackInfo->callback); + emitterInstances[eventIdValue].asyncCallbackInfo.push_back(callbackInfo); + HILOGI("OnOrOnce callbackInfo = %{public}p", callbackInfo); + } + return nullptr; + } + + napi_value JS_On(napi_env env, napi_callback_info cbinfo) + { + HILOGI("JS_On start"); + OnOrOnce(env, cbinfo, false); + return nullptr; + } + + napi_value JS_Off(napi_env env, napi_callback_info cbinfo) + { + HILOGI("JS_Off start"); + size_t argc = 1; + napi_value argv[1] = {0}; + NAPI_CALL(env, napi_get_cb_info(env, cbinfo, &argc, argv, NULL, NULL)); + NAPI_ASSERT(env, argc >= 1, "requires 1 parameter"); + + napi_valuetype eventValueType; + napi_typeof(env, argv[0], &eventValueType); + NAPI_ASSERT(env, eventValueType == napi_number, "type mismatch for parameter 1"); + + uint32_t eventId; + napi_get_value_uint32(env, argv[0], &eventId); + auto subscribe = emitterInstances.find(eventId); + if (subscribe != emitterInstances.end()) { + for (auto callbackInfo : subscribe->second.asyncCallbackInfo) { + HILOGI("JS_Off callbackInfo = %{public}p", callbackInfo); + callbackInfo->isDeleted = true; + } + } + return nullptr; + } + + napi_value JS_Once(napi_env env, napi_callback_info cbinfo) + { + HILOGI("JS_Once start"); + OnOrOnce(env, cbinfo, true); + return nullptr; + } + + bool ParseEventData(napi_env env, napi_value key, napi_value data, Val* &val, char keyChars[NAPI_VALUE_STRING_LEN]) + { + napi_valuetype valueType; + napi_typeof(env, key, &valueType); + if (valueType != napi_valuetype::napi_string) { + HILOGI("param is discarded because the key type of the event params must be String."); + return false; + } + + size_t keyLength = 0; + napi_get_value_string_utf8(env, key, keyChars, NAPI_VALUE_STRING_LEN, &keyLength); + napi_value value = nullptr; + napi_get_named_property(env, data, keyChars, &value); + napi_typeof(env, value, &valueType); + if (valueType == napi_valuetype::napi_boolean) { + val->type = DataType::BOOL; + napi_get_value_bool(env, value, &(val->value.bValue)); + HILOGD("key:%{public}s value=%{public}d.", keyChars, val->value.bValue); + } else if (valueType == napi_valuetype::napi_number) { + val->type = DataType::INT; + napi_get_value_int32(env, value, &(val->value.nValue)); + HILOGD("key:%{public}s value=%{public}d.", keyChars, val->value.nValue); + } else if (valueType == napi_valuetype::napi_string) { + napi_get_value_string_utf8(env, value, val->value.cValue, NAPI_VALUE_STRING_LEN, &keyLength); + val->type = DataType::STRING; + HILOGD("key:%{public}s value=%{public}s.", keyChars, val->value.cValue); + } else { + HILOGI("param=%{public}s is discarded because the value type is invalid.", keyChars); + return false; + } + return true; + } + + bool EmitWithEventData(napi_env env, napi_value argv, uint32_t eventId, Priority priority) + { + napi_valuetype dataType; + napi_typeof(env, argv, &dataType); + NAPI_ASSERT(env, dataType == napi_object, "type mismatch for parameter 2"); + + bool hasData = false; + napi_has_named_property(env, argv, "data", &hasData); + if (hasData) { + napi_value data = nullptr; + napi_get_named_property(env, argv, "data", &data); + + napi_value keyArr = nullptr; + napi_status status = napi_get_property_names(env, data, &keyArr); + uint32_t len = 0; + status = napi_get_array_length(env, keyArr, &len); + + EventData eventData; + bool hasEventData = false; + for (uint32_t i = 0; i < len; i++) { + napi_value key = nullptr; + napi_get_element(env, keyArr, i, &key); + char keyChars[NAPI_VALUE_STRING_LEN] = {0}; + Val* val = new Val(); + if (!ParseEventData(env, key, data, val, keyChars)) { + delete val; + continue; + } + eventData.data.insert(make_pair(keyChars, *val)); + hasEventData = true; + delete val; + } + + if (hasEventData) { + HILOGI("sendevent with eventData id:%{public}d", eventId); + auto event = InnerEvent::Get(eventId, make_unique(eventData)); + eventHandler->SendEvent(event, 0, priority); + return true; + } + } + return false; + } + + bool IsExistValidCallback(napi_env env, uint32_t eventId) + { + auto subscribe = emitterInstances.find(eventId); + if (subscribe == emitterInstances.end()) { + HILOGW("JS_Emit has no callback"); + return false; + } + vector callbackInfo = subscribe->second.asyncCallbackInfo; + size_t callbackSize = callbackInfo.size(); + for (size_t i = 0; i < callbackSize; i++) { + if (!callbackInfo[i]->isDeleted) { + return true; + } + } + return false; + } + + napi_value JS_Emit(napi_env env, napi_callback_info cbinfo) + { + HILOGI("JS_Emit start"); + size_t argc = ARGC_NUM; + napi_value argv[ARGC_NUM] = {0}; + NAPI_CALL(env, napi_get_cb_info(env, cbinfo, &argc, argv, NULL, NULL)); + NAPI_ASSERT(env, argc >= 1, "requires more than 1 parameter"); + HILOGI("JS_Emit argc:%{public}zu", argc); + + napi_valuetype eventValueType; + napi_typeof(env, argv[0], &eventValueType); + NAPI_ASSERT(env, eventValueType == napi_object, "type mismatch for parameter 1"); + + bool hasEventId = false; + napi_value value; + napi_has_named_property(env, argv[0], "eventId", &hasEventId); + NAPI_ASSERT(env, hasEventId == true, "Wrong argument 1"); + napi_get_named_property(env, argv[0], "eventId", &value); + uint32_t eventId; + napi_get_value_uint32(env, value, &eventId); + HILOGI("JS_Emit eventIdValue:%{public}d", eventId); + + if (!IsExistValidCallback(env, eventId)) { + HILOGW("JS_Emit has no valid callback"); + return nullptr; + } + + bool hasPriority = false; + napi_has_named_property(env, argv[0], "priority", &hasPriority); + Priority priority = Priority::LOW; + if (hasPriority) { + napi_get_named_property(env, argv[0], "priority", &value); + uint32_t priorityValue; + napi_get_value_uint32(env, value, &priorityValue); + HILOGI("JS_Emit priority:%{public}d", priorityValue); + priority = static_cast(priorityValue); + } + + if (argc == ARGC_NUM && EmitWithEventData(env, argv[1], eventId, priority)) { + HILOGI("EmitWithEventData sucess"); + return nullptr; + } else { + HILOGI("JS_Emit sendevent without id:%{public}d", eventId); + auto event = InnerEvent::Get(eventId, make_unique()); + eventHandler->SendEvent(event, 0, priority); + return nullptr; + } + } + + napi_value EnumEventClassConstructor(napi_env env, napi_callback_info info) + { + napi_value thisArg = nullptr; + void *data = nullptr; + + napi_get_cb_info(env, info, nullptr, nullptr, &thisArg, &data); + + napi_value global = nullptr; + napi_get_global(env, &global); + + return thisArg; + } + + napi_value CreateEnumEventPriority(napi_env env, napi_value exports) + { + napi_value immediate = nullptr; + napi_value high = nullptr; + napi_value low = nullptr; + napi_value idle = nullptr; + + napi_create_uint32(env, (uint32_t)Priority::IMMEDIATE, &immediate); + napi_create_uint32(env, (uint32_t)Priority::HIGH, &high); + napi_create_uint32(env, (uint32_t)Priority::LOW, &low); + napi_create_uint32(env, (uint32_t)Priority::IDLE, &idle); + + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("IMMEDIATE", immediate), + DECLARE_NAPI_STATIC_PROPERTY("HIGH", high), + DECLARE_NAPI_STATIC_PROPERTY("LOW", low), + DECLARE_NAPI_STATIC_PROPERTY("IDLE", idle), + }; + napi_value result = nullptr; + napi_define_class(env, "EventPriority", NAPI_AUTO_LENGTH, EnumEventClassConstructor, nullptr, + sizeof(desc) / sizeof(*desc), desc, &result); + + napi_set_named_property(env, exports, "EventPriority", result); + + return exports; + } + + napi_value EmitterInit(napi_env env, napi_value exports) + { + HILOGE("enter"); + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("on", JS_On), + DECLARE_NAPI_FUNCTION("once", JS_Once), + DECLARE_NAPI_FUNCTION("off", JS_Off), + DECLARE_NAPI_FUNCTION("emit", JS_Emit), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + + CreateEnumEventPriority(env, exports); + + eventHandler = EventHandlerInstance::GetInstance(); + return exports; + } +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/napi/eventhandler/src/init.cpp b/interfaces/innerkits/napi/eventhandler/src/init.cpp new file mode 100644 index 0000000000..63bdfafc97 --- /dev/null +++ b/interfaces/innerkits/napi/eventhandler/src/init.cpp @@ -0,0 +1,44 @@ +/* + * 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 "events_emitter.h" + +#include "napi/native_api.h" +#include "napi/native_node_api.h" +namespace OHOS { +namespace AppExecFwk { +EXTERN_C_START +static napi_value Init(napi_env env, napi_value exports) +{ + EmitterInit(env, exports); + return exports; +} +EXTERN_C_END + +static napi_module _module = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "emitter", + .nm_priv = ((void *)0), + .reserved = {0} +}; + +extern "C" __attribute__((constructor)) void RegisterModule(void) +{ + napi_module_register(&_module); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/task_dispatcher/src/dispatcher/parallel_task_dispatcher_base.cpp b/interfaces/innerkits/task_dispatcher/src/dispatcher/parallel_task_dispatcher_base.cpp index 6967169e81..7f651672d5 100644 --- a/interfaces/innerkits/task_dispatcher/src/dispatcher/parallel_task_dispatcher_base.cpp +++ b/interfaces/innerkits/task_dispatcher/src/dispatcher/parallel_task_dispatcher_base.cpp @@ -122,7 +122,8 @@ std::shared_ptr ParallelTaskDispatcherBase::DelayDispatch( return nullptr; } TracePointBeforePost(innerTask, true, DELAY_DISPATCHER_TAG); - std::function callback = std::bind(&ParallelTaskDispatcherBase::InterceptedExecute, shared_from_this(), innerTask); + std::function callback = std::bind(&ParallelTaskDispatcherBase::InterceptedExecute, shared_from_this(), + innerTask); bool executeFlag = executor_->DelayExecute(callback, delayMs); if (!executeFlag) { APP_LOGE("ParallelTaskDispatcherBase::DelayDispatch execute failed"); diff --git a/interfaces/innerkits/task_dispatcher/src/threading/task_executor.cpp b/interfaces/innerkits/task_dispatcher/src/threading/task_executor.cpp index cb3e343e04..c4a6b100a1 100644 --- a/interfaces/innerkits/task_dispatcher/src/threading/task_executor.cpp +++ b/interfaces/innerkits/task_dispatcher/src/threading/task_executor.cpp @@ -94,7 +94,7 @@ std::shared_ptr TaskExecutor::GetTask(const std::shared_ptr std::shared_ptr nullRunnable = nullptr; std::shared_ptr next = nullptr; - for(;;){ + for (;;) { if (terminated_.load() && pendingTasks_->Empty()) { APP_LOGI("TaskExecutor::GetTask end: loop thread %{public}s is terminated", workerThread->GetThreadName().c_str()); @@ -203,7 +203,7 @@ bool TaskExecutor::EnsureConsumeStarted() void TaskExecutor::Consume() { - for(;;){ + for (;;) { if (terminated_.load() && delayTasks_->Empty()) { APP_LOGI("TaskExecutor::Consume delay task is empty"); break; diff --git a/interfaces/innerkits/task_dispatcher/src/threading/worker_pool.cpp b/interfaces/innerkits/task_dispatcher/src/threading/worker_pool.cpp index 0f37a1c575..c1ae3c5a56 100644 --- a/interfaces/innerkits/task_dispatcher/src/threading/worker_pool.cpp +++ b/interfaces/innerkits/task_dispatcher/src/threading/worker_pool.cpp @@ -71,6 +71,7 @@ bool WorkerPool::CheckConfigParams(const std::shared_ptr &conf int maxThreadCount = config->GetMaxThreadCount(); int coreThreadCount = config->GetCoreThreadCount(); + if (!CheckThreadCount(maxThreadCount, coreThreadCount)) { APP_LOGE("WorkerPool::CheckConfigParams parameters are illegal, maxThreadCount %{public}d is less than " "coreThreadCount %{public}d", @@ -238,7 +239,7 @@ bool WorkerPool::AddWorker(const std::shared_ptr &delegate, const std: std::unique_lock mLock(poolLock_); std::shared_ptr newThread = nullptr; - for(;;){ + for (;;) { unsigned int value = control_.load(); int num = GetWorkingThreadNum(value); if (num >= thread_limit_) { @@ -326,7 +327,7 @@ int WorkerPool::GetStateFromControl(unsigned int ctl) void WorkerPool::AdvanceStateTo(unsigned int target) { APP_LOGI("WorkerPool::AdvanceStateTo begin"); - for(;;){ + for (;;) { unsigned int current = control_.load(); if ((current >= target) || CompareAndSet(control_, current, CombineToControl(target, GetWorkingThreadNum(current)))) { diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/base_task_dispatcher_test/base_task_dispatcher_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/base_task_dispatcher_test/base_task_dispatcher_test.cpp index dd2ada38bd..b86f345d62 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/base_task_dispatcher_test/base_task_dispatcher_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/base_task_dispatcher_test/base_task_dispatcher_test.cpp @@ -16,14 +16,15 @@ #define private public #undef private #include "base_task_dispatcher.h" +#include "runnable.h" +#include "serial_task_dispatcher.h" +#include "task_dispatcher.h" +#include "task_dispatcher_context.h" + #include #include #include #include -#include "task_dispatcher_context.h" -#include "task_dispatcher.h" -#include "serial_task_dispatcher.h" -#include "runnable.h" using namespace testing; using namespace testing::ext; diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/serial_task_dispatcher_test/serial_task_dispatcher_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/serial_task_dispatcher_test/serial_task_dispatcher_test.cpp index e9033f2e9f..f85ceb402a 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/serial_task_dispatcher_test/serial_task_dispatcher_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/serial_task_dispatcher_test/serial_task_dispatcher_test.cpp @@ -19,10 +19,10 @@ #undef private #include "app_log_wrapper.h" #include "appexecfwk_errors.h" -#include "task_priority.h" -#include "task_executor.h" -#include "task.h" #include "default_worker_pool_config.h" +#include "task.h" +#include "task_executor.h" +#include "task_priority.h" using namespace testing; using namespace testing::ext; diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/spec_task_dispatcher_test/spec_task_dispatcher_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/spec_task_dispatcher_test/spec_task_dispatcher_test.cpp index 07212360d0..f55d58413f 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/spec_task_dispatcher_test/spec_task_dispatcher_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/spec_task_dispatcher_test/spec_task_dispatcher_test.cpp @@ -16,15 +16,17 @@ #define private public #undef private #include "spec_task_dispatcher.h" + +#include "event_runner.h" +#include "runnable.h" +#include "serial_task_dispatcher.h" +#include "task_dispatcher.h" +#include "task_dispatcher_context.h" + +#include +#include #include #include -#include -#include -#include "task_dispatcher_context.h" -#include "task_dispatcher.h" -#include "serial_task_dispatcher.h" -#include "runnable.h" -#include "event_runner.h" using namespace testing; using namespace testing::ext; diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/sync_task_test/sync_task_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/sync_task_test/sync_task_test.cpp index 522230b748..655dfe37f5 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/sync_task_test/sync_task_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/sync_task_test/sync_task_test.cpp @@ -17,11 +17,11 @@ #define private public #include "sync_task.h" #undef private +#include "app_log_wrapper.h" +#include "default_worker_pool_config.h" +#include "task.h" #include "task_priority.h" #include "task_executor.h" -#include "task.h" -#include "default_worker_pool_config.h" -#include "app_log_wrapper.h" using namespace testing; using namespace testing::ext; diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/task_dispatcher_context_test/task_dispatcher_context_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/task_dispatcher_context_test/task_dispatcher_context_test.cpp index bad87ebc86..ae5fd1d92b 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/task_dispatcher_context_test/task_dispatcher_context_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/task_dispatcher_context_test/task_dispatcher_context_test.cpp @@ -17,10 +17,10 @@ #define private public #include "task_dispatcher_context.h" #undef private +#include "default_worker_pool_config.h" +#include "task.h" #include "task_priority.h" #include "task_executor.h" -#include "task.h" -#include "default_worker_pool_config.h" using namespace testing; using namespace testing::ext; diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/work_thread_test/work_thread_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/work_thread_test/work_thread_test.cpp index bdb8d2af47..c7450520a3 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/work_thread_test/work_thread_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/work_thread_test/work_thread_test.cpp @@ -17,12 +17,12 @@ #define private public #include "work_thread.h" #undef private +#include "app_log_wrapper.h" +#include "default_thread_factory.h" +#include "default_worker_pool_config.h" #include "task_priority.h" #include "task_executor.h" #include "task.h" -#include "default_worker_pool_config.h" -#include "default_thread_factory.h" -#include "app_log_wrapper.h" using namespace testing; using namespace testing::ext; diff --git a/kits/BUILD.gn b/kits/BUILD.gn index 325663d3f6..bb315d455e 100755 --- a/kits/BUILD.gn +++ b/kits/BUILD.gn @@ -35,6 +35,7 @@ config("appkit_public_config") { visibility = [ ":*" ] include_dirs = [ "//base/global/resmgr_standard/interfaces/innerkits/include", + "//base/global/i18n_standard/frameworks/intl/include", "//third_party/icu/icu4c/source/common", ] } @@ -50,6 +51,8 @@ ohos_executable("appexec") { "//foundation/aafwk/standard/interfaces/innerkits/base/include", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/kits/appkit/native/ability_runtime/app", + "//foundation/appexecfwk/standard/kits/appkit/native/ability_runtime/context", "//foundation/appexecfwk/standard/kits/appkit/native/app/include", "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", "//utils/native/base/include", @@ -85,6 +88,9 @@ ohos_shared_library("appkit_native") { "$SUBSYSTEM_DIR/interfaces/innerkits/appexecfwk_core/include/appmgr", "$SUBSYSTEM_DIR/interfaces/innerkits/libeventhandler/include", "$SUBSYSTEM_DIR/kits/appkit/native/app/include", + "$SUBSYSTEM_DIR/kits/appkit/native/ability_runtime/app", + "$SUBSYSTEM_DIR/kits/appkit/native/ability_runtime/context", + "$SUBSYSTEM_DIR/kits/appkit/native", "//foundation/aafwk/standard/frameworks/kits/ability/native/include", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", "//foundation/aafwk/standard/services/abilitymgr/include", @@ -117,16 +123,20 @@ ohos_shared_library("appkit_native") { "$SUBSYSTEM_DIR/kits/appkit/native/app/src/main_thread.cpp", "$SUBSYSTEM_DIR/kits/appkit/native/app/src/ohos_application.cpp", "$SUBSYSTEM_DIR/kits/appkit/native/app/src/sys_mgr_client.cpp", + "$SUBSYSTEM_DIR/kits/appkit/native/ability_runtime/app/ability_stage.cpp", + "$SUBSYSTEM_DIR/kits/appkit/native/ability_runtime/app/js_ability_stage.cpp", ] cflags = [] if (target_cpu == "arm") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ + "$SUBSYSTEM_DIR/kits:app_context", "$SUBSYSTEM_DIR/common:libappexecfwk_common", "$SUBSYSTEM_DIR/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "$SUBSYSTEM_DIR/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", @@ -134,13 +144,75 @@ ohos_shared_library("appkit_native") { "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/multimodalinput/input/frameworks/proxy:libmmi-client", "//utils/native/base:utils", + "//third_party/icu/icu4c:shared_icuuc", + ] + + public_deps = [ + "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + "//base/global/i18n_standard/frameworks/intl:intl_util", + ] + external_deps = [ + "aafwk_standard:runtime", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + "bytrace_standard:bytrace_core", + ] + + part_name = "appexecfwk_standard" +} + +# build so +ohos_shared_library("app_context") { + include_dirs = [ + "$SUBSYSTEM_DIR/kits/appkit/native/app/include", + "$SUBSYSTEM_DIR/kits/appkit/native/ability_runtime/context", + "$SUBSYSTEM_DIR/interfaces/innerkits/appexecfwk_core/include/bundlemgr", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//utils/system/safwk/native/include", + ] + + configs = [ ":appkit_config" ] + + public_configs = [ ":appkit_public_config" ] + + sources = [ + "$SUBSYSTEM_DIR/kits/appkit/native/ability_runtime/context/context_impl.cpp", + "$SUBSYSTEM_DIR/kits/appkit/native/ability_runtime/context/js_context_utils.cpp", + "$SUBSYSTEM_DIR/kits/appkit/native/ability_runtime/context/js_hap_module_info_utils.cpp", + "$SUBSYSTEM_DIR/kits/appkit/native/ability_runtime/context/js_resource_manager_utils.cpp", + "$SUBSYSTEM_DIR/kits/appkit/native/app/src/sys_mgr_client.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "$SUBSYSTEM_DIR/common:libappexecfwk_common", + "$SUBSYSTEM_DIR/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "$SUBSYSTEM_DIR/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//foundation/multimodalinput/input/frameworks/proxy:libmmi-client", + "//utils/native/base:utils", + "//third_party/icu/icu4c:shared_icuuc", + ] + + public_deps = [ + "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + "//base/global/i18n_standard/frameworks/intl:intl_util", ] - public_deps = - [ "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr" ] external_deps = [ + "aafwk_standard:runtime", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "napi:ace_napi", ] part_name = "appexecfwk_standard" diff --git a/kits/appkit/napi/BUILD.gn b/kits/appkit/napi/BUILD.gn index 749594ea64..8c9d56bb6a 100644 --- a/kits/appkit/napi/BUILD.gn +++ b/kits/appkit/napi/BUILD.gn @@ -15,7 +15,11 @@ import("//build/ohos.gni") group("napi_packages") { deps = [ + "//foundation/appexecfwk/standard/kits/appkit/napi/ability_stage:abilitystage_napi", + "//foundation/appexecfwk/standard/kits/appkit/napi/ability_stage_context:abilitystagecontext_napi", "//foundation/appexecfwk/standard/kits/appkit/napi/appMgr:napi_app_mgr", "//foundation/appexecfwk/standard/kits/appkit/napi/bundlemgr:bundle", + "//foundation/appexecfwk/standard/kits/appkit/napi/context:context_napi", + "//foundation/appexecfwk/standard/kits/appkit/napi/launchermgr:innerbundlemanager", ] } diff --git a/kits/appkit/napi/ability_stage/BUILD.gn b/kits/appkit/napi/ability_stage/BUILD.gn new file mode 100644 index 0000000000..d46977be3e --- /dev/null +++ b/kits/appkit/napi/ability_stage/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") + +ts2abc_gen_abc("gen_ability_stage_abc") { + src_js = rebase_path("ability_stage.js") + dst_file = rebase_path(target_out_dir + "/ability_stage.abc") + in_puts = [ "ability_stage.js" ] + out_puts = [ target_out_dir + "/ability_stage.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("ability_stage_js") { + input = "ability_stage.js" + output = target_out_dir + "/ability_stage.o" +} + +gen_js_obj("ability_stage_abc") { + input = get_label_info(":gen_ability_stage_abc", "target_out_dir") + "/ability_stage.abc" + output = target_out_dir + "/ability_stage_abc.o" + dep = ":gen_ability_stage_abc" +} + +ohos_shared_library("abilitystage_napi") { + sources = [ "ability_stage_module.cpp" ] + + deps = [ + ":ability_stage_abc", + ":ability_stage_js", + ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module/application" + subsystem_name = "appexecfwk" + part_name = "appexecfwk_standard" +} diff --git a/kits/appkit/napi/ability_stage/ability_stage.js b/kits/appkit/napi/ability_stage/ability_stage.js new file mode 100644 index 0000000000..64adc75cb8 --- /dev/null +++ b/kits/appkit/napi/ability_stage/ability_stage.js @@ -0,0 +1,21 @@ +/* + * 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. + */ + +class AbilityStage { + constructor() {} + onCreate() {} +} + +export default AbilityStage diff --git a/kits/appkit/napi/ability_stage/ability_stage_module.cpp b/kits/appkit/napi/ability_stage/ability_stage_module.cpp new file mode 100644 index 0000000000..798d608b34 --- /dev/null +++ b/kits/appkit/napi/ability_stage/ability_stage_module.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "native_engine/native_engine.h" + +extern const char _binary_ability_stage_js_start[]; +extern const char _binary_ability_stage_js_end[]; +extern const char _binary_ability_stage_abc_start[]; +extern const char _binary_ability_stage_abc_end[]; + +extern "C" __attribute__((constructor)) +void NAPI_application_AbilityStage_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.AbilityStage", + .fileName = "application/libabilitystage_napi.so/ability_stage.js", + }; + + moduleManager->Register(&newModuleInfo); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_application_AbilityStage_GetJSCode(const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_ability_stage_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_ability_stage_js_end - _binary_ability_stage_js_start; + } +} + +// ability_stage JS register +extern "C" __attribute__((visibility("default"))) +void NAPI_application_AbilityStage_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_ability_stage_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_ability_stage_abc_end - _binary_ability_stage_abc_start; + } +} \ No newline at end of file diff --git a/kits/appkit/napi/ability_stage_context/BUILD.gn b/kits/appkit/napi/ability_stage_context/BUILD.gn new file mode 100644 index 0000000000..bd96b0d07f --- /dev/null +++ b/kits/appkit/napi/ability_stage_context/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") + +ts2abc_gen_abc("gen_ability_stage_context_abc") { + src_js = rebase_path("ability_stage_context.js") + dst_file = rebase_path(target_out_dir + "/ability_stage_context.abc") + in_puts = [ "ability_stage_context.js" ] + out_puts = [ target_out_dir + "/ability_stage_context.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("ability_stage_context_js") { + input = "ability_stage_context.js" + output = target_out_dir + "/ability_stage_context.o" +} + +gen_js_obj("ability_stage_context_abc") { + input = get_label_info(":gen_ability_stage_context_abc", "target_out_dir") + "/ability_stage_context.abc" + output = target_out_dir + "/ability_stage_context_abc.o" + dep = ":gen_ability_stage_context_abc" +} + +ohos_shared_library("abilitystagecontext_napi") { + sources = [ "ability_stage_context_module.cpp" ] + + deps = [ + ":ability_stage_context_abc", + ":ability_stage_context_js", + ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module/application" + subsystem_name = "appexecfwk" + part_name = "appexecfwk_standard" +} diff --git a/kits/appkit/napi/ability_stage_context/ability_stage_context.js b/kits/appkit/napi/ability_stage_context/ability_stage_context.js new file mode 100644 index 0000000000..247b206e50 --- /dev/null +++ b/kits/appkit/napi/ability_stage_context/ability_stage_context.js @@ -0,0 +1,26 @@ +/* + * 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. + */ + +var Context = requireNapi("application.Context") + +class AbilityStageContext extends Context { + constructor(obj) { + super(obj) + + this.currentHapModuleInfo = obj.currentHapModuleInfo + } +} + +export default AbilityStageContext diff --git a/kits/appkit/napi/ability_stage_context/ability_stage_context_module.cpp b/kits/appkit/napi/ability_stage_context/ability_stage_context_module.cpp new file mode 100644 index 0000000000..d68251793c --- /dev/null +++ b/kits/appkit/napi/ability_stage_context/ability_stage_context_module.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "native_engine/native_engine.h" + +extern const char _binary_ability_stage_context_js_start[]; +extern const char _binary_ability_stage_context_js_end[]; +extern const char _binary_ability_stage_context_abc_start[]; +extern const char _binary_ability_stage_context_abc_end[]; + +extern "C" __attribute__((constructor)) +void NAPI_application_AbilityStageContext_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.AbilityStageContext", + .fileName = "application/libabilitystagecontext_napi.so/ability_stage_context.js", + }; + + moduleManager->Register(&newModuleInfo); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_application_AbilityStageContext_GetJSCode(const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_ability_stage_context_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_ability_stage_context_js_end - _binary_ability_stage_context_js_start; + } +} + +// ability_stage_context JS register +extern "C" __attribute__((visibility("default"))) +void NAPI_application_AbilityStageContext_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_ability_stage_context_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_ability_stage_context_abc_end - _binary_ability_stage_context_abc_start; + } +} \ No newline at end of file diff --git a/kits/appkit/napi/appMgr/app_mgr.cpp b/kits/appkit/napi/appMgr/app_mgr.cpp index bedc57148c..63b43fb6d5 100755 --- a/kits/appkit/napi/appMgr/app_mgr.cpp +++ b/kits/appkit/napi/appMgr/app_mgr.cpp @@ -15,15 +15,15 @@ #include "app_mgr.h" +#include #include #include -#include #include -#include "ipc_skeleton.h" -#include "system_ability_definition.h" #include "if_system_ability_manager.h" +#include "ipc_skeleton.h" #include "iservice_registry.h" +#include "system_ability_definition.h" using namespace OHOS; using namespace OHOS::AAFwk; diff --git a/kits/appkit/napi/appMgr/app_mgr.h b/kits/appkit/napi/appMgr/app_mgr.h index e8f462e214..03c9c61a13 100644 --- a/kits/appkit/napi/appMgr/app_mgr.h +++ b/kits/appkit/napi/appMgr/app_mgr.h @@ -16,12 +16,12 @@ #ifndef APP_MGR_H #define APP_MGR_H -#include "napi/native_common.h" #include -#include "napi/native_node_api.h" -#include "hilog_wrapper.h" #include "ability_manager_interface.h" +#include "hilog_wrapper.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" struct AsyncCallbackInfo { napi_env env; diff --git a/kits/appkit/napi/context/BUILD.gn b/kits/appkit/napi/context/BUILD.gn new file mode 100644 index 0000000000..2b95245e21 --- /dev/null +++ b/kits/appkit/napi/context/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") + +ts2abc_gen_abc("gen_context_abc") { + src_js = rebase_path("context.js") + dst_file = rebase_path(target_out_dir + "/context.abc") + in_puts = [ "context.js" ] + out_puts = [ target_out_dir + "/context.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("context_js") { + input = "context.js" + output = target_out_dir + "/context.o" +} + +gen_js_obj("context_abc") { + input = get_label_info(":gen_context_abc", "target_out_dir") + "/context.abc" + output = target_out_dir + "/context_abc.o" + dep = ":gen_context_abc" +} + +ohos_shared_library("context_napi") { + sources = [ "context_module.cpp" ] + + deps = [ + ":context_abc", + ":context_js", + ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module/application" + subsystem_name = "appexecfwk" + part_name = "appexecfwk_standard" +} diff --git a/kits/appkit/napi/context/context.js b/kits/appkit/napi/context/context.js new file mode 100644 index 0000000000..d28e3283fd --- /dev/null +++ b/kits/appkit/napi/context/context.js @@ -0,0 +1,39 @@ +/* + * 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. + */ + +class Context { + constructor(obj) { + this.__context_impl__ = obj + + this.resourceManager = obj.resourceManager + this.applicationInfo = obj.applicationInfo + this.cacheDir = obj.cacheDir + this.tempDir = obj.tempDir + this.filesDir = obj.filesDir + this.distributedFilesDir = obj.distributedFilesDir + this.databaseDir = obj.databaseDir + this.storageDir = obj.storageDir + this.bundleCodeDir = obj.bundleCodeDir + } + + createBundleContext(bundleName) { + return this.__context_impl__.createBundleContext(bundleName) + } + getApplicationContext() { + return this.__context_impl__.getApplicationContext() + } +} + +export default Context diff --git a/kits/appkit/napi/context/context_module.cpp b/kits/appkit/napi/context/context_module.cpp new file mode 100644 index 0000000000..a0f7b55e01 --- /dev/null +++ b/kits/appkit/napi/context/context_module.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "native_engine/native_engine.h" + +extern const char _binary_context_js_start[]; +extern const char _binary_context_js_end[]; +extern const char _binary_context_abc_start[]; +extern const char _binary_context_abc_end[]; + +extern "C" __attribute__((constructor)) +void NAPI_application_Context_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.Context", + .fileName = "application/libcontext_napi.so/context.js", + }; + + moduleManager->Register(&newModuleInfo); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_application_Context_GetJSCode(const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_context_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_context_js_end - _binary_context_js_start; + } +} + +// context JS register +extern "C" __attribute__((visibility("default"))) +void NAPI_application_Context_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_context_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_context_abc_end - _binary_context_abc_start; + } +} \ No newline at end of file diff --git a/kits/appkit/napi/launchermgr/BUILD.gn b/kits/appkit/napi/launchermgr/BUILD.gn new file mode 100644 index 0000000000..9ce473b2fa --- /dev/null +++ b/kits/appkit/napi/launchermgr/BUILD.gn @@ -0,0 +1,54 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +ohos_shared_library("innerbundlemanager") { + include_dirs = [ + "//foundation/ace/napi/interfaces/kits", + "//third_party/node/src", + "//third_party/libuv/include", + "//foundation/aafwk/standard/services/common/include", + "//utils/system/safwk/native/include", + "./", + ] + + sources = [ + "js_launcher.cpp", + "js_launcher_mgr.cpp", + "bundle_status_callback.cpp", + ] + + deps = [ + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/ace/napi:ace_napi", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "ipc:ipc_core", + ] + + relative_install_dir = "module/bundle" + subsystem_name = "appexecfwk" + part_name = "appexecfwk_standard" +} diff --git a/kits/appkit/napi/launchermgr/bundle_status_callback.cpp b/kits/appkit/napi/launchermgr/bundle_status_callback.cpp new file mode 100644 index 0000000000..cb7f1aa2d9 --- /dev/null +++ b/kits/appkit/napi/launchermgr/bundle_status_callback.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include + +#include "bundle_status_callback.h" + +#include "hilog_wrapper.h" +#include "napi/native_common.h" + +BundleStatusCallback::BundleStatusCallback(napi_env env, napi_ref addedCallback, + napi_ref updatedCallback, + napi_ref removeCallback) + : env_(env), addedCallback_(addedCallback), + updatedCallback_(updatedCallback), removeCallback_(removeCallback) {} + +BundleStatusCallback::~BundleStatusCallback() +{ + napi_delete_reference(env_, addedCallback_); + napi_delete_reference(env_, updatedCallback_); + napi_delete_reference(env_, removeCallback_); +} + +void BundleStatusCallback::OnBundleAdded(const std::string &bundleName, const int userId) +{ + napi_value callback = nullptr; + napi_value placeHolder = nullptr; + napi_value result[2] = { 0 }; + napi_get_reference_value(env_, addedCallback_, &callback); + napi_create_string_utf8(env_, bundleName.c_str(), NAPI_AUTO_LENGTH, &result[0]); + napi_create_uint32(env_, userId, &result[1]); + napi_call_function(env_, nullptr, callback, sizeof(result) / sizeof(result[0]), result, &placeHolder); +} + +void BundleStatusCallback::OnBundleUpdated(const std::string &bundleName, const int userId) +{ + napi_value callback = nullptr; + napi_value placeHolder = nullptr; + napi_value result[2] = { 0 }; + napi_get_undefined(env_, &result[0]); + napi_get_reference_value(env_, updatedCallback_, &callback); + napi_create_string_utf8(env_, bundleName.c_str(), NAPI_AUTO_LENGTH, &result[0]); + napi_create_uint32(env_, userId, &result[1]); + napi_call_function(env_, nullptr, callback, sizeof(result) / sizeof(result[0]), result, &placeHolder); +} + +void BundleStatusCallback::OnBundleRemoved(const std::string &bundleName, const int userId) +{ + napi_value callback = nullptr; + napi_value placeHolder = nullptr; + napi_value result[2] = { 0 }; + napi_get_undefined(env_, &result[0]); + napi_get_reference_value(env_, removeCallback_, &callback); + napi_create_string_utf8(env_, bundleName.c_str(), NAPI_AUTO_LENGTH, &result[0]); + napi_create_uint32(env_, userId, &result[1]); + napi_call_function(env_, nullptr, callback, sizeof(result) / sizeof(result[0]), result, &placeHolder); +} \ No newline at end of file diff --git a/kits/appkit/napi/launchermgr/bundle_status_callback.h b/kits/appkit/napi/launchermgr/bundle_status_callback.h new file mode 100644 index 0000000000..1e6be15cf5 --- /dev/null +++ b/kits/appkit/napi/launchermgr/bundle_status_callback.h @@ -0,0 +1,46 @@ +/* + * 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 LAUNCHER_STATUS_CALLBACK_H +#define LAUNCHER_STATUS_CALLBACK_H + +#include +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +#include "bundle_status_callback_interface.h" +#include "iremote_stub.h" +#include "nocopyable.h" + +class BundleStatusCallback : public OHOS::IRemoteStub { +public: + BundleStatusCallback() = default; + BundleStatusCallback(napi_env env, napi_ref addedCallback, napi_ref updatedCallback, napi_ref removeCallback); + virtual ~BundleStatusCallback(); + virtual void OnBundleStateChanged(const uint8_t installType, const int32_t resultCode, const std::string &resultMsg, + const std::string &bundleName) override {}; + virtual void OnBundleAdded(const std::string &bundleName, const int userId) override; + virtual void OnBundleUpdated(const std::string &bundleName, const int userId) override; + virtual void OnBundleRemoved(const std::string &bundleName, const int userId) override; + +private: + napi_env env_; + napi_ref addedCallback_; + napi_ref updatedCallback_; + napi_ref removeCallback_; + DISALLOW_COPY_AND_MOVE(BundleStatusCallback); +}; + +#endif // LAUNCHER_STATUS_CALLBACK_H \ No newline at end of file diff --git a/kits/appkit/napi/launchermgr/js_launcher.cpp b/kits/appkit/napi/launchermgr/js_launcher.cpp new file mode 100644 index 0000000000..844aa8b3ba --- /dev/null +++ b/kits/appkit/napi/launchermgr/js_launcher.cpp @@ -0,0 +1,983 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "bundle_status_callback.h" +#include "hilog_wrapper.h" +#include "js_launcher_mgr.h" +#include "launcher_service.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace { +const std::string REGISTERCALLBACK = "BundleStatusChange"; +const std::string UNREGISTERCALLBACK = "BundleStatusChange"; +constexpr int32_t NAPI_RETURN_ZERO = 0; +constexpr int32_t NAPI_RETURN_ONE = 1; +constexpr int32_t OPERATION_SUCESS = 0; +constexpr int32_t OPERATION_FAILED = 1; +constexpr int32_t OPERATION_TYPE_MIAMATCH = 2; +constexpr int32_t INDEX_ONE = 1; +constexpr int32_t INDEX_TWO = 2; +constexpr int32_t INDEX_THREE = 3; +} + +struct AsyncHandleBundleContext { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + napi_deferred deferred = nullptr; + napi_ref callbackRef = 0; + OHOS::sptr bundleStatusCallback = nullptr; + std::vector launcherAbilityInfos; + std::vector shortcutInfos; + std::string bundleName; + std::string className; + int32_t userId = 0; + bool ret = false; + int32_t err = 0; + std::string message; +}; + +static OHOS::sptr GetLauncherService() +{ + return OHOS::AppExecFwk::JSLauncherMgr::GetLauncherService(); +} + +static void ParseString(napi_env env, napi_value value, std::string& result) +{ + size_t size = 0; + + if (napi_get_value_string_utf8(env, value, nullptr, NAPI_RETURN_ZERO, &size) != napi_ok) { + HILOG_ERROR("can not get string size"); + return; + } + + result.reserve(size + NAPI_RETURN_ONE); + result.resize(size); + if (napi_get_value_string_utf8(env, value, result.data(), (size + NAPI_RETURN_ONE), &size) != napi_ok) { + HILOG_ERROR("can not get string value"); + return; + } +} + +static bool ParseBundleStatusCallback(napi_env env, + OHOS::sptr& bundleStatusCallback, napi_value args) +{ + napi_status status; + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, args, &valueType)); + if (valueType != napi_object) { + HILOG_ERROR("param type mismatch!"); + return false; + } + + // parse added callback + napi_ref addCallback = nullptr; + napi_value addValue = nullptr; + status = napi_get_named_property(env, args, "add", &addValue); + NAPI_ASSERT(env, status == napi_ok, "property name incorrect!"); + napi_typeof(env, addValue, &valueType); + if (valueType != napi_function) { + HILOG_ERROR("add param type mismatch!"); + return false; + } + napi_create_reference(env, addValue, NAPI_RETURN_ONE, &addCallback); + + // parse updated callback + napi_ref updateCallback = nullptr; + napi_value updateValue = nullptr; + status = napi_get_named_property(env, args, "update", &updateValue); + NAPI_ASSERT(env, status == napi_ok, "property name incorrect!"); + napi_typeof(env, updateValue, &valueType); + if (valueType != napi_function) { + HILOG_ERROR("update param type mismatch!"); + return false; + } + napi_create_reference(env, updateValue, NAPI_RETURN_ONE, &updateCallback); + + // parse remove callback + napi_ref removeCallback = nullptr; + napi_value removeValue = nullptr; + status = napi_get_named_property(env, args, "remove", &removeValue); + NAPI_ASSERT(env, status == napi_ok, "property name incorrect!"); + napi_typeof(env, removeValue, &valueType); + if (valueType != napi_function) { + HILOG_ERROR("remove param type mismatch!"); + return false; + } + napi_create_reference(env, removeValue, NAPI_RETURN_ONE, &removeCallback); + + bundleStatusCallback = new BundleStatusCallback(env, addCallback, updateCallback, removeCallback); + + return true; +} + +static void ConvertApplicationInfo(napi_env env, napi_value objAppInfo, + const OHOS::AppExecFwk::ApplicationInfo &appInfo) +{ + napi_value nName; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, appInfo.name.c_str(), NAPI_AUTO_LENGTH, &nName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "name", nName)); + + napi_value nDescription; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, appInfo.description.c_str(), NAPI_AUTO_LENGTH, &nDescription)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "description", nDescription)); + + napi_value nDescriptionId; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, appInfo.descriptionId, &nDescriptionId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "descriptionId", nDescriptionId)); + + napi_value nIsSystemApp; + NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, appInfo.isSystemApp, &nIsSystemApp)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "systemApp", nIsSystemApp)); + + napi_value nEnabled; + NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, appInfo.enabled, &nEnabled)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "enabled", nEnabled)); + + napi_value nRemovable; + NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, appInfo.removable, &nRemovable)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "removable", nRemovable)); + + napi_value nLabel; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, appInfo.label.c_str(), NAPI_AUTO_LENGTH, &nLabel)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "label", nLabel)); + + napi_value nLabelId; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, appInfo.labelId, &nLabelId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "labelId", nLabelId)); + + napi_value nIconPath; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, appInfo.iconPath.c_str(), NAPI_AUTO_LENGTH, &nIconPath)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "icon", nIconPath)); + + napi_value nIconId; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, appInfo.iconId, &nIconId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "iconId", nIconId)); + + napi_value nSupportedModes; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, appInfo.supportedModes, &nSupportedModes)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "supportedModes", nSupportedModes)); + + napi_value nProcess; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, appInfo.process.c_str(), NAPI_AUTO_LENGTH, &nProcess)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "process", nProcess)); + + napi_value nModuleSourceDirs; + NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nModuleSourceDirs)); + for (size_t idx = 0; idx < appInfo.moduleSourceDirs.size(); idx++) { + napi_value nModuleSourceDir; + NAPI_CALL_RETURN_VOID(env, + napi_create_string_utf8(env, appInfo.moduleSourceDirs[idx].c_str(), + NAPI_AUTO_LENGTH, &nModuleSourceDir)); + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nModuleSourceDirs, idx, nModuleSourceDir)); + } + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "moduleSourceDirs", nModuleSourceDirs)); + + napi_value nPermissions; + NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nPermissions)); + for (size_t idx = 0; idx < appInfo.permissions.size(); idx++) { + napi_value nPermission; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, appInfo.permissions[idx].c_str(), NAPI_AUTO_LENGTH, &nPermission)); + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nPermissions, idx, nPermission)); + } + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "permissions", nPermissions)); + + napi_value nModuleInfos; + NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nModuleInfos)); + for (size_t idx = 0; idx < appInfo.moduleInfos.size(); idx++) { + napi_value objModuleInfos; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objModuleInfos)); + + napi_value nModuleName; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, + appInfo.moduleInfos[idx].moduleName.c_str(), + NAPI_AUTO_LENGTH, &nModuleName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objModuleInfos, "moduleName", nModuleName)); + + napi_value nModuleSourceDir; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, + appInfo.moduleInfos[idx].moduleSourceDir.c_str(), + NAPI_AUTO_LENGTH, &nModuleSourceDir)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objModuleInfos, "moduleSourceDir", nModuleSourceDir)); + + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nModuleInfos, idx, objModuleInfos)); + } + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "moduleInfos", nModuleInfos)); + + napi_value nEntryDir; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, appInfo.entryDir.c_str(), NAPI_AUTO_LENGTH, &nEntryDir)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "entryDir", nEntryDir)); + + napi_value nFlags; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, appInfo.flags, &nFlags)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "flags", nFlags)); + + HILOG_INFO("ConvertApplicationInfo entryDir=%{public}s.", appInfo.entryDir.c_str()); +} + +static void ConvertElementName(napi_env env, napi_value elementInfo, const OHOS::AppExecFwk::ElementName &elementName) +{ + // wrap deviceId + napi_value deviceId; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, elementName.GetDeviceID().c_str(), NAPI_AUTO_LENGTH, &deviceId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, elementInfo, "deviceId", deviceId)); + + // wrap bundleName + napi_value bundleName; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, elementName.GetBundleName().c_str(), NAPI_AUTO_LENGTH, &bundleName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, elementInfo, "bundleName", bundleName)); + + // wrap abilityName + napi_value abilityName; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, elementName.GetAbilityName().c_str(), NAPI_AUTO_LENGTH, &abilityName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, elementInfo, "abilityName", abilityName)); +} + +static void ConvertLauncherAbilityInfo(napi_env env, napi_value objAbilityInfo, + const OHOS::AppExecFwk::LauncherAbilityInfo &launcherAbilityInfo) +{ + // wrap labelId + napi_value labelId; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, launcherAbilityInfo.labelId, &labelId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "labelId", labelId)); + + // wrap iconId + napi_value iconId; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, launcherAbilityInfo.iconId, &iconId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "iconId", iconId)); + + // wrap userId + napi_value userId; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, launcherAbilityInfo.userId, &userId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "userId", userId)); + + // wrap installTime + napi_value installTime; + NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, launcherAbilityInfo.installTime, &installTime)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "installTime", installTime)); + + // wrap elementName + napi_value elementName; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &elementName)); + ConvertElementName(env, elementName, launcherAbilityInfo.elementName); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "elementName", elementName)); + + // wrap application + napi_value appInfo; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &appInfo)); + ConvertApplicationInfo(env, appInfo, launcherAbilityInfo.applicationInfo); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "applicationInfo", appInfo)); +} + +static bool ParseLauncherAbilityInfo( + napi_env env, napi_value result, + std::vector &launcherAbilityInfos) +{ + if (launcherAbilityInfos.empty()) { + return false; + } + size_t index = 0; + for (const auto& abilityInfo : launcherAbilityInfos) { + napi_value objAbilityInfo = nullptr; + napi_create_object(env, &objAbilityInfo); + ConvertLauncherAbilityInfo(env, objAbilityInfo, abilityInfo); + napi_set_element(env, result, index, objAbilityInfo); + index++; + } + return true; +} + +static void ConvertShortcutIntent(napi_env env, napi_value objShortcutInfo, + const OHOS::AppExecFwk::ShortcutIntent &shortcutIntent) +{ + napi_value nTargetBundle; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, shortcutIntent.targetBundle.c_str(), NAPI_AUTO_LENGTH, &nTargetBundle)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "targetBundle", nTargetBundle)); + napi_value nTargetClass; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, shortcutIntent.targetClass.c_str(), NAPI_AUTO_LENGTH, &nTargetClass)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "targetClass", nTargetClass)); +} + +static void ConvertShortcutInfo( + napi_env env, napi_value objShortcutInfo, + const OHOS::AppExecFwk::ShortcutInfo &shortcutInfo) +{ + // wrap id + napi_value shortId; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, + shortcutInfo.id.c_str(), NAPI_AUTO_LENGTH, &shortId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "id", shortId)); + + // wrap bundleName + napi_value bundleName; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, shortcutInfo.bundleName.c_str(), NAPI_AUTO_LENGTH, &bundleName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "bundleName", bundleName)); + + // wrap hostAbility + napi_value hostAbility; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, shortcutInfo.hostAbility.c_str(), NAPI_AUTO_LENGTH, &hostAbility)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "hostAbility", hostAbility)); + + // wrap icon + napi_value icon; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, shortcutInfo.icon.c_str(), NAPI_AUTO_LENGTH, &icon)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "icon", icon)); + + // wrap iconId + napi_value iconId; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, shortcutInfo.iconId, &iconId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "iconId", iconId)); + + // wrap label + napi_value label; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, shortcutInfo.label.c_str(), NAPI_AUTO_LENGTH, &label)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "label", label)); + + // wrap labelId + napi_value labelId; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, shortcutInfo.labelId, &labelId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "labelId", labelId)); + + // wrap disableMessage + napi_value disableMessage; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, shortcutInfo.disableMessage.c_str(), NAPI_AUTO_LENGTH, &disableMessage)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "disableMessage", disableMessage)); + + // wrap wants + napi_value intents; + NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &intents)); + for (size_t index = 0; index < shortcutInfo.intents.size(); ++index) { + napi_value intent; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &intent)); + ConvertShortcutIntent(env, intent, shortcutInfo.intents[index]); + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, intents, index, intent)); + } + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "wants", intents)); + + // wrap isStatic + napi_value isStatic; + NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, shortcutInfo.isStatic, &isStatic)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "isStatic", isStatic)); + + // wrap isHomeShortcut + napi_value isHomeShortcut; + NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, shortcutInfo.isHomeShortcut, &isHomeShortcut)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "isHomeShortcut", isHomeShortcut)); + + // wrap isEnabled + napi_value isEnabled; + NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, shortcutInfo.isEnables, &isEnabled)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "isEnabled", isEnabled)); +} + +static void ParseShortcutInfo(napi_env env, napi_value result, + const std::vector &shortcutInfos) +{ + if (shortcutInfos.empty()) { + HILOG_ERROR("launcher shortcut info is empty"); + return; + } + size_t index = 0; + for (const auto& item : shortcutInfos) { + napi_value objShortcutInfo; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objShortcutInfo)); + ConvertShortcutInfo(env, objShortcutInfo, item); + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, objShortcutInfo)); + index++; + } + return; +} + + +static bool InnerJSLauncherServiceOn(napi_env env, OHOS::sptr callbackRef) +{ + if (!callbackRef) { + HILOG_ERROR("Input null BundleStatusCallback"); + } + auto launcher = GetLauncherService(); + if (!launcher) { + HILOG_ERROR("can not get launcher"); + return false; + } + + auto result = launcher->RegisterCallback(callbackRef); + if (!result) { + HILOG_ERROR("RegisterBundleStatusCallback call error"); + return false; + } + return true; +} + +static napi_value JSLauncherServiceOn(napi_env env, napi_callback_info info) +{ + size_t requireArgc = 2; + size_t argc = 3; + napi_value argv[3] = { 0 }; + napi_value thisArg = nullptr; + void *data = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); + NAPI_ASSERT(env, argc >= requireArgc, "requires 2 parameter"); + std::string command; + + AsyncHandleBundleContext *asyncCallbackInfo = new AsyncHandleBundleContext(); + asyncCallbackInfo->env = env; + for (size_t i = 0; i < argc; ++i) { + napi_valuetype valueType = napi_undefined; + napi_typeof(env, argv[i], &valueType); + if ((i == 0) && (valueType == napi_string)) { + ParseString(env, argv[i], command); + } else if ((i == INDEX_ONE) && (valueType == napi_object)) { + bool res = ParseBundleStatusCallback(env, asyncCallbackInfo->bundleStatusCallback, argv[i]); + if (!res) { + asyncCallbackInfo->err = OPERATION_TYPE_MIAMATCH; + asyncCallbackInfo->message = "type mismatch"; + } + } else if ((i == INDEX_TWO) && (valueType == napi_function)) { + napi_create_reference(env, argv[i], NAPI_RETURN_ONE, &asyncCallbackInfo->callbackRef); + break; + } else { + asyncCallbackInfo->err = OPERATION_TYPE_MIAMATCH; + asyncCallbackInfo->message = "type mismatch"; + } + } + + napi_value promise = nullptr; + if (command != REGISTERCALLBACK) { + HILOG_ERROR("Input wrong command"); + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + return promise; + } + + if (asyncCallbackInfo->callbackRef == nullptr) { + napi_create_promise(env, &asyncCallbackInfo->deferred, &promise); + } else { + napi_get_undefined(env, &promise); + } + + napi_value resource = nullptr; + napi_create_string_utf8(env, "JSLauncherServiceOn", NAPI_AUTO_LENGTH, &resource); + + napi_create_async_work( + env, nullptr, resource, + [](napi_env env, void* data) { + AsyncHandleBundleContext* asyncCallbackInfo = (AsyncHandleBundleContext*)data; + if (!asyncCallbackInfo->err) { + asyncCallbackInfo->ret = InnerJSLauncherServiceOn(env, asyncCallbackInfo->bundleStatusCallback); + } + }, + [](napi_env env, napi_status status, void* data) { + AsyncHandleBundleContext* asyncCallbackInfo = (AsyncHandleBundleContext*)data; + napi_value result[2] = { 0 }; + // wrap result + if (asyncCallbackInfo->err) { + napi_create_uint32(env, asyncCallbackInfo->err, &result[0]); + napi_create_string_utf8(env, asyncCallbackInfo->message.c_str(), NAPI_AUTO_LENGTH, &result[1]); + } else { + if (asyncCallbackInfo->ret) { + napi_create_uint32(env, OPERATION_SUCESS, &result[0]); + napi_create_string_utf8(env, "register success", NAPI_AUTO_LENGTH, &result[1]); + } else { + napi_create_uint32(env, OPERATION_FAILED, &result[0]); + napi_create_string_utf8(env, "register failed", NAPI_AUTO_LENGTH, &result[1]); + } + } + // callback or promise return + if (asyncCallbackInfo->deferred) { + if (asyncCallbackInfo->ret) { + napi_resolve_deferred(env, asyncCallbackInfo->deferred, result[1]); + } else { + napi_reject_deferred(env, asyncCallbackInfo->deferred, result[0]); + } + } else { + napi_value callback = nullptr; + napi_value placeHolder = nullptr; + napi_get_reference_value(env, asyncCallbackInfo->callbackRef, &callback); + napi_call_function(env, nullptr, callback, sizeof(result) / sizeof(result[0]), result, &placeHolder); + napi_delete_reference(env, asyncCallbackInfo->callbackRef); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + }, + (void*)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + return promise; +} + +static bool InnerJSLauncherServiceOff() +{ + auto launcher = GetLauncherService(); + if (!launcher) { + HILOG_ERROR("can not get launcher"); + return false; + } + + auto result = launcher->UnRegisterCallback(); + if (!result) { + HILOG_ERROR("RegisterBundleStatusCallback call error"); + return false; + } + return true; +} + +static napi_value JSLauncherServiceOff(napi_env env, napi_callback_info info) +{ + size_t requireArgc = INDEX_ONE; + size_t argc = INDEX_TWO; + napi_value argv[INDEX_TWO] = { 0 }; + napi_value thisArg = nullptr; + void *data = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); + NAPI_ASSERT(env, argc >= requireArgc, "requires 1 parameter"); + std::string command; + AsyncHandleBundleContext *asyncCallbackInfo = new AsyncHandleBundleContext(); + asyncCallbackInfo->env = env; + for (size_t i = 0; i < argc; ++i) { + napi_valuetype valueType = napi_undefined; + napi_typeof(env, argv[i], &valueType); + if ((i == 0) && (valueType == napi_string)) { + ParseString(env, argv[i], command); + } else if ((i == INDEX_ONE) && (valueType == napi_function)) { + napi_create_reference(env, argv[i], NAPI_RETURN_ONE, &asyncCallbackInfo->callbackRef); + } else { + NAPI_ASSERT(env, false, "type mismatch"); + } + } + + napi_value promise = nullptr; + if (command != UNREGISTERCALLBACK) { + HILOG_ERROR("Input wrong command"); + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + return promise; + } + + if (asyncCallbackInfo->callbackRef == nullptr) { + napi_create_promise(env, &asyncCallbackInfo->deferred, &promise); + } else { + napi_get_undefined(env, &promise); + } + + napi_value resource = nullptr; + napi_create_string_utf8(env, "JSLauncherServiceOn", NAPI_AUTO_LENGTH, &resource); + + napi_create_async_work( + env, nullptr, resource, + [](napi_env env, void* data) { + AsyncHandleBundleContext* asyncCallbackInfo = (AsyncHandleBundleContext*)data; + asyncCallbackInfo->ret = InnerJSLauncherServiceOff(); + }, + [](napi_env env, napi_status status, void* data) { + AsyncHandleBundleContext* asyncCallbackInfo = (AsyncHandleBundleContext*)data; + napi_value result[INDEX_TWO] = { 0 }; + if (asyncCallbackInfo->ret) { + napi_create_uint32(env, 0, &result[0]); + napi_create_string_utf8(env, "unregister success", NAPI_AUTO_LENGTH, &result[INDEX_ONE]); + } else { + napi_create_uint32(env, INDEX_ONE, &result[0]); + napi_create_string_utf8(env, "unregister failed", NAPI_AUTO_LENGTH, &result[INDEX_ONE]); + } + if (asyncCallbackInfo->deferred) { + if (asyncCallbackInfo->ret) { + napi_resolve_deferred(env, asyncCallbackInfo->deferred, result[INDEX_ONE]); + } else { + napi_reject_deferred(env, asyncCallbackInfo->deferred, result[0]); + } + } else { + napi_value callback = nullptr; + napi_value placeHolder = nullptr; + napi_get_reference_value(env, asyncCallbackInfo->callbackRef, &callback); + napi_call_function(env, nullptr, callback, sizeof(result) / sizeof(result[0]), result, &placeHolder); + napi_delete_reference(env, asyncCallbackInfo->callbackRef); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + }, + (void*)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + return promise; +} + +static bool InnerJSGetAllLauncherAbilityInfos(napi_env env, uint32_t userId, + std::vector &launcherAbilityInfos) +{ + auto launcher = GetLauncherService(); + if (!launcher) { + HILOG_ERROR("can not get launcher"); + return false; + } + + auto result = launcher->GetAllLauncherAbilityInfos(userId, launcherAbilityInfos); + if (!result) { + HILOG_ERROR("GetAllLauncherAbilityInfos call error"); + return false; + } + return true; +} + +static napi_value JSGetAllLauncherAbilityInfos(napi_env env, napi_callback_info info) +{ + size_t argc = INDEX_TWO; + napi_value argv[INDEX_TWO] = { 0 }; + size_t requireArgc = INDEX_ONE; + napi_value thisArg = nullptr; + void *data = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); + NAPI_ASSERT(env, argc >= requireArgc, "requires 1 parameter"); + AsyncHandleBundleContext *asyncCallbackInfo = new AsyncHandleBundleContext(); + asyncCallbackInfo->env = env; + for (size_t i = 0; i < argc; ++i) { + napi_valuetype valueType = napi_undefined; + napi_typeof(env, argv[i], &valueType); + if ((i == 0) && (valueType == napi_number)) { + napi_get_value_int32(env, argv[i], &asyncCallbackInfo->userId); + } else if ((i == INDEX_ONE) && (valueType == napi_function)) { + napi_create_reference(env, argv[i], NAPI_RETURN_ONE, &asyncCallbackInfo->callbackRef); + break; + } else { + asyncCallbackInfo->err = OPERATION_TYPE_MIAMATCH; + asyncCallbackInfo->message = "type mismatch"; + } + } + napi_value promise = nullptr; + if (asyncCallbackInfo->callbackRef == nullptr) { + napi_create_promise(env, &asyncCallbackInfo->deferred, &promise); + } else { + napi_get_undefined(env, &promise); + } + napi_value resource = nullptr; + napi_create_string_utf8(env, "JSGetAllLauncherAbilityInfos", NAPI_AUTO_LENGTH, &resource); + + napi_create_async_work( + env, nullptr, resource, + [](napi_env env, void* data) { + AsyncHandleBundleContext* asyncCallbackInfo = (AsyncHandleBundleContext*)data; + if (!asyncCallbackInfo->err) { + asyncCallbackInfo->ret = InnerJSGetAllLauncherAbilityInfos(asyncCallbackInfo->env, + asyncCallbackInfo->userId, + asyncCallbackInfo->launcherAbilityInfos); + } + }, + [](napi_env env, napi_status status, void* data) { + AsyncHandleBundleContext* asyncCallbackInfo = (AsyncHandleBundleContext*)data; + napi_value result[INDEX_TWO] = { 0 }; + // wrap result + if (asyncCallbackInfo->err) { + napi_create_int32(env, asyncCallbackInfo->err, &result[0]); + napi_get_undefined(env, &result[INDEX_ONE]); + } else { + if (asyncCallbackInfo->ret) { + napi_create_int32(env, OPERATION_SUCESS, &result[0]); + napi_create_array(env, &result[INDEX_ONE]); + ParseLauncherAbilityInfo(env, result[INDEX_ONE], asyncCallbackInfo->launcherAbilityInfos); + } else { + napi_create_int32(env, OPERATION_FAILED, &result[0]); + napi_get_undefined(env, &result[INDEX_ONE]); + } + } + // return callback or promise + if (asyncCallbackInfo->deferred) { + if (asyncCallbackInfo->ret) { + napi_resolve_deferred(env, asyncCallbackInfo->deferred, result[INDEX_ONE]); + } else { + napi_reject_deferred(env, asyncCallbackInfo->deferred, result[0]); + } + } else { + napi_value callback = nullptr; + napi_value callResult = 0; + napi_value undefined = 0; + napi_get_reference_value(env, asyncCallbackInfo->callbackRef, &callback); + napi_call_function(env, undefined, callback, sizeof(result) / sizeof(result[0]), result, &callResult); + napi_delete_reference(env, asyncCallbackInfo->callbackRef); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + }, + (void*)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + return promise; +} + +static bool InnerJSGetLauncherAbilityInfos(napi_env env, std::string& bundleName, + uint32_t userId, std::vector& launcherAbilityInfos) +{ + auto launcher = GetLauncherService(); + if (!launcher) { + HILOG_ERROR("can not get launcher"); + return false; + } + + auto result = launcher->GetAbilityList(bundleName, userId, launcherAbilityInfos); + if (!result) { + HILOG_ERROR("GetAbilityList call error"); + return false; + } + return true; +} + +static napi_value JSGetLauncherAbilityInfos(napi_env env, napi_callback_info info) +{ + size_t argc = INDEX_THREE; + napi_value argv[INDEX_THREE] = { 0 }; + size_t requireArgc = INDEX_TWO; + napi_value thisArg = nullptr; + void *data = nullptr; + std::string bundleName; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); + NAPI_ASSERT(env, argc >= requireArgc, "requires 2 parameter"); + AsyncHandleBundleContext *asyncCallbackInfo = new AsyncHandleBundleContext(); + asyncCallbackInfo->env = env; + + for (size_t i = 0; i < argc; ++i) { + napi_valuetype valueType = napi_undefined; + napi_typeof(env, argv[i], &valueType); + if ((i == 0) && (valueType == napi_string)) { + ParseString(env, argv[i], asyncCallbackInfo->bundleName); + } else if ((i == INDEX_ONE) && (valueType == napi_number)) { + napi_get_value_int32(env, argv[i], &asyncCallbackInfo->userId); + } else if ((i == INDEX_TWO) && (valueType == napi_function)) { + napi_create_reference(env, argv[i], NAPI_RETURN_ONE, &asyncCallbackInfo->callbackRef); + break; + } else { + asyncCallbackInfo->err = OPERATION_TYPE_MIAMATCH; + asyncCallbackInfo->message = "type mismatch"; + } + } + + napi_value promise = nullptr; + if (asyncCallbackInfo->callbackRef == nullptr) { + napi_create_promise(env, &asyncCallbackInfo->deferred, &promise); + } else { + napi_get_undefined(env, &promise); + } + + napi_value resource = nullptr; + napi_create_string_utf8(env, "JSGetLauncherAbilityInfos", NAPI_AUTO_LENGTH, &resource); + napi_create_async_work( + env, nullptr, resource, + [](napi_env env, void* data) { + AsyncHandleBundleContext* asyncCallbackInfo = (AsyncHandleBundleContext*)data; + if (!asyncCallbackInfo->err) { + asyncCallbackInfo->ret = InnerJSGetLauncherAbilityInfos(asyncCallbackInfo->env, + asyncCallbackInfo->bundleName, + asyncCallbackInfo->userId, + asyncCallbackInfo->launcherAbilityInfos); + } + }, + [](napi_env env, napi_status status, void* data) { + AsyncHandleBundleContext* asyncCallbackInfo = (AsyncHandleBundleContext*)data; + napi_value result[INDEX_TWO] = { 0 }; + // wrap result + if (asyncCallbackInfo->err) { + napi_create_int32(env, asyncCallbackInfo->err, &result[0]); + napi_get_undefined(env, &result[INDEX_ONE]); + } else { + if (asyncCallbackInfo->ret) { + napi_create_uint32(env, OPERATION_SUCESS, &result[0]); + napi_create_array(env, &result[INDEX_ONE]); + ParseLauncherAbilityInfo(env, result[INDEX_ONE], asyncCallbackInfo->launcherAbilityInfos); + } else { + napi_create_uint32(env, OPERATION_FAILED, &result[0]); + napi_get_undefined(env, &result[INDEX_ONE]); + } + } + // return callback or promise + if (asyncCallbackInfo->deferred) { + if (asyncCallbackInfo->ret) { + napi_resolve_deferred(env, asyncCallbackInfo->deferred, result[INDEX_ONE]); + } else { + napi_reject_deferred(env, asyncCallbackInfo->deferred, result[0]); + } + } else { + napi_value callback = nullptr; + napi_value callResult = 0; + napi_value undefined = 0; + napi_get_reference_value(env, asyncCallbackInfo->callbackRef, &callback); + napi_call_function(env, undefined, callback, sizeof(result) / sizeof(result[0]), result, &callResult); + napi_delete_reference(env, asyncCallbackInfo->callbackRef); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + }, + (void*)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + return promise; +} + +static bool InnerJSGetShortcutInfos(napi_env env, const std::string& bundleName, + std::vector& shortcutInfos) +{ + auto launcher = GetLauncherService(); + if (!launcher) { + HILOG_ERROR("can not get launcher"); + return false; + } + auto result = launcher->GetShortcutInfos(bundleName, shortcutInfos); + if (!result) { + HILOG_ERROR("GetShortcutInfos call error"); + return false; + } + return true; +} + +static napi_value JSGetShortcutInfos(napi_env env, napi_callback_info info) +{ + size_t argc = INDEX_TWO; + napi_value argv[INDEX_TWO] = { 0 }; + size_t requireArgc = INDEX_ONE; + napi_value thisArg = nullptr; + void *data = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); + NAPI_ASSERT(env, argc >= requireArgc, "requires 1 parameter"); + AsyncHandleBundleContext *asyncCallbackInfo = new AsyncHandleBundleContext(); + asyncCallbackInfo->env = env; + + for (size_t i = 0; i < argc; ++i) { + napi_valuetype valueType = napi_undefined; + napi_typeof(env, argv[i], &valueType); + if ((i == 0) && (valueType == napi_string)) { + ParseString(env, argv[i], asyncCallbackInfo->bundleName); + } else if ((i == INDEX_ONE) && (valueType == napi_function)) { + napi_create_reference(env, argv[i], NAPI_RETURN_ONE, &asyncCallbackInfo->callbackRef); + break; + } else { + asyncCallbackInfo->err = OPERATION_TYPE_MIAMATCH; + asyncCallbackInfo->message = "type mismatch"; + } + } + napi_value promise = nullptr; + if (asyncCallbackInfo->callbackRef == nullptr) { + napi_create_promise(env, &asyncCallbackInfo->deferred, &promise); + } else { + napi_get_undefined(env, &promise); + } + napi_value resource = nullptr; + napi_create_string_utf8(env, "JSGetShortcutInfos", NAPI_AUTO_LENGTH, &resource); + + napi_create_async_work( + env, nullptr, resource, + [](napi_env env, void* data) { + AsyncHandleBundleContext* asyncCallbackInfo = (AsyncHandleBundleContext*)data; + if (!asyncCallbackInfo->err) { + asyncCallbackInfo->ret = InnerJSGetShortcutInfos(asyncCallbackInfo->env, + asyncCallbackInfo->bundleName, + asyncCallbackInfo->shortcutInfos); + } + }, + [](napi_env env, napi_status status, void* data) { + AsyncHandleBundleContext* asyncCallbackInfo = (AsyncHandleBundleContext*)data; + napi_value result[INDEX_TWO] = { 0 }; + // wrap result + if (asyncCallbackInfo->err) { + napi_create_int32(env, asyncCallbackInfo->err, &result[0]); + napi_get_undefined(env, &result[INDEX_ONE]); + } else { + if (asyncCallbackInfo->ret) { + napi_create_uint32(env, OPERATION_SUCESS, &result[0]); + napi_create_array(env, &result[INDEX_ONE]); + ParseShortcutInfo(env, result[INDEX_ONE], asyncCallbackInfo->shortcutInfos); + } else { + napi_create_uint32(env, OPERATION_FAILED, &result[0]); + napi_get_undefined(env, &result[INDEX_ONE]); + } + } + // return callback or promise + if (asyncCallbackInfo->deferred) { + if (asyncCallbackInfo->ret) { + napi_resolve_deferred(env, asyncCallbackInfo->deferred, result[1]); + } else { + napi_reject_deferred(env, asyncCallbackInfo->deferred, result[0]); + } + } else { + napi_value callback = nullptr; + napi_value callResult = 0; + napi_value undefined = 0; + napi_get_reference_value(env, asyncCallbackInfo->callbackRef, &callback); + napi_call_function(env, undefined, callback, sizeof(result) / sizeof(result[0]), result, &callResult); + napi_delete_reference(env, asyncCallbackInfo->callbackRef); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + }, + (void*)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + return promise; +} + +static napi_value LauncherServiceExport(napi_env env, napi_value exports) +{ + static napi_property_descriptor launcherDesc[] = { + DECLARE_NAPI_FUNCTION("on", JSLauncherServiceOn), + DECLARE_NAPI_FUNCTION("off", JSLauncherServiceOff), + DECLARE_NAPI_FUNCTION("getAllLauncherAbilityInfos", JSGetAllLauncherAbilityInfos), + DECLARE_NAPI_FUNCTION("getLauncherAbilityInfos", JSGetLauncherAbilityInfos), + DECLARE_NAPI_FUNCTION("getShortcutInfos", JSGetShortcutInfos), + }; + + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(launcherDesc) / sizeof(launcherDesc[0]), launcherDesc)); + return exports; +} + +static napi_module launcherServiceModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = LauncherServiceExport, + .nm_modname = "bundle.innerBundleManager", + .nm_priv = ((void*)0), + .reserved = { 0 }, +}; + +extern "C" __attribute__((constructor)) void LauncherServiceRegister() +{ + napi_module_register(&launcherServiceModule); +} + diff --git a/kits/appkit/napi/launchermgr/js_launcher_mgr.cpp b/kits/appkit/napi/launchermgr/js_launcher_mgr.cpp new file mode 100644 index 0000000000..2118e8ce2f --- /dev/null +++ b/kits/appkit/napi/launchermgr/js_launcher_mgr.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "js_launcher_mgr.h" +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +JSLauncherMgr::JSLauncherMgr() +{ + launcherService_ = new LauncherService(); +} + +JSLauncherMgr::~JSLauncherMgr(){} + +OHOS::sptr JSLauncherMgr::GetLauncherService() +{ + return DelayedSingleton::GetInstance()->launcherService_; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/kits/appkit/napi/launchermgr/js_launcher_mgr.h b/kits/appkit/napi/launchermgr/js_launcher_mgr.h new file mode 100644 index 0000000000..e35e2f251c --- /dev/null +++ b/kits/appkit/napi/launchermgr/js_launcher_mgr.h @@ -0,0 +1,42 @@ +/* + * 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 APPEXECFWK_JS_LAUNCHER_MGR_H +#define APPEXECFWK_JS_LAUNCHER_MGR_H + +#include +#include +#include + +#include "hilog_wrapper.h" +#include "launcher_service.h" +#include "nocopyable.h" +#include "singleton.h" + +namespace OHOS { +namespace AppExecFwk { +class JSLauncherMgr { + DECLARE_DELAYED_SINGLETON(JSLauncherMgr); + +public: + static OHOS::sptr GetLauncherService(); + +private: + OHOS::sptr launcherService_ = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // APPEXECFWK_JS_LAUNCHER_MGR_H diff --git a/kits/appkit/native/ability_runtime/app/ability_stage.cpp b/kits/appkit/native/ability_runtime/app/ability_stage.cpp new file mode 100644 index 0000000000..db0a5e979b --- /dev/null +++ b/kits/appkit/native/ability_runtime/app/ability_stage.cpp @@ -0,0 +1,90 @@ +/* + * 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_stage.h" + +#include "hilog_wrapper.h" +#include "js_ability_stage.h" +#include "runtime.h" + +namespace OHOS { +namespace AbilityRuntime { +std::shared_ptr AbilityStage::Create( + const std::unique_ptr& runtime, const AppExecFwk::HapModuleInfo& hapModuleInfo) +{ + if (!runtime) { + return std::make_shared(); + } + + switch (runtime->GetLanguage()) { + case Runtime::Language::JS: + return JsAbilityStage::Create(runtime, hapModuleInfo); + + default: + return std::make_shared(); + } +} + +void AbilityStage::OnCreate() const +{ + HILOG_INFO("AbilityStage::OnCreate come"); +} + +void AbilityStage::OnDestory() const +{ + HILOG_INFO("AbilityStage::OnDestory come"); +} + +std::shared_ptr AbilityStage::GetContext() const +{ + return context_; +} + +void AbilityStage::Init(std::shared_ptr context) +{ + this->context_ = context; +} + +void AbilityStage::AddAbility(const sptr &token, + std::shared_ptr abilityRecord) +{ + if (token == nullptr) { + HILOG_ERROR("AbilityStage::AddAbility failed, token is nullptr"); + return; + } + + if (abilityRecord == nullptr) { + HILOG_ERROR("AbilityStage::AddAbility failed, abilityRecord is nullptr"); + return; + } + + abilityRecords_[token] = abilityRecord; +} + +void AbilityStage::RemoveAbility(const sptr &token) +{ + if (token == nullptr) { + HILOG_ERROR("AbilityStage::RemoveAbility failed, token is nullptr"); + return; + } + abilityRecords_.erase(token); +} + +bool AbilityStage::ContainsAbility() +{ + return abilityRecords_.size() > 0; +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/kits/appkit/native/ability_runtime/app/ability_stage.h b/kits/appkit/native/ability_runtime/app/ability_stage.h new file mode 100644 index 0000000000..d554b205d7 --- /dev/null +++ b/kits/appkit/native/ability_runtime/app/ability_stage.h @@ -0,0 +1,56 @@ +/* + * 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 ABILITY_RUNTIME_ABILITY_STAGE_H +#define ABILITY_RUNTIME_ABILITY_STAGE_H + +#include +#include +#include + +#include "ability_local_record.h" +#include "ability_runtime/context/context.h" + +namespace OHOS { +namespace AbilityRuntime { +class Runtime; +/** + * @brief the hap level entity + * + * To share the data amony the abilities of a hap, + * and supply lifecycle func for the developers. + * + */ +class AbilityStage { +public: + static std::shared_ptr Create( + const std::unique_ptr& runtime, const AppExecFwk::HapModuleInfo& hapModuleInfo); + + AbilityStage() = default; + virtual ~AbilityStage() = default; + virtual void OnCreate() const; + virtual void OnDestory() const; + virtual void Init(std::shared_ptr context); + std::shared_ptr GetContext() const; + void AddAbility(const sptr &token, std::shared_ptr abilityRecord); + void RemoveAbility(const sptr &token); + bool ContainsAbility(); +private: + std::shared_ptr context_; + std::map, std::shared_ptr> abilityRecords_; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_ABILITY_STAGE_H \ No newline at end of file diff --git a/kits/appkit/native/ability_runtime/app/js_ability_stage.cpp b/kits/appkit/native/ability_runtime/app/js_ability_stage.cpp new file mode 100644 index 0000000000..4597bafe2e --- /dev/null +++ b/kits/appkit/native/ability_runtime/app/js_ability_stage.cpp @@ -0,0 +1,111 @@ +/* + * 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 "js_ability_stage.h" + +#include "hilog_wrapper.h" +#include "js_context_utils.h" +#include "js_runtime.h" +#include "js_runtime_utils.h" + +namespace OHOS { +namespace AbilityRuntime { +std::shared_ptr JsAbilityStage::Create( + const std::unique_ptr& runtime, const AppExecFwk::HapModuleInfo& hapModuleInfo) +{ + auto& jsRuntime = static_cast(*runtime); + + std::string srcPath(hapModuleInfo.name); + srcPath.append("/assets/js/"); + if (hapModuleInfo.srcPath.empty()) { + srcPath.append("AbilityStage.abc"); + } else { + srcPath.append(hapModuleInfo.srcPath); + srcPath.append("/AbilityStage.abc"); + } + + std::string moduleName(hapModuleInfo.moduleName); + moduleName.append("::").append("AbilityStage"); + + auto moduleObj = jsRuntime.LoadModule(moduleName, srcPath); + return std::make_shared(jsRuntime, std::move(moduleObj)); +} + +JsAbilityStage::JsAbilityStage(JsRuntime& jsRuntime, std::unique_ptr&& jsAbilityStageObj) + : jsRuntime_(jsRuntime), jsAbilityStageObj_(std::move(jsAbilityStageObj)) +{} + +JsAbilityStage::~JsAbilityStage() = default; + +void JsAbilityStage::Init(std::shared_ptr context) +{ + AbilityStage::Init(context); + + if (!context) { + HILOG_ERROR("context is nullptr"); + return; + } + + if (!jsAbilityStageObj_) { + return; + } + + HandleScope handleScope(jsRuntime_); + auto& engine = jsRuntime_.GetNativeEngine(); + + NativeObject* obj = ConvertNativeValueTo(jsAbilityStageObj_->Get()); + if (obj == nullptr) { + HILOG_ERROR("Failed to get AbilityStage object"); + return; + } + + NativeValue* contextObj = CreateJsBaseContext(engine, context); + auto shellContextRef = jsRuntime_.LoadSystemModule("application.AbilityStageContext", &contextObj, 1); + contextObj = shellContextRef->Get(); + + context->Bind(jsRuntime_, shellContextRef.release()); + obj->SetProperty("context", contextObj); +} + +void JsAbilityStage::OnCreate() const +{ + HILOG_INFO("JsAbilityStage::OnCreate come"); + + AbilityStage::OnCreate(); + + if (!jsAbilityStageObj_) { + HILOG_WARN("Not found AbilityStage.js"); + return; + } + + HandleScope handleScope(jsRuntime_); + auto& nativeEngine = jsRuntime_.GetNativeEngine(); + + NativeValue* value = jsAbilityStageObj_->Get(); + NativeObject* obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + HILOG_ERROR("Failed to get AbilityStage object"); + return; + } + + NativeValue* methodOnCreate = obj->GetProperty("onCreate"); + if (methodOnCreate == nullptr) { + HILOG_ERROR("Failed to get 'onCreate' from AbilityStage object"); + return; + } + nativeEngine.CallFunction(value, methodOnCreate, nullptr, 0); +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/kits/appkit/native/ability_runtime/app/js_ability_stage.h b/kits/appkit/native/ability_runtime/app/js_ability_stage.h new file mode 100644 index 0000000000..0d247baf59 --- /dev/null +++ b/kits/appkit/native/ability_runtime/app/js_ability_stage.h @@ -0,0 +1,44 @@ +/* + * 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 ABILITY_RUNTIME_JS_ABILITY_STAGE_H +#define ABILITY_RUNTIME_JS_ABILITY_STAGE_H + +#include "ability_stage.h" + +class NativeReference; + +namespace OHOS { +namespace AbilityRuntime { +class JsRuntime; +class JsAbilityStage : public AbilityStage { +public: + static std::shared_ptr Create( + const std::unique_ptr& runtime, const AppExecFwk::HapModuleInfo& hapModuleInfo); + + JsAbilityStage(JsRuntime& jsRuntime, std::unique_ptr&& jsAbilityStageObj); + ~JsAbilityStage() override; + + void Init(std::shared_ptr context) override; + + void OnCreate() const override; + +private: + JsRuntime& jsRuntime_; + std::unique_ptr jsAbilityStageObj_; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_JS_ABILITY_STAGE_H \ No newline at end of file diff --git a/kits/appkit/native/ability_runtime/context/bindable.h b/kits/appkit/native/ability_runtime/context/bindable.h new file mode 100644 index 0000000000..4fea92b45a --- /dev/null +++ b/kits/appkit/native/ability_runtime/context/bindable.h @@ -0,0 +1,86 @@ +/* + * 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 ABILITY_RUNTIME_BINDABLE_H +#define ABILITY_RUNTIME_BINDABLE_H + +#include + +namespace OHOS { +namespace AbilityRuntime { +class Runtime; + +class BindingObject final { +public: + template + BindingObject(Runtime& runtime, T* ptr) : runtime_(runtime), object_(ptr, SimpleRelease) {} + ~BindingObject() = default; + + template + T* Get() + { + return static_cast(object_.get()); + } + + void Reset() + { + object_.reset(); + } + + Runtime& GetRuntime() + { + return runtime_; + } + + BindingObject(const BindingObject&) = delete; + BindingObject& operator=(const BindingObject&) = delete; + BindingObject(BindingObject&&) = delete; + BindingObject& operator=(BindingObject&&) = delete; + +private: + template + static void SimpleRelease(void* ptr) + { + delete static_cast(ptr); + } + + Runtime& runtime_; + std::unique_ptr object_; +}; + +class Bindable { +public: + virtual ~Bindable() = default; + + template + void Bind(Runtime& runtime, T* object) + { + object_ = std::make_unique(runtime, object); + } + + const std::unique_ptr& GetBindingObject() const + { + return object_; + } + +protected: + Bindable() = default; + +private: + std::unique_ptr object_; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_BINDABLE_H \ No newline at end of file diff --git a/kits/appkit/native/ability_runtime/context/context.h b/kits/appkit/native/ability_runtime/context/context.h new file mode 100644 index 0000000000..f97a7769fb --- /dev/null +++ b/kits/appkit/native/ability_runtime/context/context.h @@ -0,0 +1,146 @@ +/* + * 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 ABILITY_RUNTIME_CONTEXT_H +#define ABILITY_RUNTIME_CONTEXT_H + +#include +#include + +#include "application_info.h" +#include "bindable.h" +#include "hap_module_info.h" +#include "resource_manager.h" + +namespace OHOS { +namespace AbilityRuntime { +class Context : public Bindable { +public: + Context() = default; + ~Context() override = default; + + /** + * @brief Obtains the Context object of the application. + * + * @return Returns the Context object of the application. + */ + static std::shared_ptr GetApplicationContext(); + + /** + * @brief Obtains the bundle name of the current ability. + * + * @return Returns the bundle name of the current ability. + */ + virtual std::string GetBundleName() const = 0; + + /** + * @brief Creates a Context object for an application with the given bundle name. + * + * @param bundleName Indicates the bundle name of the application. + * + * @return Returns a Context object created for the specified application. + */ + virtual std::shared_ptr CreateBundleContext(const std::string &bundleName) = 0; + + /** + * @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. + */ + virtual std::shared_ptr GetApplicationInfo() const = 0; + + /** + * @brief Obtains a resource manager. + * + * @return Returns a ResourceManager object. + */ + virtual std::shared_ptr GetResourceManager() const = 0; + + /** + * @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. + */ + virtual std::string GetBundleCodePath() const = 0; + + /** + * @brief Obtains the HapModuleInfo object of the application. + * + * @return Returns the HapModuleInfo object of the application. + */ + virtual std::shared_ptr GetHapModuleInfo() const = 0; + + /** + * @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. + */ + virtual std::string GetBundleCodeDir() = 0; + + /** + * @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. + */ + virtual std::string GetCacheDir() = 0; + + /** + * @brief Obtains the temporary directory. + * + * @return Returns the application temporary directory. + */ + virtual std::string GetTempDir() = 0; + + /** + * @brief Obtains the directory for storing files for the application on the device's internal storage. + * + * @return Returns the application file directory. + */ + virtual std::string GetFilesDir() = 0; + + /** + * @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. + */ + virtual std::string GetDatabaseDir() = 0; + + /** + * @brief Obtains the path storing the storage file of the application. + * + * @return Returns the local storage file. + */ + virtual std::string GetStorageDir() = 0; + + /** + * @brief Obtains the path distributed file of the application + * + * @return Returns the distributed file. + */ + virtual std::string GetDistributedFilesDir() = 0; + +protected: + static std::shared_ptr appContext_; + static std::mutex contextMutex_; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_CONTEXT_H diff --git a/kits/appkit/native/ability_runtime/context/context_impl.cpp b/kits/appkit/native/ability_runtime/context/context_impl.cpp new file mode 100644 index 0000000000..c9f22bb3fa --- /dev/null +++ b/kits/appkit/native/ability_runtime/context/context_impl.cpp @@ -0,0 +1,322 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "context_impl.h" + +#include "hilog_wrapper.h" +#include "ipc_singleton.h" +#include "locale_config.h" +#include "sys_mgr_client.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AbilityRuntime { +const int64_t ContextImpl::CONTEXT_CREATE_BY_SYSTEM_APP(0x00000001); +const std::string ContextImpl::CONTEXT_BUNDLECODE_BASE("/data/app/base/"); +const std::string ContextImpl::CONTEXT_BUNDLECODE("/data/storage/app/base"); +const std::string ContextImpl::CONTEXT_BUNDLE("/bundle/"); +const std::string ContextImpl::CONTEXT_DISTRIBUTEDFILES_BASE_BEFORE("/mnt/hmdfs/"); +const std::string ContextImpl::CONTEXT_DISTRIBUTEDFILES_BASE_MIDDLE("/device_view/local/data/"); +const std::string ContextImpl::CONTEXT_DISTRIBUTEDFILES("distributedfiles"); +const std::string ContextImpl::CONTEXT_FILE_SEPARATOR("/"); +const std::string ContextImpl::CONTEXT_DATA("/data/"); +const std::string ContextImpl::CONTEXT_BASE("/data/storage/"); +const std::string ContextImpl::CONTEXT_PRIVATE("/private/"); +const std::string ContextImpl::CONTEXT_CACHES("caches"); +const std::string ContextImpl::CONTEXT_STORAGE("storage"); +const std::string ContextImpl::CONTEXT_DATABASE("database"); +const std::string ContextImpl::CONTEXT_TEMP("/temp"); +const std::string ContextImpl::CONTEXT_FILES("/files"); +const std::string ContextImpl::CONTEXT_CE("ce"); + +std::string ContextImpl::GetBundleName() const +{ + if (parentContext_ != nullptr) { + return parentContext_->GetBundleName(); + } + return (applicationInfo_ != nullptr) ? applicationInfo_->bundleName : ""; +} + +std::string ContextImpl::GetBundleCodeDir() +{ + std::string dir; + if (IsCreateBySystemApp()) { + dir = CONTEXT_BUNDLECODE_BASE + GetBundleName(); + } else { + dir = CONTEXT_BUNDLECODE; + } + HILOG_DEBUG("ContextImpl::GetBundleCodeDir:%{public}s", dir.c_str()); + return dir; +} + +std::string ContextImpl::GetCacheDir() +{ + std::string dir = GetBaseDir() + CONTEXT_PRIVATE + CONTEXT_CACHES; + HILOG_DEBUG("ContextImpl::GetCacheDir:%{public}s", dir.c_str()); + return dir; +} + +std::string ContextImpl::GetDatabaseDir() +{ + std::string dir = GetBaseDir() + CONTEXT_PRIVATE + CONTEXT_DATABASE; + HILOG_DEBUG("ContextImpl::GetDatabaseDir:%{public}s", dir.c_str()); + return dir; +} + +std::string ContextImpl::GetStorageDir() +{ + std::string dir = GetBaseDir() + CONTEXT_PRIVATE + CONTEXT_STORAGE; + HILOG_DEBUG("ContextImpl::GetStorageDir:%{public}s", dir.c_str()); + return dir; +} + +std::string ContextImpl::GetTempDir() +{ + std::string dir = GetBaseDir() + CONTEXT_TEMP; + HILOG_DEBUG("ContextImpl::GetTempDir:%{public}s", dir.c_str()); + return dir; +} + +std::string ContextImpl::GetFilesDir() +{ + std::string dir = GetBaseDir() + CONTEXT_FILES; + HILOG_DEBUG("ContextImpl::GetFilesDir:%{public}s", dir.c_str()); + return dir; +} + +std::string ContextImpl::GetDistributedFilesDir() +{ + HILOG_DEBUG("ContextImpl::GetDistributedFilesDir"); + std::string dir; + if (IsCreateBySystemApp()) { + dir = CONTEXT_DISTRIBUTEDFILES_BASE_BEFORE + GetCurrentAccount() + + CONTEXT_DISTRIBUTEDFILES_BASE_MIDDLE + GetBundleName(); + } else { + dir = CONTEXT_BASE + CONTEXT_DISTRIBUTEDFILES; + } + HILOG_DEBUG("ContextImpl::GetDistributedFilesDir:%{public}s", dir.c_str()); + return dir; +} + +std::string ContextImpl::GetBaseDir() const +{ + std::string baseDir; + if (IsCreateBySystemApp()) { + baseDir = CONTEXT_DATA + currArea_ + CONTEXT_FILE_SEPARATOR + GetCurrentAccount() + + CONTEXT_BUNDLE + GetBundleName(); + } else { + baseDir = CONTEXT_BASE + currArea_; + } + if (parentContext_ != nullptr) { + baseDir = baseDir + CONTEXT_FILE_SEPARATOR + GetHapModuleInfo()->moduleName; + } + + HILOG_DEBUG("ContextImpl::GetBaseDir:%{public}s", baseDir.c_str()); + return baseDir; +} + +std::string ContextImpl::GetCurrentAccount() const +{ + return "0"; +} + +std::shared_ptr ContextImpl::CreateBundleContext(const std::string &bundleName) +{ + if (parentContext_ != nullptr) { + return parentContext_->CreateBundleContext(bundleName); + } + + if (bundleName.empty()) { + HILOG_ERROR("ContextImpl::CreateBundleContext bundleName is empty"); + return nullptr; + } + + sptr bundleMgr = GetBundleManager(); + if (bundleMgr == nullptr) { + HILOG_ERROR("ContextImpl::CreateBundleContext GetBundleManager is nullptr"); + return nullptr; + } + + AppExecFwk::BundleInfo bundleInfo; + HILOG_DEBUG("ContextImpl::CreateBundleContext length: %{public}zu, bundleName: %{public}s", + (size_t)bundleName.length(), + bundleName.c_str()); + bundleMgr->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); + + if (bundleInfo.name.empty() || bundleInfo.applicationInfo.name.empty()) { + HILOG_ERROR("ContextImpl::CreateBundleContext GetBundleInfo is error"); + return nullptr; + } + + std::shared_ptr appContext = std::make_shared(); + appContext->SetFlags(CONTEXT_CREATE_BY_SYSTEM_APP); + + // init resourceManager. + InitResourceManager(bundleInfo, appContext); + + appContext->SetApplicationInfo(std::make_shared(bundleInfo.applicationInfo)); + return appContext; +} + +void ContextImpl::InitResourceManager( + const AppExecFwk::BundleInfo &bundleInfo, const std::shared_ptr &appContext) const +{ + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); + if (appContext == nullptr || resourceManager == nullptr) { + HILOG_ERROR("ContextImpl::InitResourceManager create resourceManager failed"); + return; + } + + HILOG_DEBUG( + "ContextImpl::InitResourceManager moduleResPaths count: %{public}zu", bundleInfo.moduleResPaths.size()); + for (auto moduleResPath : bundleInfo.moduleResPaths) { + if (!moduleResPath.empty()) { + HILOG_ERROR("ContextImpl::InitResourceManager length: %{public}zu, moduleResPath: %{public}s", + moduleResPath.length(), + moduleResPath.c_str()); + if (!resourceManager->AddResource(moduleResPath.c_str())) { + HILOG_ERROR("ContextImpl::InitResourceManager AddResource failed"); + } + } + } + + std::unique_ptr resConfig(Global::Resource::CreateResConfig()); + UErrorCode status = U_ZERO_ERROR; + icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLanguage(), status); + resConfig->SetLocaleInfo(locale); + if (resConfig->GetLocaleInfo() != nullptr) { + HILOG_DEBUG("ContextImpl::InitResourceManager language: %{public}s, script: %{public}s, region: %{public}s,", + resConfig->GetLocaleInfo()->getLanguage(), + resConfig->GetLocaleInfo()->getScript(), + resConfig->GetLocaleInfo()->getCountry()); + } else { + HILOG_ERROR("ContextImpl::InitResourceManager language: GetLocaleInfo is null."); + } + resourceManager->UpdateResConfig(*resConfig); + appContext->SetResourceManager(resourceManager); +} + +sptr ContextImpl::GetBundleManager() const +{ + HILOG_DEBUG("ContextImpl::GetBundleManager begin"); + auto bundleObj = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility( + BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (bundleObj == nullptr) { + HILOG_ERROR("failed to get bundle manager service"); + return nullptr; + } + HILOG_DEBUG("ContextImpl::GetBundleManager before iface_cast"); + sptr bms = iface_cast(bundleObj); + HILOG_DEBUG("ContextImpl::GetBundleManager after iface_cast"); + HILOG_DEBUG("ContextImpl::GetBundleManager end"); + return bms; +} + +void ContextImpl::SetApplicationInfo(const std::shared_ptr &info) +{ + if (info == nullptr) { + HILOG_ERROR("ContextImpl::SetApplicationInfo failed, info is empty"); + return; + } + applicationInfo_ = info; +} + +void ContextImpl::SetResourceManager(const std::shared_ptr &resourceManager) +{ + HILOG_DEBUG("ContextImpl::initResourceManager. Start."); + resourceManager_ = resourceManager; + HILOG_DEBUG("ContextImpl::initResourceManager. End."); +} + +std::shared_ptr ContextImpl::GetResourceManager() const +{ + if (parentContext_ != nullptr) { + return parentContext_->GetResourceManager(); + } + + return resourceManager_; +} + +std::shared_ptr ContextImpl::GetApplicationInfo() const +{ + if (parentContext_ != nullptr) { + return parentContext_->GetApplicationInfo(); + } + + return applicationInfo_; +} + +void ContextImpl::SetParentContext(const std::shared_ptr &context) +{ + parentContext_ = context; +} + +std::string ContextImpl::GetBundleCodePath() const +{ + if (parentContext_ != nullptr) { + return parentContext_->GetBundleCodePath(); + } + return (applicationInfo_ != nullptr) ? applicationInfo_->codePath : ""; +} + +void ContextImpl::InitHapModuleInfo(const std::shared_ptr &abilityInfo) +{ + if (hapModuleInfo_ != nullptr || abilityInfo == nullptr) { + return; + } + sptr ptr = GetBundleManager(); + if (ptr == nullptr) { + HILOG_ERROR("InitHapModuleInfo: failed to get bundle manager service"); + return; + } + + hapModuleInfo_ = std::make_shared(); + if (!ptr->GetHapModuleInfo(*abilityInfo.get(), *hapModuleInfo_)) { + HILOG_ERROR("InitHapModuleInfo: GetHapModuleInfo failed, will retval false value"); + } +} + +std::shared_ptr ContextImpl::GetHapModuleInfo() const +{ + return hapModuleInfo_; +} + +void ContextImpl::SetFlags(int64_t flags) +{ + flags_ = static_cast(flags_) | CONTEXT_CREATE_BY_SYSTEM_APP; +} + +bool ContextImpl::IsCreateBySystemApp() const +{ + return (static_cast(flags_) & CONTEXT_CREATE_BY_SYSTEM_APP) == 1; +} + +std::shared_ptr Context::appContext_ = nullptr; +std::mutex Context::contextMutex_; + +std::shared_ptr Context::GetApplicationContext() +{ + std::lock_guard lock(contextMutex_); + return appContext_; +} + +void ContextImpl::InitAppContext() +{ + std::lock_guard lock(Context::contextMutex_); + Context::appContext_ = shared_from_this(); +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/kits/appkit/native/ability_runtime/context/context_impl.h b/kits/appkit/native/ability_runtime/context/context_impl.h new file mode 100644 index 0000000000..088fea1297 --- /dev/null +++ b/kits/appkit/native/ability_runtime/context/context_impl.h @@ -0,0 +1,205 @@ +/* + * 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 ABILITY_RUNTIME_CONTEXT_IMPL_H +#define ABILITY_RUNTIME_CONTEXT_IMPL_H + +#include "context.h" + +#include "bundle_mgr_interface.h" + +namespace OHOS { +namespace AbilityRuntime { +class ContextImpl : public Context, public std::enable_shared_from_this { +public: + ContextImpl() = default; + virtual ~ContextImpl() = default; + + /** + * @brief Obtains the bundle name of the current ability. + * + * @return Returns the bundle name of the current ability. + */ + std::string GetBundleName() const override; + + /** + * @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 GetBundleCodeDir() override; + + /** + * @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 GetCacheDir() override; + + /** + * @brief Obtains the temporary directory. + * + * @return Returns the application temporary directory. + */ + std::string GetTempDir() override; + + /** + * @brief Obtains the directory for storing files for the application on the device's internal storage. + * + * @return Returns the application file directory. + */ + std::string GetFilesDir() override; + + /** + * @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 GetDatabaseDir() override; + + /** + * @brief Obtains the path storing the storage file of the application. + * + * @return Returns the local storage file. + */ + std::string GetStorageDir() override; + + /** + * @brief Obtains the path distributed file of the application + * + * @return Returns the distributed file. + */ + std::string GetDistributedFilesDir() override; + + /** + * @brief set the ResourceManager. + * + * @param the ResourceManager has been inited. + * + */ + void SetResourceManager(const std::shared_ptr &resourceManager); + + /** + * @brief Obtains a resource manager. + * + * @return Returns a ResourceManager object. + */ + std::shared_ptr GetResourceManager() const override; + + /** + * @brief Creates a Context object for an application with the given bundle name. + * + * @param bundleName Indicates the bundle name of the application. + * + * @return Returns a Context object created for the specified application. + */ + std::shared_ptr CreateBundleContext(const std::string &bundleName) override; + + /** + * @brief Obtains an IBundleMgr instance. + * You can use this instance to obtain information about the application bundle. + * + * @return Returns an IBundleMgr instance. + */ + sptr GetBundleManager() const; + + /** + * @brief Set ApplicationInfo + * + * @param info ApplicationInfo instance. + */ + void SetApplicationInfo(const std::shared_ptr &info); + + /** + * @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 GetApplicationInfo() const override; + + /** + * @brief Set ApplicationInfo + * + * @param info ApplicationInfo instance. + */ + void SetParentContext(const std::shared_ptr &context); + + /** + * @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 GetBundleCodePath() const override; + + /** + * @brief Obtains the HapModuleInfo object of the application. + * + * @return Returns the HapModuleInfo object of the application. + */ + std::shared_ptr GetHapModuleInfo() const override; + + /** + * @brief Set HapModuleInfo + * + * @param hapModuleInfo HapModuleInfo instance. + */ + void InitHapModuleInfo(const std::shared_ptr &abilityInfo); + + /** + * @brief Set application context + */ + void InitAppContext(); +private: + static const std::string CONTEXT_BUNDLECODE_BASE; + static const std::string CONTEXT_BUNDLECODE; + static const std::string CONTEXT_BUNDLE; + static const std::string CONTEXT_DISTRIBUTEDFILES_BASE_BEFORE; + static const std::string CONTEXT_DISTRIBUTEDFILES_BASE_MIDDLE; + static const std::string CONTEXT_DISTRIBUTEDFILES; + static const std::string CONTEXT_FILE_SEPARATOR; + static const std::string CONTEXT_DATA; + static const std::string CONTEXT_BASE; + static const std::string CONTEXT_PRIVATE; + static const std::string CONTEXT_CACHES; + static const std::string CONTEXT_STORAGE; + static const std::string CONTEXT_DATABASE; + static const std::string CONTEXT_TEMP; + static const std::string CONTEXT_FILES; + static const std::string CONTEXT_CE; + static const int64_t CONTEXT_CREATE_BY_SYSTEM_APP; + int flags_ = 0x00000000; + + void InitResourceManager( + const AppExecFwk::BundleInfo &bundleInfo, const std::shared_ptr &appContext) const; + bool IsCreateBySystemApp() const; + std::string GetBaseDir() const; + std::string GetCurrentAccount() const; + void SetFlags(int64_t flags); + + std::shared_ptr applicationInfo_ = nullptr; + std::shared_ptr parentContext_ = nullptr; + std::shared_ptr resourceManager_ = nullptr; + std::shared_ptr hapModuleInfo_ = nullptr; + std::string currArea_ = CONTEXT_CE; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_CONTEXT_IMPL_H diff --git a/kits/appkit/native/ability_runtime/context/js_context_utils.cpp b/kits/appkit/native/ability_runtime/context/js_context_utils.cpp new file mode 100644 index 0000000000..0a9f36d0a5 --- /dev/null +++ b/kits/appkit/native/ability_runtime/context/js_context_utils.cpp @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "js_context_utils.h" + +#include "hilog_wrapper.h" +#include "js_data_struct_converter.h" +#include "js_hap_module_info_utils.h" +#include "js_resource_manager_utils.h" +#include "js_runtime_utils.h" + +namespace OHOS { +namespace AbilityRuntime { +namespace { +constexpr char BASE_CONTEXT_NAME[] = "__base_context_ptr__"; + +class JsBaseContext { +public: + explicit JsBaseContext(std::weak_ptr&& context) : context_(std::move(context)) {} + virtual ~JsBaseContext() = default; + + static void Finalizer(NativeEngine* engine, void* data, void* hint); + static NativeValue* CreateBundleContext(NativeEngine* engine, NativeCallbackInfo* info); + static NativeValue* GetApplicationContext(NativeEngine* engine, NativeCallbackInfo* info); + + void KeepContext(std::shared_ptr context) + { + keepContext_ = context; + } + +private: + NativeValue* OnCreateBundleContext(NativeEngine& engine, NativeCallbackInfo& info); + NativeValue* OnGetApplicationContext(NativeEngine& engine, NativeCallbackInfo& info); + + std::shared_ptr keepContext_; + +protected: + std::weak_ptr context_; +}; + +void JsBaseContext::Finalizer(NativeEngine* engine, void* data, void* hint) +{ + HILOG_INFO("JsBaseContext::Finalizer is called"); + std::unique_ptr(static_cast(data)); +} + +NativeValue* JsBaseContext::CreateBundleContext(NativeEngine* engine, NativeCallbackInfo* info) +{ + JsBaseContext* me = CheckParamsAndGetThis(engine, info, BASE_CONTEXT_NAME); + return me != nullptr ? me->OnCreateBundleContext(*engine, *info) : nullptr; +} + +NativeValue* JsBaseContext::GetApplicationContext(NativeEngine* engine, NativeCallbackInfo* info) +{ + JsBaseContext* me = CheckParamsAndGetThis(engine, info, BASE_CONTEXT_NAME); + return me != nullptr ? me->OnGetApplicationContext(*engine, *info) : nullptr; +} + +NativeValue* JsBaseContext::OnCreateBundleContext(NativeEngine& engine, NativeCallbackInfo& info) +{ + if (info.argc == 0) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + + auto context = context_.lock(); + if (!context) { + HILOG_WARN("context is already released"); + return engine.CreateUndefined(); + } + + std::string bundleName; + if (!ConvertFormJsValue(engine, info.argv[0], bundleName)) { + HILOG_ERROR("Parse bundleName failed"); + return engine.CreateUndefined(); + } + + auto bundleContext = context->CreateBundleContext(bundleName); + if (!bundleContext) { + HILOG_ERROR("bundleContext is nullptr"); + return engine.CreateUndefined(); + } + + JsRuntime& jsRuntime = *static_cast(engine.GetJsEngine()); + NativeValue* value = CreateJsBaseContext(engine, bundleContext, true); + return jsRuntime.LoadSystemModule("application.AbilityStageContext", &value, 1)->Get(); +} + +NativeValue* JsBaseContext::OnGetApplicationContext(NativeEngine& engine, NativeCallbackInfo& info) +{ + auto context = context_.lock(); + if (!context) { + HILOG_WARN("context is already released"); + return engine.CreateUndefined(); + } + + auto appContext = context->GetApplicationContext(); + if (!appContext) { + HILOG_ERROR("appContext is nullptr"); + return engine.CreateUndefined(); + } + + JsRuntime& jsRuntime = *static_cast(engine.GetJsEngine()); + NativeValue* value = CreateJsBaseContext(engine, appContext, true); + return jsRuntime.LoadSystemModule("application.Context", &value, 1)->Get(); +} +} // namespace + +NativeValue* CreateJsBaseContext(NativeEngine& engine, std::shared_ptr context, bool keepContext) +{ + NativeValue* objValue = engine.CreateObject(); + NativeObject* object = ConvertNativeValueTo(objValue); + + auto jsContext = std::make_unique(context); + if (keepContext) { + jsContext->KeepContext(context); + } + SetNamedNativePointer(engine, *object, BASE_CONTEXT_NAME, jsContext.release(), JsBaseContext::Finalizer); + + auto appInfo = context->GetApplicationInfo(); + if (appInfo != nullptr) { + object->SetProperty("applicationInfo", CreateJsApplicationInfo(engine, *appInfo)); + } + auto hapModuleInfo = context->GetHapModuleInfo(); + if (hapModuleInfo != nullptr) { + object->SetProperty("currentHapModuleInfo", CreateJsHapModuleInfo(engine, *hapModuleInfo)); + } + auto resourceManager = context->GetResourceManager(); + if (resourceManager != nullptr) { + object->SetProperty("resourceManager", CreateJsResourceManager(engine, resourceManager)); + } + object->SetProperty("cacheDir", CreateJsValue(engine, context->GetCacheDir())); + object->SetProperty("tempDir", CreateJsValue(engine, context->GetTempDir())); + object->SetProperty("filesDir", CreateJsValue(engine, context->GetFilesDir())); + object->SetProperty("distributedFilesDir", CreateJsValue(engine, context->GetDistributedFilesDir())); + object->SetProperty("databaseDir", CreateJsValue(engine, context->GetDatabaseDir())); + object->SetProperty("storageDir", CreateJsValue(engine, context->GetStorageDir())); + object->SetProperty("bundleCodeDir", CreateJsValue(engine, context->GetBundleCodeDir())); + + BindNativeFunction(engine, *object, "createBundleContext", JsBaseContext::CreateBundleContext); + BindNativeFunction(engine, *object, "getApplicationContext", JsBaseContext::GetApplicationContext); + + return objValue; +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/kits/appkit/native/ability_runtime/context/js_context_utils.h b/kits/appkit/native/ability_runtime/context/js_context_utils.h new file mode 100644 index 0000000000..a6595e2ea7 --- /dev/null +++ b/kits/appkit/native/ability_runtime/context/js_context_utils.h @@ -0,0 +1,32 @@ +/* + * 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 ABILITY_RUNTIME_JS_CONTEXT_UTILS_H +#define ABILITY_RUNTIME_JS_CONTEXT_UTILS_H + +#include + +#include "context.h" + +class NativeEngine; +class NativeValue; +struct NativeCallbackInfo; + +namespace OHOS { +namespace AbilityRuntime { +NativeValue* CreateJsBaseContext(NativeEngine& engine, std::shared_ptr context, bool keepContext = false); +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_JS_CONTEXT_UTILS_H diff --git a/kits/appkit/native/ability_runtime/context/js_hap_module_info_utils.cpp b/kits/appkit/native/ability_runtime/context/js_hap_module_info_utils.cpp new file mode 100644 index 0000000000..24c006562a --- /dev/null +++ b/kits/appkit/native/ability_runtime/context/js_hap_module_info_utils.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "js_hap_module_info_utils.h" + +#include "js_data_struct_converter.h" +#include "js_runtime_utils.h" + +namespace OHOS { +namespace AbilityRuntime { +NativeValue* CreateJsHapModuleInfo(NativeEngine& engine, AppExecFwk::HapModuleInfo& hapModuleInfo) +{ + NativeValue* objValue = engine.CreateObject(); + NativeObject* object = ConvertNativeValueTo(objValue); + + object->SetProperty("name", CreateJsValue(engine, hapModuleInfo.name)); + object->SetProperty("moduleName", CreateJsValue(engine, hapModuleInfo.moduleName)); + object->SetProperty("description", CreateJsValue(engine, hapModuleInfo.description)); + object->SetProperty("iconPath", CreateJsValue(engine, hapModuleInfo.iconPath)); + object->SetProperty("label", CreateJsValue(engine, hapModuleInfo.label)); + object->SetProperty("backgroundImg", CreateJsValue(engine, hapModuleInfo.backgroundImg)); + object->SetProperty("mainAbility", CreateJsValue(engine, hapModuleInfo.mainAbility)); + object->SetProperty("srcPath", CreateJsValue(engine, hapModuleInfo.srcPath)); + object->SetProperty("supportedModes", CreateJsValue(engine, hapModuleInfo.supportedModes)); + + NativeValue *capArrayValue = engine.CreateArray(hapModuleInfo.reqCapabilities.size()); + NativeArray *capArray = ConvertNativeValueTo(capArrayValue); + if (capArray != nullptr) { + int index = 0; + for (auto cap : hapModuleInfo.reqCapabilities) { + capArray->SetElement(index++, CreateJsValue(engine, cap)); + } + } + object->SetProperty("reqCapabilities", capArrayValue); + + NativeValue *deviceArrayValue = engine.CreateArray(hapModuleInfo.deviceTypes.size()); + NativeArray *deviceArray = ConvertNativeValueTo(deviceArrayValue); + if (deviceArray != nullptr) { + int index = 0; + for (auto device : hapModuleInfo.deviceTypes) { + deviceArray->SetElement(index++, CreateJsValue(engine, device)); + } + } + object->SetProperty("deviceTypes", deviceArrayValue); + + NativeValue *abilityArrayValue = engine.CreateArray(hapModuleInfo.abilityInfos.size()); + NativeArray *abilityArray = ConvertNativeValueTo(abilityArrayValue); + if (abilityArray != nullptr) { + int index = 0; + for (auto abilityInfo : hapModuleInfo.abilityInfos) { + abilityArray->SetElement(index++, CreateJsAbilityInfo(engine, abilityInfo)); + } + } + object->SetProperty("abilityInfos", abilityArrayValue); + + return objValue; +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/kits/appkit/native/ability_runtime/context/js_hap_module_info_utils.h b/kits/appkit/native/ability_runtime/context/js_hap_module_info_utils.h new file mode 100644 index 0000000000..c7dfd66671 --- /dev/null +++ b/kits/appkit/native/ability_runtime/context/js_hap_module_info_utils.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ABILITY_RUNTIME_JS_HAP_MODULE_INFO_UTILS_H +#define ABILITY_RUNTIME_JS_HAP_MODULE_INFO_UTILS_H + +#include "hap_module_info.h" + +class NativeEngine; +class NativeValue; + +namespace OHOS { +namespace AbilityRuntime { +class JsRuntime; + +NativeValue* CreateJsHapModuleInfo(NativeEngine& engine, AppExecFwk::HapModuleInfo& hapModuleInfo); +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_JS_HAP_MODULE_INFO_UTILS_H diff --git a/kits/appkit/native/ability_runtime/context/js_resource_manager_utils.cpp b/kits/appkit/native/ability_runtime/context/js_resource_manager_utils.cpp new file mode 100644 index 0000000000..b75cad0dfb --- /dev/null +++ b/kits/appkit/native/ability_runtime/context/js_resource_manager_utils.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "js_resource_manager_utils.h" + +#include "hilog_wrapper.h" +#include "js_runtime_utils.h" +#include "rstate.h" + +namespace OHOS { +namespace AbilityRuntime { +namespace { +const int32_t GETSTRING_PARAM_SIZE = 1; +class JsResourceManager final { +public: + JsResourceManager(const std::shared_ptr& resourceManager) + : resourceManager_(resourceManager) {} + ~JsResourceManager() = default; + + static void Finalizer(NativeEngine* engine, void* data, void* hint) + { + HILOG_INFO("JsResourceManager::Finalizer is called"); + std::unique_ptr(static_cast(data)); + } + + static NativeValue* GetString(NativeEngine* engine, NativeCallbackInfo* info) + { + JsResourceManager* me = CheckParamsAndGetThis(engine, info); + return me != nullptr ? me->GetString(*engine, *info) : nullptr; + } + +private: + NativeValue* GetString(NativeEngine& engine, NativeCallbackInfo& info) + { + HILOG_INFO("JsResourceManager GetString is called"); + + if (info.argc == 0) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + + NativeNumber* number = ConvertNativeValueTo(info.argv[0]); + uint32_t param = number ? *(number) : 0; + + AsyncTask::CompleteCallback complete = + [weak = resourceManager_, resId = param](NativeEngine& engine, AsyncTask& task, int32_t status) { + auto resourceManager = weak.lock(); + if (!resourceManager) { + HILOG_INFO("JsResourceManager is released"); + task.Reject(engine, CreateJsError(engine, 1, "resourceManager is released")); + return; + } + std::string retValue; + OHOS::Global::Resource::RState errval = resourceManager->GetStringById(resId, retValue); + if (errval == OHOS::Global::Resource::RState::SUCCESS) { + HILOG_DEBUG("resourceManager GetStringById:%{public}s", retValue.c_str()); + task.Resolve(engine, engine.CreateString(retValue.c_str(), retValue.length())); + } else { + HILOG_DEBUG("resourceManager GetStringById failed"); + task.Reject(engine, CreateJsError(engine, errval, "getString failed")); + } + }; + + NativeValue* lastParam = info.argc > GETSTRING_PARAM_SIZE ? info.argv[GETSTRING_PARAM_SIZE] : nullptr; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; + } + + std::weak_ptr resourceManager_; +}; +} // namespace + +NativeValue* CreateJsResourceManager( + NativeEngine& engine, std::shared_ptr resourceManager) +{ + NativeValue* objValue = engine.CreateObject(); + NativeObject* object = ConvertNativeValueTo(objValue); + + std::unique_ptr jsResourceManager = std::make_unique(resourceManager); + object->SetNativePointer(jsResourceManager.release(), JsResourceManager::Finalizer, nullptr); + + BindNativeFunction(engine, *object, "getString", JsResourceManager::GetString); + return objValue; +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/kits/appkit/native/ability_runtime/context/js_resource_manager_utils.h b/kits/appkit/native/ability_runtime/context/js_resource_manager_utils.h new file mode 100644 index 0000000000..973231b754 --- /dev/null +++ b/kits/appkit/native/ability_runtime/context/js_resource_manager_utils.h @@ -0,0 +1,32 @@ +/* + * 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 ABILITY_RUNTIME_JS_RESOURCE_MANAGER_UTILS_H +#define ABILITY_RUNTIME_JS_RESOURCE_MANAGER_UTILS_H + +#include "resource_manager.h" + +class NativeEngine; +class NativeValue; + +namespace OHOS { +namespace AbilityRuntime { +class JsRuntime; + +NativeValue* CreateJsResourceManager(NativeEngine& engine, + std::shared_ptr resourceManager); +} // namespace AbilityRuntime +} // namespace OHOS +#endif // ABILITY_RUNTIME_JS_RESOURCE_MANAGER_UTILS_H diff --git a/kits/appkit/native/ability_runtime/extension_context.cpp b/kits/appkit/native/ability_runtime/extension_context.cpp new file mode 100644 index 0000000000..cd327d92b5 --- /dev/null +++ b/kits/appkit/native/ability_runtime/extension_context.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "extension_context.h" + +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AbilityRuntime { +void ExtensionContext::SetToken(const sptr &token) +{ + if (token == nullptr) { + HILOG_DEBUG("ExtensionContext::SetToken failed, application is nullptr"); + return; + } + token_ = token; +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/kits/appkit/native/ability_runtime/extension_context.h b/kits/appkit/native/ability_runtime/extension_context.h new file mode 100644 index 0000000000..efcffeb486 --- /dev/null +++ b/kits/appkit/native/ability_runtime/extension_context.h @@ -0,0 +1,46 @@ +/* + * 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 EXTENSION_CONTEXT_H +#define EXTENSION_CONTEXT_H + +#include "context_impl.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AbilityRuntime { +/** + * @brief context supply for extension + * + */ +class ExtensionContext : public ContextImpl { +public: + ExtensionContext() = default; + virtual ~ExtensionContext() = default; + + /** + * @brief Set the token witch the app launched. + * + * @param token The token which the is launched by app. + */ + void SetToken(const sptr &token); + +protected: + sptr token_; +private: +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // EXTENSION_CONTEXT_H \ No newline at end of file diff --git a/kits/appkit/native/ability_runtime/service_extension_context.cpp b/kits/appkit/native/ability_runtime/service_extension_context.cpp new file mode 100644 index 0000000000..9c69eba185 --- /dev/null +++ b/kits/appkit/native/ability_runtime/service_extension_context.cpp @@ -0,0 +1,95 @@ +/* + * 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 "service_extension_context.h" + +#include "ability_manager_client.h" +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AbilityRuntime { +int ServiceExtensionContext::ILLEGAL_REQUEST_CODE(-1); + +void ServiceExtensionContext::StartAbility(const AAFwk::Want &want) const +{ + HILOG_DEBUG("%{public}s begin.", __func__); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, token_, ILLEGAL_REQUEST_CODE); + HILOG_DEBUG("%{public}s. End calling ams->StartAbility. ret=%{public}d", __func__, err); + if (err != ERR_OK) { + HILOG_ERROR("ServiceContext::StartAbility is failed %{public}d", err); + } +} + +bool ServiceExtensionContext::ConnectAbility(const AAFwk::Want &want, const sptr &conn) +{ + HILOG_INFO("%{public}s begin.", __func__); + + ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(want, conn, token_); + HILOG_INFO("%{public}s end ConnectAbility, ret=%{public}d", __func__, ret); + bool value = ((ret == ERR_OK) ? true : false); + if (!value) { + HILOG_ERROR("ServiceContext::ConnectAbility ErrorCode = %{public}d", ret); + } + HILOG_INFO("%{public}s end.", __func__); + return value; +} + +void ServiceExtensionContext::DisconnectAbility(const sptr &conn) +{ + HILOG_INFO("%{public}s begin.", __func__); + ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(conn); + HILOG_INFO("%{public}s end ams->DisconnectAbility, ret=%{public}d", __func__, ret); + if (ret != ERR_OK) { + HILOG_ERROR("ServiceContext::DisconnectAbility error"); + } + HILOG_INFO("ServiceContext::DisconnectAbility end"); +} + +void ServiceExtensionContext::TerminateAbility() +{ + HILOG_INFO("%{public}s begin.", __func__); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->TerminateAbility(token_, -1, nullptr); + if (err != ERR_OK) { + HILOG_ERROR("ServiceExtensionContext::TerminateAbility is failed %{public}d", err); + } + HILOG_INFO("%{public}s end.", __func__); +} + +AppExecFwk::AbilityType ServiceExtensionContext::GetAbilityInfoType() const +{ + std::shared_ptr info = GetAbilityInfo(); + if (info == nullptr) { + HILOG_ERROR("ServiceContext::GetAbilityInfoType info == nullptr"); + return AppExecFwk::AbilityType::UNKNOWN; + } + + return info->type; +} + +std::shared_ptr ServiceExtensionContext::GetAbilityInfo() const +{ + return abilityInfo_; +} + +void ServiceExtensionContext::SetAbilityInfo(const std::shared_ptr &abilityInfo) +{ + if (abilityInfo == nullptr) { + HILOG_ERROR("ServiceExtensionContext::SetAbilityInfo Info == nullptr"); + return; + } + abilityInfo_ = abilityInfo; +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/kits/appkit/native/ability_runtime/service_extension_context.h b/kits/appkit/native/ability_runtime/service_extension_context.h new file mode 100644 index 0000000000..85bb96518e --- /dev/null +++ b/kits/appkit/native/ability_runtime/service_extension_context.h @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SERVICE_EXTENSION_CONTEXT_H +#define SERVICE_EXTENSION_CONTEXT_H + +#include "extension_context.h" + +#include "ability_connect_callback_interface.h" +#include "ability_info.h" +#include "want.h" + +namespace OHOS { +namespace AbilityRuntime { +/** + * @brief context supply for service + * + */ +class ServiceExtensionContext : public ExtensionContext { +public: + ServiceExtensionContext() = default; + virtual ~ServiceExtensionContext() = default; + + /** + * @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. + * + */ + void StartAbility(const AAFwk::Want &want) const; + + /** + * @brief Connects the current ability to an ability using the AbilityInfo.AbilityType.SERVICE template. + * + * @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 ConnectAbility(const AAFwk::Want &want, const sptr &conn); + + /** + * @brief Disconnects the current ability from an ability + * + * @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 DisconnectAbility(const sptr &conn); + + /** + * @brief Destroys the current ability. + * + */ + void TerminateAbility(); + + /** + * @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. + */ + std::shared_ptr GetAbilityInfo() const; + + /** + * @brief Set AbilityInfo when init. + * + */ + void SetAbilityInfo(const std::shared_ptr &abilityInfo); + +private: + static int ILLEGAL_REQUEST_CODE; + + /** + * @brief Get Current Ability Type + * + * @return Current Ability Type + */ + OHOS::AppExecFwk::AbilityType GetAbilityInfoType() const; + + std::shared_ptr abilityInfo_; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // SERVICE_EXTENSION_CONTEXT_H \ No newline at end of file diff --git a/kits/appkit/native/app/include/context.h b/kits/appkit/native/app/include/context.h index e6a4df1407..4fc00e4b37 100755 --- a/kits/appkit/native/app/include/context.h +++ b/kits/appkit/native/app/include/context.h @@ -705,7 +705,7 @@ public: /** * set lock screen white list * - * @param isAllow Whether to allow lock screen. + * @param isAllow Whether to allow lock screen. * */ virtual void SetShowOnLockScreen(bool isAllow) = 0; diff --git a/kits/appkit/native/app/include/main_thread.h b/kits/appkit/native/app/include/main_thread.h index 57fef92f47..2b2bbda768 100644 --- a/kits/appkit/native/app/include/main_thread.h +++ b/kits/appkit/native/app/include/main_thread.h @@ -32,6 +32,7 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::Global; enum class MainThreadState { INIT, ATTACH, READY, RUNNING }; +struct BundleInfo; class ContextDeal; // class Global::Resource::ResourceManager; class AppMgrDeathRecipient : public IRemoteObject::DeathRecipient { @@ -453,7 +454,7 @@ private: Profile &appProfile); bool CheckForHandleLaunchApplication(const AppLaunchData &appLaunchData); bool InitResourceManager(std::shared_ptr &resourceManager, - std::shared_ptr &contextDeal, ApplicationInfo &appInfo); + std::shared_ptr &contextDeal, ApplicationInfo &appInfo, BundleInfo& bundleInfo); std::vector fileEntries_; std::vector handleAbilityLib_; // the handler of ACE Library. #endif // ABILITY_LIBRARY_LOADER diff --git a/kits/appkit/native/app/include/ohos_application.h b/kits/appkit/native/app/include/ohos_application.h index 6c05ec2757..1e9ded168c 100644 --- a/kits/appkit/native/app/include/ohos_application.h +++ b/kits/appkit/native/app/include/ohos_application.h @@ -18,11 +18,18 @@ #include #include +#include + #include "application_context.h" #include "ability_lifecycle_callbacks.h" +#include "ability_runtime/context/context.h" +#include "ability_stage.h" #include "element_callback.h" namespace OHOS { +namespace AbilityRuntime { +class Runtime; +} // namespace AbilityRuntime namespace AppExecFwk { class ElementsCallback; class ApplicationImpl; @@ -33,7 +40,7 @@ class OHOSApplication : public ApplicationContext, public std::enable_shared_from_this { public: OHOSApplication(); - virtual ~OHOSApplication() = default; + virtual ~OHOSApplication(); /** * @brief dump OHOSApplication info @@ -42,6 +49,20 @@ public: */ void DumpApplication(); + /** + * @brief Set Runtime + * + * @param runtime Runtime instance. + */ + void SetRuntime(std::unique_ptr&& runtime); + + /** + * @brief Set ApplicationContext + * + * @param context ApplicationContext instance. + */ + void SetApplicationContext(const std::shared_ptr &abilityRuntimeContext); + /** * * @brief Set the abilityRecordMgr to the OHOSApplication. @@ -194,10 +215,43 @@ public: */ virtual void OnTerminate(); + /** + * @brief add the ability stage when a hap first load + * + * @param abilityRecord + * @return abilityStage context + */ + std::shared_ptr AddAbilityStage( + const std::shared_ptr &abilityRecord); + + /** + * @brief remove the ability stage when all of the abilities in the hap have been removed + * + * @param abilityInfo + */ + void CleanAbilityStage(const sptr &token, const std::shared_ptr &abilityInfo); + + /** + * @brief return the application context + * + * @param context + */ + std::shared_ptr GetAppContext() const; + + /** + * @brief return the application runtime + * + * @param runtime + */ + const std::unique_ptr& GetRuntime(); + private: std::list> abilityLifecycleCallbacks_; std::list> elementsCallbacks_; std::shared_ptr abilityRecordMgr_ = nullptr; + std::shared_ptr abilityRuntimeContext_ = nullptr; + std::unordered_map> abilityStages_; + std::unique_ptr runtime_; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/kits/appkit/native/app/src/ability_manager.cpp b/kits/appkit/native/app/src/ability_manager.cpp index 7711bc26bb..ced6666e18 100644 --- a/kits/appkit/native/app/src/ability_manager.cpp +++ b/kits/appkit/native/app/src/ability_manager.cpp @@ -16,8 +16,8 @@ #include "ability_manager.h" #include "app_log_wrapper.h" #include "singleton.h" -#include "system_ability_definition.h" #include "sys_mgr_client.h" +#include "system_ability_definition.h" namespace OHOS { namespace AppExecFwk { diff --git a/kits/appkit/native/app/src/application_impl.cpp b/kits/appkit/native/app/src/application_impl.cpp index 3d79a1abc4..639425164f 100644 --- a/kits/appkit/native/app/src/application_impl.cpp +++ b/kits/appkit/native/app/src/application_impl.cpp @@ -14,8 +14,9 @@ */ #include "application_impl.h" -#include "ohos_application.h" + #include "app_log_wrapper.h" +#include "ohos_application.h" namespace OHOS { namespace AppExecFwk { diff --git a/kits/appkit/native/app/src/context_container.cpp b/kits/appkit/native/app/src/context_container.cpp index b4e53b9b85..24b4c13741 100755 --- a/kits/appkit/native/app/src/context_container.cpp +++ b/kits/appkit/native/app/src/context_container.cpp @@ -13,11 +13,12 @@ * limitations under the License. */ #include "context_container.h" -#include "app_log_wrapper.h" + +#include "ability_manager_client.h" #include "ability_manager_errors.h" +#include "app_log_wrapper.h" #include "application_context.h" #include "bundle_constants.h" -#include "ability_manager_client.h" namespace OHOS { namespace AppExecFwk { diff --git a/kits/appkit/native/app/src/context_deal.cpp b/kits/appkit/native/app/src/context_deal.cpp index e721a8f631..39333ef01c 100755 --- a/kits/appkit/native/app/src/context_deal.cpp +++ b/kits/appkit/native/app/src/context_deal.cpp @@ -14,16 +14,16 @@ */ #include "context_deal.h" -#include "file_ex.h" +#include "ability_manager_client.h" +#include "ability_manager_interface.h" +#include "app_log_wrapper.h" +#include "application_context.h" #include "directory_ex.h" +#include "file_ex.h" #include "iservice_registry.h" -#include "app_log_wrapper.h" -#include "ability_manager_interface.h" -#include "ability_manager_client.h" -#include "system_ability_definition.h" -#include "sys_mgr_client.h" #include "spec_task_dispatcher.h" -#include "application_context.h" +#include "sys_mgr_client.h" +#include "system_ability_definition.h" #include "task_dispatcher_context.h" #define MODE 0771 diff --git a/kits/appkit/native/app/src/main_thread.cpp b/kits/appkit/native/app/src/main_thread.cpp index 9d9e0c7613..3c89359276 100644 --- a/kits/appkit/native/app/src/main_thread.cpp +++ b/kits/appkit/native/app/src/main_thread.cpp @@ -14,19 +14,28 @@ */ #include "main_thread.h" + #include -#include "ohos_application.h" + +#include "ability_loader.h" +#include "ability_thread.h" #include "app_loader.h" +#include "app_log_wrapper.h" #include "application_env_impl.h" -#include "ability_thread.h" -#include "task_handler_client.h" +#include "bytrace.h" #include "context_deal.h" +#include "context_impl.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" +#include "js_runtime.h" +#include "locale_config.h" +#include "ohos_application.h" #include "resource_manager.h" +#include "runtime.h" +#include "service_extension.h" #include "sys_mgr_client.h" #include "system_ability_definition.h" -#include "app_log_wrapper.h" +#include "task_handler_client.h" #if defined(ABILITY_LIBRARY_LOADER) || defined(APPLICATION_LIBRARY_LOADER) #include @@ -35,6 +44,10 @@ namespace OHOS { namespace AppExecFwk { +namespace { +constexpr int TARGET_VERSION_THRESHOLDS = 8; +} + #define ACEABILITY_LIBRARY_LOADER #ifdef ABILITY_LIBRARY_LOADER #endif @@ -371,6 +384,17 @@ void MainThread::ScheduleLaunchAbility(const AbilityInfo &info, const sptr abilityToken = token; std::shared_ptr abilityRecord = std::make_shared(abilityInfo, abilityToken); + std::shared_ptr contextDeal = std::make_shared(); + sptr bundleMgr = contextDeal->GetBundleManager(); + if (bundleMgr == nullptr) { + APP_LOGE("MainThread::ScheduleLaunchAbility GetBundleManager is nullptr"); + } else { + BundleInfo bundleInfo; + bundleMgr->GetBundleInfo(abilityInfo->bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); + abilityRecord->SetTargetVersion(bundleInfo.targetVersion); + APP_LOGI("MainThread::ScheduleLaunchAbility targetVersion:%{public}d", bundleInfo.targetVersion); + } + auto task = [appThread = this, abilityRecord]() { appThread->HandleLaunchAbility(abilityRecord); }; if (!mainHandler_->PostTask(task)) { APP_LOGE("MainThread::ScheduleLaunchAbility PostTask task failed"); @@ -536,6 +560,7 @@ void MainThread::HandleTerminateApplicationLocal() */ void MainThread::HandleProcessSecurityExit() { + BYTRACE(BYTRACE_TAG_APP); APP_LOGI("MainThread::HandleProcessSecurityExit called start."); if (abilityRecordMgr_ == nullptr) { APP_LOGE("MainThread::HandleProcessSecurityExit abilityRecordMgr_ is null"); @@ -614,22 +639,8 @@ bool MainThread::CheckForHandleLaunchApplication(const AppLaunchData &appLaunchD } bool MainThread::InitResourceManager(std::shared_ptr &resourceManager, - std::shared_ptr &contextDeal, ApplicationInfo &appInfo) + std::shared_ptr &contextDeal, ApplicationInfo &appInfo, BundleInfo& bundleInfo) { - APP_LOGI("MainThread::InitResourceManager. Start calling GetBundleManager."); - sptr bundleMgr = contextDeal->GetBundleManager(); - if (bundleMgr == nullptr) { - APP_LOGE("MainThread::handleLaunchApplication GetBundleManager is nullptr"); - return false; - } - APP_LOGI("MainThread::handleLaunchApplication. End calling GetBundleManager."); - - BundleInfo bundleInfo; - APP_LOGI("MainThread::handleLaunchApplication length: %{public}zu, bundleName: %{public}s", - appInfo.bundleName.length(), - appInfo.bundleName.c_str()); - bundleMgr->GetBundleInfo(appInfo.bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); - APP_LOGI("MainThread::handleLaunchApplication moduleResPaths count: %{public}zu start", bundleInfo.moduleResPaths.size()); for (auto moduleResPath : bundleInfo.moduleResPaths) { @@ -648,7 +659,9 @@ bool MainThread::InitResourceManager(std::shared_ptr resConfig(Global::Resource::CreateResConfig()); APP_LOGI("MainThread::handleLaunchApplication after Resource::CreateResConfig."); - resConfig->SetLocaleInfo("zh", "Hans", "CN"); + UErrorCode status = U_ZERO_ERROR; + icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLanguage(), status); + resConfig->SetLocaleInfo(locale); const icu::Locale *localeInfo = resConfig->GetLocaleInfo(); if (localeInfo != nullptr) { APP_LOGI("MainThread::handleLaunchApplication language: %{public}s, script: %{public}s, region: %{public}s,", @@ -673,6 +686,7 @@ bool MainThread::InitResourceManager(std::shared_ptr bundleMgr = contextDeal->GetBundleManager(); + if (bundleMgr == nullptr) { + APP_LOGE("MainThread::handleLaunchApplication GetBundleManager is nullptr"); + return; + } + APP_LOGI("MainThread::handleLaunchApplication. End calling GetBundleManager."); + + BundleInfo bundleInfo; + APP_LOGI("MainThread::handleLaunchApplication length: %{public}zu, bundleName: %{public}s", + appInfo.bundleName.length(), appInfo.bundleName.c_str()); + bundleMgr->GetBundleInfo(appInfo.bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); + + if (!InitResourceManager(resourceManager, contextDeal, appInfo, bundleInfo)) { APP_LOGE("MainThread::handleLaunchApplication InitResourceManager failed"); return; } + if (bundleInfo.compatibleVersion >= TARGET_VERSION_THRESHOLDS) { + // Create runtime + AbilityRuntime::Runtime::Options options; + options.codePath = appInfo.codePath; + auto runtime = AbilityRuntime::Runtime::Create(options); + if (!runtime) { + APP_LOGE("OHOSApplication::OHOSApplication: Failed to create runtime"); + return; + } + + if (runtime->GetLanguage() == AbilityRuntime::Runtime::Language::JS) { + std::unique_ptr> idleTask = std::make_unique>(); + *idleTask = [&jsRuntime = static_cast(*runtime), &idleTask = *idleTask]() { + jsRuntime.GetNativeEngine().Loop(LOOP_NOWAIT); + EventHandler::Current()->PostIdleTask(idleTask); + }; + mainHandler_->PostIdleTask(*idleTask.release()); + } + + application_->SetRuntime(std::move(runtime)); + AbilityLoader::GetInstance().RegisterAbility("Ability", [application = application_]() { + return Ability::Create(application->GetRuntime()); + }); + AbilityLoader::GetInstance().RegisterExtension("ServiceExtension", [application = application_]() { + return AbilityRuntime::ServiceExtension::Create(application->GetRuntime()); + }); + } + contextDeal->initResourceManager(resourceManager); contextDeal->SetApplicationContext(application_); application_->AttachBaseContext(contextDeal); application_->SetAbilityRecordMgr(abilityRecordMgr_); + // create contextImpl + std::shared_ptr contextImpl = std::make_shared(); + contextImpl->SetResourceManager(resourceManager); + contextImpl->SetApplicationInfo(std::make_shared(appInfo)); + contextImpl->InitAppContext(); + application_->SetApplicationContext(contextImpl); + applicationImpl_->SetRecordId(appLaunchData.GetRecordId()); applicationImpl_->SetApplication(application_); mainThreadState_ = MainThreadState::READY; @@ -748,6 +810,7 @@ void MainThread::HandleAbilityStageInfo(const AppResidentProcessInfo &residentPr */ void MainThread::HandleLaunchAbility(const std::shared_ptr &abilityRecord) { + BYTRACE(BYTRACE_TAG_APP); APP_LOGI("MainThread::handleLaunchAbility called start."); if (applicationImpl_ == nullptr) { @@ -785,13 +848,14 @@ void MainThread::HandleLaunchAbility(const std::shared_ptr & } mainThreadState_ = MainThreadState::RUNNING; + std::shared_ptr stageContext = application_->AddAbilityStage(abilityRecord); #ifdef APP_ABILITY_USE_TWO_RUNNER APP_LOGI("MainThread::handleLaunchAbility. Start calling AbilityThreadMain start."); - AbilityThread::AbilityThreadMain(application_, abilityRecord); + AbilityThread::AbilityThreadMain(application_, abilityRecord, stageContext); APP_LOGI("MainThread::handleLaunchAbility. Start calling AbilityThreadMain end."); #else APP_LOGI("MainThread::handleLaunchAbility. Start calling 2 AbilityThreadMain start."); - AbilityThread::AbilityThreadMain(application_, abilityRecord, mainHandler_->GetEventRunner()); + AbilityThread::AbilityThreadMain(application_, abilityRecord, mainHandler_->GetEventRunner(), stageContext); APP_LOGI("MainThread::handleLaunchAbility. Start calling 2 AbilityThreadMain end."); #endif APP_LOGI("MainThread::handleLaunchAbility called end."); @@ -830,7 +894,6 @@ void MainThread::HandleCleanAbilityLocal(const sptr &token) APP_LOGI("MainThread::HandleCleanAbilityLocal ability name: %{public}s", abilityInfo->name.c_str()); abilityRecordMgr_->RemoveAbilityRecord(token); - #ifdef APP_ABILITY_USE_TWO_RUNNER std::shared_ptr runner = record->GetEventRunner(); @@ -856,6 +919,7 @@ void MainThread::HandleCleanAbilityLocal(const sptr &token) */ void MainThread::HandleCleanAbility(const sptr &token) { + BYTRACE(BYTRACE_TAG_APP); APP_LOGI("MainThread::handleCleanAbility called start."); if (!IsApplicationReady()) { APP_LOGE("MainThread::handleCleanAbility not init OHOSApplication, should launch application first"); @@ -880,7 +944,6 @@ void MainThread::HandleCleanAbility(const sptr &token) APP_LOGI("MainThread::handleCleanAbility ability name: %{public}s", abilityInfo->name.c_str()); abilityRecordMgr_->RemoveAbilityRecord(token); - #ifdef APP_ABILITY_USE_TWO_RUNNER std::shared_ptr runner = record->GetEventRunner(); @@ -907,6 +970,7 @@ void MainThread::HandleCleanAbility(const sptr &token) */ void MainThread::HandleForegroundApplication() { + BYTRACE(BYTRACE_TAG_APP); APP_LOGI("MainThread::handleForegroundApplication called start."); if ((application_ == nullptr) || (appMgr_ == nullptr)) { APP_LOGE("MainThread::handleForegroundApplication error!"); @@ -931,6 +995,7 @@ void MainThread::HandleForegroundApplication() */ void MainThread::HandleBackgroundApplication() { + BYTRACE(BYTRACE_TAG_APP); APP_LOGI("MainThread::handleBackgroundApplication called start."); if ((application_ == nullptr) || (appMgr_ == nullptr)) { @@ -956,6 +1021,7 @@ void MainThread::HandleBackgroundApplication() */ void MainThread::HandleTerminateApplication() { + BYTRACE(BYTRACE_TAG_APP); APP_LOGI("MainThread::handleTerminateApplication called start."); if ((application_ == nullptr) || (appMgr_ == nullptr)) { APP_LOGE("MainThread::handleTerminateApplication error!"); @@ -1009,6 +1075,7 @@ void MainThread::HandleTerminateApplication() */ void MainThread::HandleShrinkMemory(const int level) { + BYTRACE(BYTRACE_TAG_APP); APP_LOGI("MainThread::HandleShrinkMemory called start."); if (applicationImpl_ == nullptr) { @@ -1029,6 +1096,7 @@ void MainThread::HandleShrinkMemory(const int level) */ void MainThread::HandleConfigurationUpdated(const Configuration &config) { + BYTRACE(BYTRACE_TAG_APP); APP_LOGI("MainThread::HandleConfigurationUpdated called start."); if (applicationImpl_ == nullptr) { diff --git a/kits/appkit/native/app/src/ohos_application.cpp b/kits/appkit/native/app/src/ohos_application.cpp index e5666c8a04..48fc6c214b 100644 --- a/kits/appkit/native/app/src/ohos_application.cpp +++ b/kits/appkit/native/app/src/ohos_application.cpp @@ -14,11 +14,14 @@ */ #include "ohos_application.h" -#include "application_impl.h" + #include "ability_record_mgr.h" #include "app_loader.h" #include "app_log_wrapper.h" +#include "application_impl.h" +#include "context_impl.h" #include "iservice_registry.h" +#include "runtime.h" #include "system_ability_definition.h" namespace OHOS { @@ -31,6 +34,8 @@ OHOSApplication::OHOSApplication() elementsCallbacks_.clear(); } +OHOSApplication::~OHOSApplication() = default; + /** * * @brief Called when Ability#onSaveAbilityState(PacMap) was called on an ability. @@ -109,6 +114,38 @@ void OHOSApplication::DumpApplication() } } +/** + * @brief Set Runtime + * + * @param runtime Runtime instance. + */ +void OHOSApplication::SetRuntime(std::unique_ptr&& runtime) +{ + APP_LOGI("OHOSApplication::SetRuntime begin"); + if (runtime == nullptr) { + APP_LOGE("OHOSApplication::SetRuntime failed, runtime is empty"); + return; + } + runtime_ = std::move(runtime); + APP_LOGI("OHOSApplication::SetRuntime end"); +} + +/** + * @brief Set ApplicationContext + * + * @param abilityRuntimeContext ApplicationContext instance. + */ +void OHOSApplication::SetApplicationContext(const std::shared_ptr &abilityRuntimeContext) +{ + APP_LOGI("OHOSApplication::SetApplicationContext begin"); + if (abilityRuntimeContext == nullptr) { + APP_LOGE("OHOSApplication::SetApplicationContext failed, context is empty"); + return; + } + abilityRuntimeContext_ = abilityRuntimeContext; + APP_LOGI("OHOSApplication::SetApplicationContext end"); +} + /** * * @brief Set the abilityRecordMgr to the OHOSApplication. @@ -125,7 +162,7 @@ void OHOSApplication::SetAbilityRecordMgr(const std::shared_ptr OHOSApplication::AddAbilityStage( + const std::shared_ptr &abilityRecord) +{ + if (abilityRecord == nullptr) { + APP_LOGE("AddAbilityStage:abilityRecord is nullptr"); + return nullptr; + } + const std::shared_ptr &abilityInfo = abilityRecord->GetAbilityInfo(); + if (abilityInfo == nullptr) { + APP_LOGE("AddAbilityStage:abilityInfo is nullptr"); + return nullptr; + } + std::string moduleName = abilityInfo->moduleName; + std::shared_ptr abilityStage; + auto iterator = abilityStages_.find(moduleName); + if (iterator == abilityStages_.end()) { + std::shared_ptr stageContext = std::make_shared(); + stageContext->SetParentContext(abilityRuntimeContext_); + stageContext->InitHapModuleInfo(abilityInfo); + std::shared_ptr hapModuleInfo = stageContext->GetHapModuleInfo(); + if (hapModuleInfo == nullptr) { + APP_LOGE("AddAbilityStage:hapModuleInfo is nullptr"); + return nullptr; + } + abilityStage = AbilityRuntime::AbilityStage::Create(runtime_, *hapModuleInfo); + abilityStage->Init(stageContext); + abilityStage->OnCreate(); + abilityStages_[moduleName] = abilityStage; + } else { + abilityStage = iterator->second; + } + const sptr &token = abilityRecord->GetToken(); + if (token == nullptr) { + APP_LOGE("AddAbilityStage:token is null"); + return nullptr; + } + abilityStage->AddAbility(token, abilityRecord); + return abilityStage->GetContext(); +} + +void OHOSApplication::CleanAbilityStage(const sptr &token, + const std::shared_ptr &abilityInfo) +{ + if (abilityInfo == nullptr) { + APP_LOGE("CleanAbilityStage:abilityInfo is nullptr"); + return; + } + if (token == nullptr) { + APP_LOGE("CleanAbilityStage:token is nullptr"); + return; + } + std::string moduleName = abilityInfo->moduleName; + auto iterator = abilityStages_.find(moduleName); + if (iterator != abilityStages_.end()) { + auto abilityStage = iterator->second; + abilityStage->RemoveAbility(token); + if (!abilityStage->ContainsAbility()) { + abilityStage->OnDestory(); + abilityStages_.erase(moduleName); + } + } +} + +std::shared_ptr OHOSApplication::GetAppContext() const +{ + return abilityRuntimeContext_; +} + +const std::unique_ptr& OHOSApplication::GetRuntime() +{ + return runtime_; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/kits/appkit/native/app/src/sys_mgr_client.cpp b/kits/appkit/native/app/src/sys_mgr_client.cpp index a91a426cdc..5322d19cd9 100644 --- a/kits/appkit/native/app/src/sys_mgr_client.cpp +++ b/kits/appkit/native/app/src/sys_mgr_client.cpp @@ -17,8 +17,8 @@ #include "app_log_wrapper.h" #include "if_system_ability_manager.h" -#include "iservice_registry.h" #include "ipc_skeleton.h" +#include "iservice_registry.h" #include "string_ex.h" namespace OHOS { diff --git a/kits/appkit/native/test/BUILD.gn b/kits/appkit/native/test/BUILD.gn index 7b9f397d75..e2dae10d06 100755 --- a/kits/appkit/native/test/BUILD.gn +++ b/kits/appkit/native/test/BUILD.gn @@ -22,6 +22,7 @@ ABILITY_INNERKITS_PATH = "//foundation/aafwk/standard/interfaces/innerkits" config("module_private_config") { visibility = [ ":*" ] include_dirs = [ + "//foundation/appexecfwk/standard/kits/appkit/native/ability_runtime/context", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr", "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk_L2/content", @@ -109,6 +110,8 @@ ohos_unittest("application_test") { "//foundation/appexecfwk/standard/kits/appkit/native/app/src/app_loader.cpp", "//foundation/appexecfwk/standard/kits/appkit/native/app/src/application_context.cpp", "unittest/application_test.cpp", + "unittest/ability_stage_test.cpp", + "unittest/context_impl_test.cpp", ] configs = [ ":module_private_config" ] @@ -119,6 +122,8 @@ ohos_unittest("application_test") { "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/appexecfwk/standard/kits:app_context", + "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/common:libappexecfwk_common", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", @@ -132,6 +137,7 @@ ohos_unittest("application_test") { ] external_deps = [ + "aafwk_standard:runtime", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] @@ -164,6 +170,7 @@ ohos_unittest("context_container_test") { ] external_deps = [ + "aafwk_standard:runtime", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] @@ -250,6 +257,7 @@ ohos_unittest("context_deal_test") { ] external_deps = [ + "aafwk_standard:runtime", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] @@ -285,6 +293,7 @@ ohos_unittest("application_impl_test") { ] external_deps = [ + "aafwk_standard:runtime", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h b/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h index d5186e5c1f..eb6f925b40 100644 --- a/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h +++ b/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h @@ -18,14 +18,14 @@ #include -#include "iremote_object.h" -#include "iremote_stub.h" #include "ability_connect_callback_interface.h" +#include "ability_context.h" +#include "ability_manager_client.h" #include "ability_manager_errors.h" -#include "ability_scheduler_interface.h" #include "ability_manager_interface.h" -#include "ability_manager_client.h" -#include "ability_context.h" +#include "ability_scheduler_interface.h" +#include "iremote_object.h" +#include "iremote_stub.h" #include "want.h" namespace OHOS { diff --git a/kits/appkit/native/test/unittest/ability_stage_test.cpp b/kits/appkit/native/test/unittest/ability_stage_test.cpp new file mode 100644 index 0000000000..72a02cc7af --- /dev/null +++ b/kits/appkit/native/test/unittest/ability_stage_test.cpp @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "ability_local_record.h" +#include "ability_stage.h" +#include "context.h" +#include "context_impl.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +class AbilityStageTest : public testing::Test { +public: + AbilityStageTest() : abilityStage_(nullptr) + {} + ~AbilityStageTest() + {} + std::shared_ptr abilityStage_ = nullptr; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +class MockToken : public OHOS::IRemoteObject { +public: + int32_t GetObjectRefCount() override + { + return 0; + } + + int SendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override + { + return 0; + } + + bool AddDeathRecipient(const sptr &recipient) override + { + return true; + } + + bool RemoveDeathRecipient(const sptr &recipient) override + { + return true; + } + + int Dump(int fd, const std::vector &args) override + { + return 0; + } +}; + +void AbilityStageTest::SetUpTestCase(void) +{} + +void AbilityStageTest::TearDownTestCase(void) +{} + +void AbilityStageTest::SetUp(void) +{ + abilityStage_ = std::make_shared(); +} + +void AbilityStageTest::TearDown(void) +{} + +/** + * @tc.number: AppExecFwk_AbilityStage_GetContext_001 + * @tc.name: GetContext + * @tc.desc: Test whether getContext is called normally. + * @tc.type: FUNC + * @tc.require: SR000GH1HL + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_GetContext_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_GetContext_001 start"; + std::shared_ptr context = abilityStage_->GetContext(); + EXPECT_EQ(context, nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_GetContext_001 end"; +} + +/** + * @tc.number: AppExecFwk_AbilityStage_GetContext_002 + * @tc.name: GetContext + * @tc.desc: Test whether getContext is called normally. + * @tc.type: FUNC + * @tc.require: AR000GJ71I + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_GetContext_002, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_GetContext_002 start"; + std::shared_ptr context = std::make_shared(); + abilityStage_->Init(context); + EXPECT_NE(abilityStage_->GetContext(), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_GetContext_002 end"; +} + +/** + * @tc.number: AppExecFwk_AbilityStage_AddAbility_001 + * @tc.name: AddAbility + * @tc.desc: Test whether AddAbility is called normally. + * @tc.type: FUNC + * @tc.require: AR000GJ719 + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_AddAbility_001, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_AddAbility_001 start"; + EXPECT_FALSE(abilityStage_->ContainsAbility()); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_AddAbility_001 end"; +} + +/** + * @tc.number: AppExecFwk_AbilityStage_AddAbility_002 + * @tc.name: AddAbility + * @tc.desc: Test whether AddAbility is called normally. + * @tc.type: FUNC + * @tc.require: AR000GJ719 + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_AddAbility_002, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_AddAbility_002 start"; + sptr token = new MockToken(); + abilityStage_->AddAbility(token, std::make_shared(nullptr, nullptr)); + EXPECT_TRUE(abilityStage_->ContainsAbility()); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_AddAbility_002 end"; +} + +/** + * @tc.number: AppExecFwk_AbilityStage_RemoveAbility_001 + * @tc.name: RemoveAbility + * @tc.desc: Test whether RemoveAbility is called normally. + * @tc.type: FUNC + * @tc.require: AR000GJ719 + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_RemoveAbility_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_RemoveAbility_001 start"; + EXPECT_FALSE(abilityStage_->ContainsAbility()); + abilityStage_->RemoveAbility(nullptr); + EXPECT_FALSE(abilityStage_->ContainsAbility()); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_RemoveAbility_001 end"; +} + +/** + * @tc.number: AppExecFwk_AbilityStage_RemoveAbility_002 + * @tc.name: RemoveAbility + * @tc.desc: Test whether RemoveAbility is called normally. + * @tc.type: FUNC + * @tc.require: AR000GJ719 + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_RemoveAbility_002, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_RemoveAbility_002 start"; + sptr token = new MockToken(); + abilityStage_->AddAbility(token, std::make_shared(nullptr, nullptr)); + EXPECT_TRUE(abilityStage_->ContainsAbility()); + abilityStage_->RemoveAbility(token); + EXPECT_FALSE(abilityStage_->ContainsAbility()); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_RemoveAbility_002 end"; +} + +/** + * @tc.number: AppExecFwk_AbilityStage_ContainsAbility_001 + * @tc.name: ContainsAbility + * @tc.desc: Test whether ContainsAbility is called normally. + * @tc.type: FUNC + * @tc.require: AR000GJ719 + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_ContainsAbility_001, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_ContainsAbility_001 start"; + EXPECT_FALSE(abilityStage_->ContainsAbility()); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_ContainsAbility_001 end"; +} + +/** + * @tc.number: AppExecFwk_AbilityStage_ContainsAbility_002 + * @tc.name: ContainsAbility + * @tc.desc: Test whether ContainsAbility is called normally. + * @tc.type: FUNC + * @tc.require: AR000GJ719 + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_ContainsAbility_002, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_ContainsAbility_002 start"; + sptr token = new MockToken(); + abilityStage_->AddAbility(token, std::make_shared(nullptr, nullptr)); + EXPECT_TRUE(abilityStage_->ContainsAbility()); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_ContainsAbility_002 end"; +} +} // namespace AppExecFwk +} \ No newline at end of file diff --git a/kits/appkit/native/test/unittest/context_deal_for_task_dispacher_test.cpp b/kits/appkit/native/test/unittest/context_deal_for_task_dispacher_test.cpp index 21c1c1b065..ec6ff8f756 100644 --- a/kits/appkit/native/test/unittest/context_deal_for_task_dispacher_test.cpp +++ b/kits/appkit/native/test/unittest/context_deal_for_task_dispacher_test.cpp @@ -17,8 +17,8 @@ #include #include "application_context.h" -#include "event_runner.h" #include "context_deal.h" +#include "event_runner.h" namespace OHOS { diff --git a/kits/appkit/native/test/unittest/context_deal_interface1_test.cpp b/kits/appkit/native/test/unittest/context_deal_interface1_test.cpp index afaa615d59..cba43f8fd1 100644 --- a/kits/appkit/native/test/unittest/context_deal_interface1_test.cpp +++ b/kits/appkit/native/test/unittest/context_deal_interface1_test.cpp @@ -13,15 +13,15 @@ * limitations under the License. */ -#include -#include #include "gmock/gmock.h" +#include +#include -#include "context_deal.h" -#include "ohos_application.h" #include "ability_handler.h" #include "ability_info.h" #include "ability.h" +#include "context_deal.h" +#include "ohos_application.h" #include "mock_ability_manager_client_interface1.h" #include "mock_resourceManager_interface1.h" diff --git a/kits/appkit/native/test/unittest/context_impl_test.cpp b/kits/appkit/native/test/unittest/context_impl_test.cpp new file mode 100644 index 0000000000..014a504d80 --- /dev/null +++ b/kits/appkit/native/test/unittest/context_impl_test.cpp @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "ability_local_record.h" +#include "context_impl.h" +#include "context.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +class ContextImplTest : public testing::Test { +public: + ContextImplTest() : contextImpl_(nullptr) + {} + ~ContextImplTest() + {} + std::shared_ptr contextImpl_ = nullptr; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void ContextImplTest::SetUpTestCase(void) +{} + +void ContextImplTest::TearDownTestCase(void) +{} + +void ContextImplTest::SetUp(void) +{ + contextImpl_ = std::make_shared(); +} + +void ContextImplTest::TearDown(void) +{} + +/** + * @tc.number: AppExecFwk_ContextImpl_GetBundleName_001 + * @tc.name: GetBundleName + * @tc.desc: Test whether GetBundleName is called normally. + * @tc.type: FUNC + * @tc.require: SR000GH1HL + */ +HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetBundleName_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetBundleName_001 start"; + std::string bundleName = contextImpl_->GetBundleName(); + EXPECT_STREQ(bundleName.c_str(), ""); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetBundleName_001 end"; +} + +/** + * @tc.number: AppExecFwk_ContextImpl_GetBundleName_002 + * @tc.name: GetBundleName + * @tc.desc: Test whether GetBundleName is called normally. + * @tc.type: FUNC + * @tc.require: SR000GH1HL + */ +HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetBundleName_002, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetBundleName_002 start"; + std::shared_ptr applicationInfo = std::make_shared(); + applicationInfo->bundleName = "com.test"; + contextImpl_->SetApplicationInfo(applicationInfo); + std::string bundleName = contextImpl_->GetBundleName(); + EXPECT_STREQ(bundleName.c_str(), "com.test"); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetBundleName_002 end"; +} + +/** + * @tc.number: AppExecFwk_ContextImpl_SetApplicationInfo_001 + * @tc.name: SetApplicationInfo + * @tc.desc: Test whether SetApplicationInfo is called normally. + * @tc.type: FUNC + * @tc.require: SR000GH1HL + */ +HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_SetApplicationInfo_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_SetApplicationInfo_001 start"; + std::shared_ptr applicationInfo = std::make_shared(); + contextImpl_->SetApplicationInfo(applicationInfo); + EXPECT_NE(contextImpl_->GetApplicationInfo(), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_SetApplicationInfo_001 end"; +} + +/** + * @tc.number: AppExecFwk_ContextImpl_GetApplicationInfo_001 + * @tc.name: GetApplicationInfo + * @tc.desc: Test whether GetApplicationInfo is called normally. + * @tc.type: FUNC + * @tc.require: SR000GH1HL + */ +HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetApplicationInfo_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetApplicationInfo_001 start"; + EXPECT_NE(contextImpl_->GetApplicationInfo(), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetApplicationInfo_001 end"; +} + +/** + * @tc.number: AppExecFwk_ContextImpl_GetApplicationContext_001 + * @tc.name: GetApplicationContext + * @tc.desc: Test whether GetApplicationContext is called normally. + * @tc.type: FUNC + * @tc.require: SR000GH1HL + */ +HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetApplicationContext_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetApplicationContext_001 start"; + EXPECT_EQ(contextImpl_->GetApplicationContext(), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetApplicationContext_001 end"; +} + +/** + * @tc.number: AppExecFwk_ContextImpl_SetParentContext_001 + * @tc.name: SetParentContext + * @tc.desc: Test whether SetParentContext is called normally. + * @tc.type: FUNC + * @tc.require: SR000GH1HL + */ +HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_SetParentContext_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_SetParentContext_001 start"; + std::shared_ptr contextImpl_ = std::make_shared(); + contextImpl_->SetParentContext(contextImpl_); + EXPECT_NE(contextImpl_->GetApplicationContext(), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_SetParentContext_001 end"; +} + +/** + * @tc.number: AppExecFwk_ContextImpl_GetHapModuleInfo_001 + * @tc.name: GetHapModuleInfo + * @tc.desc: Test whether GetHapModuleInfo is called normally. + * @tc.type: FUNC + * @tc.require: SR000GH1HL + */ +HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetHapModuleInfo_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetHapModuleInfo_001 start"; + EXPECT_EQ(contextImpl_->GetHapModuleInfo(), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetHapModuleInfo_001 end"; +} +} // namespace AppExecFwk +} \ No newline at end of file diff --git a/kits/appkit/test/BUILD.gn b/kits/appkit/test/BUILD.gn index c2069eb70e..a3a4a80b17 100755 --- a/kits/appkit/test/BUILD.gn +++ b/kits/appkit/test/BUILD.gn @@ -78,6 +78,7 @@ ohos_moduletest("appexecfwk_appkit_native_app_module_test_first") { external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "bytrace_standard:bytrace_core", ] } @@ -117,6 +118,7 @@ ohos_moduletest("appexecfwk_appkit_native_app_module_test_second") { external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "bytrace_standard:bytrace_core", ] } @@ -156,6 +158,7 @@ ohos_moduletest("appexecfwk_appkit_native_app_module_test_third") { external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "bytrace_standard:bytrace_core", ] } @@ -195,6 +198,7 @@ ohos_moduletest("appexecfwk_appkit_native_app_module_test_fourth") { external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "bytrace_standard:bytrace_core", ] } diff --git a/kits/appkit/test/Mock/include/mock_bundle_mgr_service.h b/kits/appkit/test/Mock/include/mock_bundle_mgr_service.h index f324c31467..e78184cd0e 100755 --- a/kits/appkit/test/Mock/include/mock_bundle_mgr_service.h +++ b/kits/appkit/test/Mock/include/mock_bundle_mgr_service.h @@ -63,6 +63,7 @@ public: } MOCK_METHOD2(GetBundleInfosByMetaData, bool(const std::string &metaData, std::vector &bundleInfos)); MOCK_METHOD2(QueryAbilityInfo, bool(const Want &want, AbilityInfo &abilityInfo)); + MOCK_METHOD2(QueryAbilityInfosForClone, bool(const Want &want, std::vector &abilityInfos)); MOCK_METHOD2(QueryAbilityInfoByUri, bool(const std::string &abilityUri, AbilityInfo &abilityInfo)); MOCK_METHOD1(QueryKeepAliveBundleInfos, bool(std::vector &bundleInfos)); MOCK_METHOD2(GetAbilityLabel, std::string(const std::string &bundleName, const std::string &className)); diff --git a/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_fourth.cpp b/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_fourth.cpp index ac5ec82087..b53fbae6c2 100644 --- a/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_fourth.cpp +++ b/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_fourth.cpp @@ -15,13 +15,13 @@ #include #include "main_thread.h" -#include "sys_mgr_client.h" -#include "system_ability_definition.h" +#include "mock_ability_mgr_service.h" +#include "mock_ability_token.h" #include "mock_app_mgr_service.h" #include "mock_app_thread.h" -#include "mock_ability_token.h" -#include "mock_ability_mgr_service.h" #include "mock_bundle_mgr_service.h" +#include "sys_mgr_client.h" +#include "system_ability_definition.h" namespace OHOS { namespace AppExecFwk { diff --git a/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_third.cpp b/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_third.cpp index a6d6b60346..1e45f2b80b 100644 --- a/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_third.cpp +++ b/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_third.cpp @@ -15,13 +15,13 @@ #include #include "main_thread.h" -#include "sys_mgr_client.h" -#include "system_ability_definition.h" +#include "mock_ability_mgr_service.h" +#include "mock_ability_token.h" #include "mock_app_mgr_service.h" #include "mock_app_thread.h" -#include "mock_ability_token.h" -#include "mock_ability_mgr_service.h" #include "mock_bundle_mgr_service.h" +#include "sys_mgr_client.h" +#include "system_ability_definition.h" namespace OHOS { namespace AppExecFwk { diff --git a/libs/libeventhandler/BUILD.gn b/libs/libeventhandler/BUILD.gn index 998c9297e7..362c23ad74 100644 --- a/libs/libeventhandler/BUILD.gn +++ b/libs/libeventhandler/BUILD.gn @@ -20,6 +20,7 @@ config("libeventhandler_config") { "//utils/native/base/include", "src", "//base/hiviewdfx/interfaces/innerkits/libhilog/include", + "//base/hiviewdfx/interfaces/innerkits/libhitrace/include", ] } diff --git a/libs/libeventhandler/src/epoll_io_waiter.h b/libs/libeventhandler/src/epoll_io_waiter.h index 7f274bab49..8c6f28470b 100644 --- a/libs/libeventhandler/src/epoll_io_waiter.h +++ b/libs/libeventhandler/src/epoll_io_waiter.h @@ -19,8 +19,8 @@ #include #include -#include "nocopyable.h" #include "io_waiter.h" +#include "nocopyable.h" namespace OHOS { namespace AppExecFwk { diff --git a/libs/libeventhandler/src/event_handler.cpp b/libs/libeventhandler/src/event_handler.cpp index 7a6fa63a4c..382751d162 100644 --- a/libs/libeventhandler/src/event_handler.cpp +++ b/libs/libeventhandler/src/event_handler.cpp @@ -69,6 +69,13 @@ bool EventHandler::SendEvent(InnerEvent::Pointer &event, int64_t delayTime, Prio } event->SetOwner(shared_from_this()); + // get traceId from event, if HiTrace::begin has been called, would get a valid trace id. + auto traceId = event->GetOrCreateTraceId(); + // if traceId is valid, out put trace information + if (AllowHiTraceOutPut(traceId, event->HasWaiter())) { + HiTracePointerOutPut(traceId, event, "Send", HiTraceTracepointType::HITRACE_TP_CS); + } + eventRunner_->GetEventQueue()->Insert(event, priority); return true; } @@ -104,6 +111,10 @@ bool EventHandler::SendSyncEvent(InnerEvent::Pointer &event, Priority priority) DistributeEvent(event); return true; } + + // get traceId from event, if HiTrace::begin has been called, would get a valid trace id. + auto spanId = event->GetOrCreateTraceId(); + // Create waiter, used to block. auto waiter = event->CreateWaiter(); // Send this event as normal one. @@ -113,6 +124,10 @@ bool EventHandler::SendSyncEvent(InnerEvent::Pointer &event, Priority priority) // Wait until event is processed(recycled). waiter->Wait(); + if ((spanId) && (spanId->IsValid())) { + HiTrace::Tracepoint(HiTraceTracepointType::HITRACE_TP_CR, *spanId, "event is processed"); + } + return true; } @@ -231,6 +246,15 @@ void EventHandler::DistributeEvent(const InnerEvent::Pointer &event) std::weak_ptr oldHandler = currentEventHandler; // Save current event handler into thread local data. currentEventHandler = shared_from_this(); + + auto spanId = event->GetTraceId(); + auto traceId = HiTrace::GetId(); + bool allowTraceOutPut = AllowHiTraceOutPut(spanId, event->HasWaiter()); + if (allowTraceOutPut) { + HiTrace::SetId(*spanId); + HiTracePointerOutPut(spanId, event, "Receive", HiTraceTracepointType::HITRACE_TP_SR); + } + if (event->HasTask()) { // Call task callback directly if contains a task. (event->GetTaskCallback())(); @@ -238,6 +262,15 @@ void EventHandler::DistributeEvent(const InnerEvent::Pointer &event) // Otherwise let developers to handle it. ProcessEvent(event); } + + if (allowTraceOutPut) { + HiTrace::Tracepoint(HiTraceTracepointType::HITRACE_TP_SS, *spanId, "Event Distribute over"); + HiTrace::ClearId(); + if (traceId.IsValid()) { + HiTrace::SetId(traceId); + } + } + // Restore current event handler. if (oldHandler.expired()) { currentEventHandler = nullptr; diff --git a/libs/libeventhandler/src/event_handler_utils.h b/libs/libeventhandler/src/event_handler_utils.h index a089c59665..7f71137f7c 100644 --- a/libs/libeventhandler/src/event_handler_utils.h +++ b/libs/libeventhandler/src/event_handler_utils.h @@ -22,6 +22,7 @@ #include #include "hilog/log.h" +#include "hitrace/trace.h" #include "inner_event.h" #define DEFINE_HILOG_LABEL(name) static constexpr OHOS::HiviewDFX::HiLogLabel LOG_LABEL = {LOG_CORE, LOG_DOMAIN, name} @@ -63,6 +64,31 @@ static inline int32_t NanosecondsToTimeout(int64_t nanoseconds) return (milliseconds > INT32_MAX) ? INT32_MAX : static_cast(milliseconds); } +using HiTrace = OHOS::HiviewDFX::HiTrace; + +static inline bool AllowHiTraceOutPut(const std::shared_ptr& traceId, bool isSyncEvent) +{ + if ((!traceId) || (!traceId->IsValid())) { + return false; + } + if ((!isSyncEvent) && (!traceId->IsFlagEnabled(HITRACE_FLAG_INCLUDE_ASYNC))) { + return false; + } + return true; +} + +static inline void HiTracePointerOutPut(const std::shared_ptr& spanId, + const InnerEvent::Pointer& event, const char* action, HiTraceTracepointType type) +{ + if (!event->HasTask()) { + HiTrace::Tracepoint(type, *spanId, "%s event, event id: %d", action, event->GetInnerEventId()); + } else if (!event->GetTaskName().empty()) { + HiTrace::Tracepoint(type, *spanId, "%s task with name, name: %s", action, event->GetTaskName().c_str()); + } else { + HiTrace::Tracepoint(type, *spanId, "%s UnNamed Task", action); + } +} + static inline char *GetLastErr() { return strerror(errno); diff --git a/libs/libeventhandler/src/event_runner.cpp b/libs/libeventhandler/src/event_runner.cpp index 7ec620864c..7cdeb324dd 100644 --- a/libs/libeventhandler/src/event_runner.cpp +++ b/libs/libeventhandler/src/event_runner.cpp @@ -27,8 +27,8 @@ #include "event_handler.h" #include "event_handler_utils.h" #include "event_inner_runner.h" -#include "thread_local_data.h" #include "singleton.h" +#include "thread_local_data.h" DEFINE_HILOG_LABEL("EventRunner"); diff --git a/libs/libeventhandler/src/inner_event.cpp b/libs/libeventhandler/src/inner_event.cpp index 2237701e08..e794879a1e 100644 --- a/libs/libeventhandler/src/inner_event.cpp +++ b/libs/libeventhandler/src/inner_event.cpp @@ -204,6 +204,11 @@ void InnerEvent::ClearEvent() smartPtrTypeId_ = 0; } } + + if (hiTraceId_) { + hiTraceId_.reset(); + } + // Clear owner owner_.reset(); } @@ -224,6 +229,26 @@ bool InnerEvent::HasWaiter() const return (waiter_ != nullptr); } +const std::shared_ptr InnerEvent::GetOrCreateTraceId() +{ + if (hiTraceId_) { + return hiTraceId_; + } + + auto traceId = HiTrace::GetId(); + if (!traceId.IsValid()) { + return nullptr; + } + + hiTraceId_ = std::make_shared(HiTrace::CreateSpan()); + return hiTraceId_; +} + +const std::shared_ptr InnerEvent::GetTraceId() +{ + return hiTraceId_; +} + std::string InnerEvent::Dump() { std::string content; diff --git a/libs/libeventhandler/test/BUILD.gn b/libs/libeventhandler/test/BUILD.gn index fd01bf7a75..20c0e637c5 100644 --- a/libs/libeventhandler/test/BUILD.gn +++ b/libs/libeventhandler/test/BUILD.gn @@ -35,7 +35,10 @@ ohos_unittest("LibEventHandlerEventQueueTest") { deps = [ "//third_party/googletest:gtest_main" ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "hitrace_native:libhitrace", + ] } ohos_unittest("LibEventHandlerEventTest") { @@ -49,7 +52,10 @@ ohos_unittest("LibEventHandlerEventTest") { deps = [ "//third_party/googletest:gtest_main" ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "hitrace_native:libhitrace", + ] } ohos_unittest("LibEventHandlerEventRunnerTest") { @@ -63,7 +69,33 @@ ohos_unittest("LibEventHandlerEventRunnerTest") { deps = [ "//third_party/googletest:gtest_main" ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "hitrace_native:libhitrace", + ] +} + +ohos_unittest("LibEventHandlerTraceTest") { + module_out_path = module_output_path + + sources = lib_event_handler_sources + + sources += [ + "unittest/lib_event_handler_trace_test.cpp", + ] + + configs = [ + ":libeventhandler_test_private_config", + ] + + deps = [ + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "hitrace_native:libhitrace", + ] } group("unittest") { @@ -73,5 +105,6 @@ group("unittest") { ":LibEventHandlerEventQueueTest", ":LibEventHandlerEventRunnerTest", ":LibEventHandlerEventTest", + ":LibEventHandlerTraceTest", ] } diff --git a/libs/libeventhandler/test/unittest/lib_event_handler_trace_test.cpp b/libs/libeventhandler/test/unittest/lib_event_handler_trace_test.cpp new file mode 100644 index 0000000000..bbf19e7640 --- /dev/null +++ b/libs/libeventhandler/test/unittest/lib_event_handler_trace_test.cpp @@ -0,0 +1,586 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include + +#include "hitrace/trace.h" +#define private public +#include "event_handler.h" +#include "event_runner.h" + +using namespace testing::ext; +using namespace OHOS::AppExecFwk; +using namespace OHOS::HiviewDFX; + +using WaitFunc = std::function; + +std::atomic g_eventProcess(false); +const int32_t USLEEP_STEP = 100; +const int32_t USLEEP_TIME_OUT = 50000; + +class FirstTestEventHandler : public EventHandler { +public: + explicit FirstTestEventHandler(const std::shared_ptr& runner) : EventHandler(runner) {} + ~FirstTestEventHandler() override {} + + void ProcessEvent(const InnerEvent::Pointer& event) override + { + auto traceId = event->GetOrCreateTraceId(); + switch (event->GetParam()) { + case HITRACE_FLAG_INCLUDE_ASYNC: { + EXPECT_TRUE(traceId->IsFlagEnabled(HITRACE_FLAG_INCLUDE_ASYNC)); + break; + } + case (HITRACE_FLAG_TP_INFO | HITRACE_FLAG_INCLUDE_ASYNC): { + EXPECT_TRUE(traceId->IsFlagEnabled(HITRACE_FLAG_TP_INFO)); + break; + } + case HITRACE_FLAG_DONOT_CREATE_SPAN: { + EXPECT_TRUE(traceId->IsValid()); + break; + } + case (HITRACE_FLAG_INCLUDE_ASYNC | HITRACE_FLAG_NO_BE_INFO): { + EXPECT_TRUE(traceId->IsFlagEnabled(HITRACE_FLAG_NO_BE_INFO)); + break; + } + case (HITRACE_FLAG_INCLUDE_ASYNC | HITRACE_FLAG_DONOT_ENABLE_LOG): { + EXPECT_TRUE(traceId->IsFlagEnabled(HITRACE_FLAG_DONOT_ENABLE_LOG)); + break; + } + case (HITRACE_FLAG_INCLUDE_ASYNC | HITRACE_FLAG_FAULT_TRIGGER): { + EXPECT_TRUE(traceId->IsFlagEnabled(HITRACE_FLAG_FAULT_TRIGGER)); + break; + } + default: + break; + } + g_eventProcess.store(true); + } +}; + +class SecondTestEventHandler : public EventHandler { +public: + explicit SecondTestEventHandler(const std::shared_ptr& runner) : EventHandler(runner) {} + ~SecondTestEventHandler() override {} + + void ProcessEvent(const InnerEvent::Pointer& event) override + { + auto eventTraceId = event->GetOrCreateTraceId(); + EXPECT_TRUE(eventTraceId->IsValid()); + g_eventProcess.store(true); + } +}; + +class ThirdTestEventHandler : public EventHandler { +public: + explicit ThirdTestEventHandler(const std::shared_ptr& runner) : EventHandler(runner) {} + ~ThirdTestEventHandler() override {} + + void ProcessEvent(const InnerEvent::Pointer& event) override + { + auto eventTraceId = event->GetOrCreateTraceId(); + EXPECT_FALSE(eventTraceId->IsValid()); + g_eventProcess.store(true); + } +}; + +/** + * wait until waitFunc return true. + */ +void Wait(const WaitFunc& waitFunc) +{ + uint32_t sleepTime = 0; + bool timeOut = false; + while (waitFunc()) { + usleep(USLEEP_STEP); + sleepTime += USLEEP_STEP; + if (sleepTime > USLEEP_TIME_OUT) { + timeOut = true; + break; + } + } + EXPECT_FALSE(timeOut); +} + +void TraceFlagTest(int flagParam) +{ + auto runner = EventRunner::Create(true); + auto handler = std::make_shared(runner); + uint32_t innerEventId = 0; + auto event = InnerEvent::Get(innerEventId, flagParam); + handler->SendEvent(event); + auto process = []() { + return !g_eventProcess.load(); + }; + Wait(process); +} + +class LibEventHandlerTraceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void LibEventHandlerTraceTest::SetUpTestCase() {} + +void LibEventHandlerTraceTest::TearDownTestCase() {} + +void LibEventHandlerTraceTest::SetUp() {} + +void LibEventHandlerTraceTest::TearDown() +{ + /** + * @tc.teardown:reset g_eventProcess value. + */ + g_eventProcess.store(false); +} + +/** + * @tc.name: EventTrace001 + * @tc.desc: trace id of event is not valid when not add trace id to event. + * @tc.type: FUNC + * @tc.require: AR000GGRVV + * @tc.author: liuyanzhi + */ +HWTEST_F(LibEventHandlerTraceTest, EventTrace001, TestSize.Level0) +{ + /** + * @tc.setup: get event with eventId and param. + */ + uint32_t eventId = 0; + int64_t eventParam = 0; + auto event = InnerEvent::Get(eventId, eventParam); + + /** + * @tc.steps: step1. get trace id from event and check wheather the trace id is valid. + * @tc.expected: step1. trace id is not valid. + */ + auto traceId = event->GetOrCreateTraceId(); + auto eventTraceId = event->GetTraceId(); + EXPECT_FALSE(traceId->IsValid()); + EXPECT_FALSE(eventTraceId->IsValid()); +} + +/** + * @tc.name: EventTrace002 + * @tc.desc: Check wheather trace id of event is valid when begin hitrace. + * @tc.type: FUNC + * @tc.require: AR000GGRVV + * @tc.author: liuyanzhi + */ +HWTEST_F(LibEventHandlerTraceTest, EventTrace002, TestSize.Level0) +{ + /** + * @tc.setup: begin hitrace and get event with eventId and param. + */ + auto initId = HiTrace::Begin("EventHandler", HITRACE_FLAG_INCLUDE_ASYNC); + uint32_t eventId = 0; + int64_t eventParam = 0; + auto event = InnerEvent::Get(eventId, eventParam); + + /** + * @tc.steps: step1. call GetOrCreateTraceId to add trace into event and get trace id from event . + * @tc.expected: step1. trace id is valid. + */ + auto traceId = event->GetOrCreateTraceId(); + auto eventTraceId = event->GetTraceId(); + EXPECT_TRUE(traceId->IsValid()); + EXPECT_TRUE(eventTraceId->IsValid()); + + /** + * @tc.teardown: end trace id. + */ + HiTrace::End(initId); +} + +/** + * @tc.name: BeginTrace001 + * @tc.desc: Check wheather trace id of event is valid when begin hitrace. + * @tc.type: FUNC + * @tc.require: AR000GGRVV + * @tc.author: liuyanzhi + */ +HWTEST_F(LibEventHandlerTraceTest, BeginTrace001, TestSize.Level0) +{ + /** + * @tc.setup: begin hitrace with flag HITRACE_FLAG_INCLUDE_ASYNC and HITRACE_FLAG_TP_INFO. + */ + auto initId = HiTrace::Begin("EventHandler", HITRACE_FLAG_INCLUDE_ASYNC | HITRACE_FLAG_TP_INFO); + + /** + * @tc.steps: step1. post task and check trace id of event until the task is executed. + * @tc.expected: step1. trace id is valid. + */ + auto runner = EventRunner::Create(true); + auto handler = std::make_shared(runner); + auto f = []() { + HiTraceId traceId = HiTrace::GetId(); + EXPECT_TRUE(traceId.IsValid()); + g_eventProcess.store(true); + }; + handler->PostTask(f); + auto process = []() { + return !g_eventProcess.load(); + }; + Wait(process); + + /** + * @tc.teardown: end trace id. + */ + HiTrace::End(initId); +} + +/** + * @tc.name: BeginTrace002 + * @tc.desc: Check wheather trace id of event is valid when not begin hitrace. + * @tc.type: FUNC + * @tc.require: AR000GGRVV + * @tc.author: liuyanzhi + */ +HWTEST_F(LibEventHandlerTraceTest, BeginTrace002, TestSize.Level0) +{ + /** + * @tc.setup: create runner and handler. + */ + auto runner = EventRunner::Create(true); + auto handler = std::make_shared(runner); + + /** + * @tc.steps: step1. post task and check trace id of event until the task is executed. + * @tc.expected: step1. trace id is not valid. + */ + auto f = []() { + HiTraceId traceId = HiTrace::GetId(); + EXPECT_FALSE(traceId.IsValid()); + g_eventProcess.store(true); + }; + handler->PostTask(f); + auto process = []() { + return !g_eventProcess.load(); + }; + Wait(process); +} + +/** + * @tc.name: TraceFlag001 + * @tc.desc: Check wheather the flag of trace id of event is the same as the flag set when begin trace with the flag + * HITRACE_FLAG_INCLUDE_ASYNC. + * @tc.type: FUNC + * @tc.require: AR000GGRVV + * @tc.author: liuyanzhi + */ +HWTEST_F(LibEventHandlerTraceTest, TraceFlag001, TestSize.Level0) +{ + /** + * @tc.setup: begin trace and set flag HITRACE_FLAG_INCLUDE_ASYNC. + */ + auto initId = HiTrace::Begin("EventHandler", HITRACE_FLAG_INCLUDE_ASYNC); + + /** + * @tc.steps: step1. create runner and handler, get event with id and param and send the event, check wheather the + * flag is the same as the flag set when begin trace + * @tc.expected: step1. the flag is the same. + */ + int flagParam = HITRACE_FLAG_INCLUDE_ASYNC; + TraceFlagTest(flagParam); + + /** + * @tc.teardown: end trace id. + */ + HiTrace::End(initId); +} + +/** + * @tc.name: TraceFlag002 + * @tc.desc: Check wheather the flag of trace id of event is the same as the flag set when begin trace with the flag + * HITRACE_FLAG_DONOT_CREATE_SPAN. + * @tc.type: FUNC + * @tc.require: AR000GGRVV + * @tc.author: liuyanzhi + */ +HWTEST_F(LibEventHandlerTraceTest, TraceFlag002, TestSize.Level0) +{ + /** + * @tc.setup:begin trace and set flag HITRACE_FLAG_DONOT_CREATE_SPAN. + */ + auto initId = HiTrace::Begin("EventHandler", HITRACE_FLAG_DONOT_CREATE_SPAN); + + /** + * @tc.steps: step1. create runner and handler, get event with id and param and send the event, check wheather the + * flag is the same as the flag set when begin trace + * @tc.expected: step1. the flag is the same. + */ + int flagParam = HITRACE_FLAG_DONOT_CREATE_SPAN; + TraceFlagTest(flagParam); + + /** + * @tc.teardown: end trace id. + */ + HiTrace::End(initId); +} + +/** + * @tc.name: TraceFlag003 + * @tc.desc: Check wheather the flag of trace id of event is the same as the flag set when begin trace with the flag + * HITRACE_FLAG_TP_INFO. + * @tc.type: FUNC + * @tc.require: AR000GGRVV + * @tc.author: liuyanzhi + */ +HWTEST_F(LibEventHandlerTraceTest, TraceFlag003, TestSize.Level0) +{ + /** + * @tc.setup:begin trace and set flag HITRACE_FLAG_TP_INFO. + */ + auto initId = HiTrace::Begin("EventHandler", HITRACE_FLAG_TP_INFO | HITRACE_FLAG_INCLUDE_ASYNC); + + /** + * @tc.steps: step1. create runner and handler, get event with id and param and send the event, check wheather the + * flag is the same as the flag set when begin trace + * @tc.expected: step1. the flag is the same. + */ + int flagParam = HITRACE_FLAG_TP_INFO | HITRACE_FLAG_INCLUDE_ASYNC; + TraceFlagTest(flagParam); + + /** + * @tc.teardown: end trace id. + */ + HiTrace::End(initId); +} + +/** + * @tc.name: TraceFlag004 + * @tc.desc: Check wheather the flag of trace id of event is the same as the flag set when begin trace with the flag + * HITRACE_FLAG_NO_BE_INFO. + * @tc.type: FUNC + * @tc.require: AR000GGRVV + * @tc.author: liuyanzhi + */ +HWTEST_F(LibEventHandlerTraceTest, TraceFlag004, TestSize.Level0) +{ + /** + * @tc.setup: begin trace and set flag HITRACE_FLAG_NO_BE_INFO. + */ + auto initId = HiTrace::Begin("EventHandler", HITRACE_FLAG_NO_BE_INFO | HITRACE_FLAG_INCLUDE_ASYNC); + + /** + * @tc.steps: step1. create runner and handler, get event with id and param and send the event, check wheather the + * flag is the same as the flag set when begin trace + * @tc.expected: step1. the flag is the same. + */ + int flagParam = HITRACE_FLAG_NO_BE_INFO | HITRACE_FLAG_INCLUDE_ASYNC; + TraceFlagTest(flagParam); + + /** + * @tc.teardown: end trace id. + */ + HiTrace::End(initId); +} + +/** + * @tc.name: TraceFlag005 + * @tc.desc: Check wheather the flag of trace id of event is the same as the flag set when begin trace with the flag + * HITRACE_FLAG_DONOT_ENABLE_LOG. + * @tc.type: FUNC + * @tc.require: AR000GGRVV + * @tc.author: liuyanzhi + */ +HWTEST_F(LibEventHandlerTraceTest, TraceFlag005, TestSize.Level0) +{ + /** + * @tc.setup: begin trace and set flag HITRACE_FLAG_DONOT_ENABLE_LOG. + */ + auto initId = HiTrace::Begin("EventHandler", HITRACE_FLAG_DONOT_ENABLE_LOG | HITRACE_FLAG_INCLUDE_ASYNC); + + /** + * @tc.steps: step1. create runner and handler, get event with id and param and send the event, check wheather the + * flag is the same as the flag set when begin trace + * @tc.expected: step1. the flag is the same. + */ + int flagParam = HITRACE_FLAG_DONOT_ENABLE_LOG | HITRACE_FLAG_INCLUDE_ASYNC; + TraceFlagTest(flagParam); + + /** + * @tc.teardown: end trace id. + */ + HiTrace::End(initId); +} + +/** + * @tc.name: TraceFlag006 + * @tc.desc: Check wheather the flag of trace id of event is the same as the flag set when begin trace with the flag + * HITRACE_FLAG_FAULT_TRIGGER. + * @tc.type: FUNC + * @tc.require: AR000GGRVV + * @tc.author: liuyanzhi + */ +HWTEST_F(LibEventHandlerTraceTest, TraceFlag006, TestSize.Level0) +{ + /** + * @tc.setup: begin trace and set flag HITRACE_FLAG_FAULT_TRIGGER. + */ + auto initId = HiTrace::Begin("EventHandler", HITRACE_FLAG_FAULT_TRIGGER | HITRACE_FLAG_INCLUDE_ASYNC); + + /** + * @tc.steps: step1. create runner and handler, get event with id and param and send the event, check wheather the + * flag is the same as the flag set when begin trace + * @tc.expected: step1. the flag is the same. + */ + int flagParam = HITRACE_FLAG_FAULT_TRIGGER | HITRACE_FLAG_INCLUDE_ASYNC; + TraceFlagTest(flagParam); + + /** + * @tc.teardown: end trace id. + */ + HiTrace::End(initId); +} + +/** + * @tc.name: DepositTrace001 + * @tc.desc: Check wheather trace id of event is valid when runner and handler belong to the same thread. + * @tc.type: FUNC + * @tc.require: AR000GGRVV + * @tc.author: liuyanzhi + */ +HWTEST_F(LibEventHandlerTraceTest, DepositTrace001, TestSize.Level0) +{ + /** + * @tc.setup: create runner and handler, begin trace and set flag. + */ + auto initId = HiTrace::Begin("EventHandler", HITRACE_FLAG_INCLUDE_ASYNC | HITRACE_FLAG_TP_INFO); + + /** + * @tc.steps: step1. create runner and handler in the same thread, get event and sendEvent, then + * check wheather the trace is valid. + * @tc.expected: step1. trace id is valid. + */ + auto runner = EventRunner::Create(false); + auto handler = std::make_shared(runner); + uint32_t innerEventId = 0; + auto event = InnerEvent::Get(innerEventId); + + auto process = []() { + return !g_eventProcess.load(); + }; + auto f = [&runner, &process]() { + Wait(process); + runner->Stop(); + }; + std::thread newThread(f); + newThread.detach(); + handler->SendEvent(event); + auto result = runner->Run(); + EXPECT_EQ(OHOS::ERR_OK, result); + + /** + * @tc.teardown: end trace id. + */ + HiTrace::End(initId); +} + +/** + * @tc.name: SyncSendTrace001 + * @tc.desc: Check wheather trace id of event is valid when SendSyncEvent. + * @tc.type: FUNC + * @tc.require: AR000GGRVV + * @tc.author: liuyanzhi + */ +HWTEST_F(LibEventHandlerTraceTest, SyncSendTrace001, TestSize.Level0) +{ + /** + * @tc.setup: create runner and handler, begin trace and set flag. + */ + auto initId = HiTrace::Begin("EventHandler", HITRACE_FLAG_INCLUDE_ASYNC | HITRACE_FLAG_TP_INFO); + + /** + * @tc.steps: step1. create runner and handler, make sure the runner is the current runner, then get event and + * send Sync Event, then check wheather the trace is valid. + * @tc.expected: step1. trace id is not valid. + */ + auto runner = EventRunner::Create(true); + auto handler = std::make_shared(runner); + uint32_t innerEventId = 0; + auto event = InnerEvent::Get(innerEventId); + + auto process = []() { + return !g_eventProcess.load(); + }; + + auto running = [&runner]() { + return !runner->IsRunning(); + }; + + auto f = [&runner, &handler, &event, &process, &running]() { + Wait(running); + handler->SendSyncEvent(event); + Wait(process); + }; + auto m = [&handler, &f, &running]() { + Wait(running); + handler->PostTask(f); + }; + + std::thread newThread(m); + newThread.join(); + /** + * @tc.teardown: end trace id. + */ + HiTrace::End(initId); +} + +/** + * @tc.name: SyncSendTrace002 + * @tc.desc: Check wheather trace id of event is valid when SendSyncEvent. + * @tc.type: FUNC + * @tc.require: AR000GGRVV + * @tc.author: liuyanzhi + */ +HWTEST_F(LibEventHandlerTraceTest, SyncSendTrace002, TestSize.Level0) +{ + /** + * @tc.setup: create runner and handler, begin trace and set flag. + */ + auto initId = HiTrace::Begin("EventHandler", HITRACE_FLAG_INCLUDE_ASYNC | HITRACE_FLAG_TP_INFO); + + /** + * @tc.steps: step1. create runner and handler, make sure the runner is not current runner, then get event and + * send Sync Event, then check wheather the trace is valid. + * @tc.expected: step1. trace id is valid. + */ + auto runner = EventRunner::Create(true); + auto handler = std::make_shared(runner); + uint32_t innerEventId = 0; + auto event = InnerEvent::Get(innerEventId); + + auto process = []() { + return !g_eventProcess.load(); + }; + + auto running = [&runner]() { + return !runner->IsRunning(); + }; + + Wait(running); + handler->SendSyncEvent(event); + Wait(process); + /** + * @tc.teardown: end trace id. + */ + HiTrace::End(initId); +} diff --git a/libs/test/moduletest/common/event_handler/BUILD.gn b/libs/test/moduletest/common/event_handler/BUILD.gn index 9789d8fd4c..f618854ab5 100644 --- a/libs/test/moduletest/common/event_handler/BUILD.gn +++ b/libs/test/moduletest/common/event_handler/BUILD.gn @@ -42,7 +42,10 @@ ohos_moduletest("EventHandlerSendEventModuleTest") { deps = [ "//third_party/googletest:gtest_main" ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "hitrace_native:libhitrace", + ] } ohos_moduletest("EventHandlerPostTaskModuleTest") { @@ -59,7 +62,10 @@ ohos_moduletest("EventHandlerPostTaskModuleTest") { deps = [ "//third_party/googletest:gtest_main" ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "hitrace_native:libhitrace", + ] } ohos_moduletest("EventHandlerSetGetRemoveModuleTest") { @@ -76,7 +82,10 @@ ohos_moduletest("EventHandlerSetGetRemoveModuleTest") { deps = [ "//third_party/googletest:gtest_main" ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "hitrace_native:libhitrace", + ] } ohos_moduletest("EventHandlerFdListenerModuleTest") { @@ -93,7 +102,10 @@ ohos_moduletest("EventHandlerFdListenerModuleTest") { deps = [ "//third_party/googletest:gtest_main" ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "hitrace_native:libhitrace", + ] } ohos_moduletest("EventHandlerPressModuleTest") { @@ -110,7 +122,10 @@ ohos_moduletest("EventHandlerPressModuleTest") { deps = [ "//third_party/googletest:gtest_main" ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "hitrace_native:libhitrace", + ] } ohos_moduletest("EventHandlerSendSyncEventModuleTest") { @@ -127,7 +142,10 @@ ohos_moduletest("EventHandlerSendSyncEventModuleTest") { deps = [ "//third_party/googletest:gtest_main" ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "hitrace_native:libhitrace", + ] } ohos_moduletest("EventHandlerSendTimingEventModuleTest") { @@ -144,7 +162,10 @@ ohos_moduletest("EventHandlerSendTimingEventModuleTest") { deps = [ "//third_party/googletest:gtest_main" ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "hitrace_native:libhitrace", + ] } group("moduletest") { diff --git a/mgit.info b/mgit.info new file mode 100644 index 0000000000..13e10fb477 --- /dev/null +++ b/mgit.info @@ -0,0 +1 @@ +hmf/appexecfwk/standard diff --git a/ohos.build b/ohos.build index eff7d380c2..20447a6163 100644 --- a/ohos.build +++ b/ohos.build @@ -63,13 +63,22 @@ }, "name": "//foundation/appexecfwk/standard/interfaces/innerkits/eventhandler_native:eventhandler_native" }, + { + "header": { + "header_base": "//foundation/appexecfwk/standard/interfaces/innerkits/napi/eventhandler/include", + "header_files": [ + "events_emitter.h" + ] + }, + "name": "//foundation/appexecfwk/standard/interfaces/innerkits/napi/eventhandler:emitter" + }, { "header": { "header_base": "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include", "header_files": [ "form_callback_interface.h", "form_host_client.h", - "form_mgr.h" + "form_mgr.h" ] }, "name": "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit:fmskit_native" @@ -80,7 +89,8 @@ "//foundation/appexecfwk/standard/services:services_target", "//foundation/appexecfwk/standard/tools:tools_target", "//foundation/appexecfwk/standard/interfaces/innerkits:innerkits_target", - "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/appexecfwk/standard/kits:app_context", + "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/kits:appexec", "//foundation/appexecfwk/standard/sa_profile:appexecfwk_sa_profile", "//foundation/appexecfwk/standard/sa_profile:foundation.rc", diff --git a/sa_profile/BUILD.gn b/sa_profile/BUILD.gn index 180d06646b..d3728330ee 100644 --- a/sa_profile/BUILD.gn +++ b/sa_profile/BUILD.gn @@ -25,11 +25,7 @@ ohos_sa_profile("appexecfwk_sa_profile") { } ohos_prebuilt_etc("foundation.rc") { - if (use_musl) { - source = "foundation.cfg" - } else { - source = "foundation.rc" - } + source = "foundation.cfg" relative_install_dir = "init" subsystem_name = "appexecfwk" part_name = "appexecfwk_standard" diff --git a/services/appmgr/BUILD.gn b/services/appmgr/BUILD.gn index 9ede160529..11a050f29d 100644 --- a/services/appmgr/BUILD.gn +++ b/services/appmgr/BUILD.gn @@ -128,6 +128,7 @@ ohos_shared_library("libams") { "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "bytrace_standard:bytrace_core", ] subsystem_name = "appexecfwk" diff --git a/services/appmgr/examples/app_mgr_service_register_test/main_client.cpp b/services/appmgr/examples/app_mgr_service_register_test/main_client.cpp index 3b25dd2bf3..3837b6dcee 100644 --- a/services/appmgr/examples/app_mgr_service_register_test/main_client.cpp +++ b/services/appmgr/examples/app_mgr_service_register_test/main_client.cpp @@ -15,11 +15,11 @@ #include +#include "app_mgr_interface.h" #include "if_system_ability_manager.h" -#include "system_ability_definition.h" -#include "iservice_registry.h" #include "ipc_skeleton.h" -#include "app_mgr_interface.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" using namespace OHOS; using namespace OHOS::AppExecFwk; diff --git a/services/appmgr/include/app_mgr_service_inner.h b/services/appmgr/include/app_mgr_service_inner.h index 32ba7e6730..fde1113408 100644 --- a/services/appmgr/include/app_mgr_service_inner.h +++ b/services/appmgr/include/app_mgr_service_inner.h @@ -686,6 +686,16 @@ private: int32_t callerUid, pid_t callerPid, const int userId); private: + /** + * Notify application status. + * + * @param bundleName Indicates the name of the bundle. + * @param eventData Indicates the event defined by CommonEventSupport + * + * @return + */ + void NotifyAppStatus(const std::string &bundleName, const std::string &eventData); + std::vector> appStateCallbacks_; std::shared_ptr appProcessManager_; std::shared_ptr remoteClientManager_; diff --git a/services/appmgr/src/ams_mgr_scheduler.cpp b/services/appmgr/src/ams_mgr_scheduler.cpp index 692848b813..b8fdbd83af 100644 --- a/services/appmgr/src/ams_mgr_scheduler.cpp +++ b/services/appmgr/src/ams_mgr_scheduler.cpp @@ -60,7 +60,7 @@ void AmsMgrScheduler::LoadAbility(const sptr &token, const sptr loadAbilityFunc = + std::function loadAbilityFunc = std::bind(&AppMgrServiceInner::LoadAbility, amsMgrServiceInner_, token, preToken, abilityInfo, appInfo); amsHandler_->PostTask(loadAbilityFunc, TASK_LOAD_ABILITY); @@ -71,7 +71,7 @@ void AmsMgrScheduler::UpdateAbilityState(const sptr &token, const if (!IsReady()) { return; } - std::function updateAbilityStateFunc = + std::function updateAbilityStateFunc = std::bind(&AppMgrServiceInner::UpdateAbilityState, amsMgrServiceInner_, token, state); amsHandler_->PostTask(updateAbilityStateFunc, TASK_UPDATE_ABILITY_STATE); } @@ -81,7 +81,7 @@ void AmsMgrScheduler::TerminateAbility(const sptr &token) if (!IsReady()) { return; } - std::function terminateAbilityFunc = + std::function terminateAbilityFunc = std::bind(&AppMgrServiceInner::TerminateAbility, amsMgrServiceInner_, token); amsHandler_->PostTask(terminateAbilityFunc, TASK_TERMINATE_ABILITY); } @@ -91,7 +91,7 @@ void AmsMgrScheduler::RegisterAppStateCallback(const sptr &ca if (!IsReady()) { return; } - std::function registerAppStateCallbackFunc = + std::function registerAppStateCallbackFunc = std::bind(&AppMgrServiceInner::RegisterAppStateCallback, amsMgrServiceInner_, callback); amsHandler_->PostTask(registerAppStateCallbackFunc, TASK_REGISTER_APP_STATE_CALLBACK); } @@ -101,7 +101,7 @@ void AmsMgrScheduler::Reset() if (!IsReady()) { return; } - std::function resetFunc = std::bind(&AppMgrServiceInner::StopAllProcess, amsMgrServiceInner_); + std::function resetFunc = std::bind(&AppMgrServiceInner::StopAllProcess, amsMgrServiceInner_); amsHandler_->PostTask(resetFunc, TASK_STOP_ALL_PROCESS); } @@ -111,13 +111,9 @@ void AmsMgrScheduler::AbilityBehaviorAnalysis(const sptr &token, if (!IsReady()) { return; } - std::function abilityBehaviorAnalysisFunc = std::bind(&AppMgrServiceInner::AbilityBehaviorAnalysis, - amsMgrServiceInner_, - token, - preToken, - visibility, - perceptibility, - connectionState); + std::function abilityBehaviorAnalysisFunc = + std::bind(&AppMgrServiceInner::AbilityBehaviorAnalysis, amsMgrServiceInner_, token, preToken, visibility, + perceptibility, connectionState); amsHandler_->PostTask(abilityBehaviorAnalysisFunc, TASK_ABILITY_BEHAVIOR_ANALYSIS); } @@ -126,7 +122,7 @@ void AmsMgrScheduler::KillProcessByAbilityToken(const sptr &token if (!IsReady()) { return; } - std::function killProcessByAbilityTokenFunc = + std::function killProcessByAbilityTokenFunc = std::bind(&AppMgrServiceInner::KillProcessByAbilityToken, amsMgrServiceInner_, token); amsHandler_->PostTask(killProcessByAbilityTokenFunc, TASK_KILL_PROCESS_BY_ABILITYTOKEN); } diff --git a/services/appmgr/src/app_death_recipient.cpp b/services/appmgr/src/app_death_recipient.cpp index f094ad812e..9c841c0310 100644 --- a/services/appmgr/src/app_death_recipient.cpp +++ b/services/appmgr/src/app_death_recipient.cpp @@ -42,7 +42,7 @@ void AppDeathRecipient::OnRemoteDied(const wptr &remote) return; } - std::function onRemoteDiedFunc = std::bind(&AppMgrServiceInner::OnRemoteDied, serviceInner, remote); + std::function onRemoteDiedFunc = std::bind(&AppMgrServiceInner::OnRemoteDied, serviceInner, remote); handler->PostTask(onRemoteDiedFunc, TASK_ON_REMOTE_DIED); } diff --git a/services/appmgr/src/app_mgr_service.cpp b/services/appmgr/src/app_mgr_service.cpp index 298d68f937..faef254bf5 100644 --- a/services/appmgr/src/app_mgr_service.cpp +++ b/services/appmgr/src/app_mgr_service.cpp @@ -15,8 +15,8 @@ #include "app_mgr_service.h" -#include #include +#include #include "datetime_ex.h" #include "ipc_skeleton.h" @@ -31,9 +31,9 @@ namespace OHOS { namespace AppExecFwk { -static const int experienceMemThreshold = 20; -static const float percentage = 100.0; namespace { +static const int EXPERIENCE_MEM_THRESHOLD = 20; +static const float PERCENTAGE = 100.0; const std::string TASK_ATTACH_APPLICATION = "AttachApplicationTask"; const std::string TASK_APPLICATION_FOREGROUNDED = "ApplicationForegroundedTask"; const std::string TASK_APPLICATION_BACKGROUNDED = "ApplicationBackgroundedTask"; @@ -165,7 +165,7 @@ void AppMgrService::AttachApplication(const sptr &app) pid_t pid = IPCSkeleton::GetCallingPid(); AddAppDeathRecipient(pid); - std::function attachApplicationFunc = + std::function attachApplicationFunc = std::bind(&AppMgrServiceInner::AttachApplication, appMgrServiceInner_, pid, iface_cast(app)); handler_->PostTask(attachApplicationFunc, TASK_ATTACH_APPLICATION); } @@ -175,7 +175,7 @@ void AppMgrService::ApplicationForegrounded(const int32_t recordId) if (!IsReady()) { return; } - std::function applicationForegroundedFunc = + std::function applicationForegroundedFunc = std::bind(&AppMgrServiceInner::ApplicationForegrounded, appMgrServiceInner_, recordId); handler_->PostTask(applicationForegroundedFunc, TASK_APPLICATION_FOREGROUNDED); } @@ -185,7 +185,7 @@ void AppMgrService::ApplicationBackgrounded(const int32_t recordId) if (!IsReady()) { return; } - std::function applicationBackgroundedFunc = + std::function applicationBackgroundedFunc = std::bind(&AppMgrServiceInner::ApplicationBackgrounded, appMgrServiceInner_, recordId); handler_->PostTask(applicationBackgroundedFunc, TASK_APPLICATION_BACKGROUNDED); } @@ -195,7 +195,7 @@ void AppMgrService::ApplicationTerminated(const int32_t recordId) if (!IsReady()) { return; } - std::function applicationTerminatedFunc = + std::function applicationTerminatedFunc = std::bind(&AppMgrServiceInner::ApplicationTerminated, appMgrServiceInner_, recordId); handler_->PostTask(applicationTerminatedFunc, TASK_APPLICATION_TERMINATED); } @@ -205,7 +205,7 @@ void AppMgrService::AbilityCleaned(const sptr &token) if (!IsReady()) { return; } - std::function abilityCleanedFunc = + std::function abilityCleanedFunc = std::bind(&AppMgrServiceInner::AbilityTerminated, appMgrServiceInner_, token); handler_->PostTask(abilityCleanedFunc, TASK_ABILITY_CLEANED); } @@ -231,7 +231,7 @@ void AppMgrService::AddAppDeathRecipient(const pid_t pid) const sptr appDeathRecipient = new AppDeathRecipient(); appDeathRecipient->SetEventHandler(handler_); appDeathRecipient->SetAppMgrServiceInner(appMgrServiceInner_); - std::function addAppRecipientFunc = + std::function addAppRecipientFunc = std::bind(&AppMgrServiceInner::AddAppDeathRecipient, appMgrServiceInner_, pid, appDeathRecipient); handler_->PostTask(addAppRecipientFunc, TASK_ADD_APP_DEATH_RECIPIENT); } @@ -259,7 +259,7 @@ int32_t AppMgrService::ClearUpApplicationData(const std::string &bundleName) } int32_t uid = IPCSkeleton::GetCallingUid(); pid_t pid = IPCSkeleton::GetCallingPid(); - std::function clearUpApplicationDataFunc = + std::function clearUpApplicationDataFunc = std::bind(&AppMgrServiceInner::ClearUpApplicationData, appMgrServiceInner_, bundleName, uid, pid); handler_->PostTask(clearUpApplicationDataFunc, TASK_CLEAR_UP_APPLICATION_DATA); return ERR_OK; @@ -314,8 +314,8 @@ void AppMgrService::GetSystemMemoryAttr(SystemMemoryAttr &memoryInfo, std::strin APP_LOGE("%{public}s, discarded memThreshold = %{public}d", __func__, experienceMemThreshold); } else { if (!memJson.contains("memoryThreshold")) { - memThreshold = experienceMemThreshold; - APP_LOGE("%{public}s, memThreshold = %{public}d", __func__, experienceMemThreshold); + memThreshold = EXPERIENCE_MEM_THRESHOLD; + APP_LOGE("%{public}s, memThreshold = %{public}d", __func__, EXPERIENCE_MEM_THRESHOLD); } else { memThreshold = memJson.at("memorythreshold").get(); APP_LOGI("%{public}s, memThreshold = %{public}d", __func__, memThreshold); @@ -324,7 +324,7 @@ void AppMgrService::GetSystemMemoryAttr(SystemMemoryAttr &memoryInfo, std::strin memoryInfo.availSysMem_ = systemMemInfo.GetMemFree(); memoryInfo.totalSysMem_ = systemMemInfo.GetMemTotal(); - memoryInfo.threshold_ = static_cast(memoryInfo.totalSysMem_ * memThreshold / percentage); + memoryInfo.threshold_ = static_cast(memoryInfo.totalSysMem_ * memThreshold / PERCENTAGE); memoryInfo.isSysInlowMem_ = memoryInfo.availSysMem_ < memoryInfo.threshold_; } diff --git a/services/appmgr/src/app_mgr_service_inner.cpp b/services/appmgr/src/app_mgr_service_inner.cpp index 01d7f4d54e..a4301bc1d8 100644 --- a/services/appmgr/src/app_mgr_service_inner.cpp +++ b/services/appmgr/src/app_mgr_service_inner.cpp @@ -15,21 +15,24 @@ #include "app_mgr_service_inner.h" -#include -#include #include +#include +#include #include "app_log_wrapper.h" -#include "perf_profile.h" #include "datetime_ex.h" +#include "perf_profile.h" -#include "iservice_registry.h" -#include "system_ability_definition.h" -#include "iremote_object.h" -#include "common_event.h" -#include "bundle_constants.h" #include "app_process_data.h" +#include "bundle_constants.h" +#include "bytrace.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "iremote_object.h" +#include "iservice_registry.h" #include "permission/permission_kit.h" +#include "system_ability_definition.h" namespace OHOS { namespace AppExecFwk { @@ -69,6 +72,7 @@ AppMgrServiceInner::~AppMgrServiceInner() void AppMgrServiceInner::LoadAbility(const sptr &token, const sptr &preToken, const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo) { + BYTRACE(BYTRACE_TAG_APP); if (!token || !abilityInfo || !appInfo) { APP_LOGE("param error"); return; @@ -114,6 +118,7 @@ void AppMgrServiceInner::LoadAbility(const sptr &token, const spt void AppMgrServiceInner::AttachApplication(const pid_t pid, const sptr &app) { + BYTRACE(BYTRACE_TAG_APP); if (pid <= 0) { APP_LOGE("invalid pid:%{public}d", pid); return; @@ -171,6 +176,7 @@ void AppMgrServiceInner::AddAbilityStageDone(const int32_t recordId) void AppMgrServiceInner::ApplicationForegrounded(const int32_t recordId) { + BYTRACE(BYTRACE_TAG_APP); auto appRecord = GetAppRunningRecordByAppRecordId(recordId); if (!appRecord) { APP_LOGE("get app record failed"); @@ -198,6 +204,7 @@ void AppMgrServiceInner::ApplicationForegrounded(const int32_t recordId) void AppMgrServiceInner::ApplicationBackgrounded(const int32_t recordId) { + BYTRACE(BYTRACE_TAG_APP); auto appRecord = GetAppRunningRecordByAppRecordId(recordId); if (!appRecord) { APP_LOGE("get app record failed"); @@ -221,12 +228,12 @@ void AppMgrServiceInner::ApplicationBackgrounded(const int32_t recordId) void AppMgrServiceInner::ApplicationTerminated(const int32_t recordId) { + BYTRACE(BYTRACE_TAG_APP); auto appRecord = GetAppRunningRecordByAppRecordId(recordId); if (!appRecord) { APP_LOGE("get app record failed"); return; } - if (appRecord->GetState() != ApplicationState::APP_STATE_BACKGROUND) { APP_LOGE("current state is not background"); return; @@ -257,13 +264,13 @@ int32_t AppMgrServiceInner::KillApplication(const std::string &bundleName) int result = ERR_OK; int64_t startTime = SystemTimeMillis(); std::list pids; - if (!appRunningManager_->GetPidsByBundleName(bundleName, pids)) { APP_LOGI("The process corresponding to the package name did not start"); return result; } if (WaitForRemoteProcessExit(pids, startTime)) { APP_LOGI("The remote process exited successfully "); + NotifyAppStatus(bundleName, EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED); return result; } for (auto iter = pids.begin(); iter != pids.end(); ++iter) { @@ -273,6 +280,7 @@ int32_t AppMgrServiceInner::KillApplication(const std::string &bundleName) return result; } } + NotifyAppStatus(bundleName, EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED); return result; } @@ -354,6 +362,7 @@ int32_t AppMgrServiceInner::KillApplicationByUserId(const std::string &bundleNam void AppMgrServiceInner::ClearUpApplicationData(const std::string &bundleName, int32_t callerUid, pid_t callerPid) { + BYTRACE(BYTRACE_TAG_APP); ClearUpApplicationDataByUserId(bundleName, callerUid, callerPid, Constants::DEFAULT_USERID); } @@ -373,26 +382,29 @@ void AppMgrServiceInner::ClearUpApplicationDataByUserId(const std::string &bundl APP_LOGE("GetBundleManager fail"); return; } - int32_t clearUid = bundleMgr_->GetUidByBundleName(bundleName, userId); + + int32_t clearUid = bundleMgr_->GetUidByBundleName(bundleName, 0); if (bundleMgr_->CheckIsSystemAppByUid(callerUid) || callerUid == clearUid) { // request to clear user information permission. - int32_t result = Permission::PermissionKit::RemoveUserGrantedReqPermissions(bundleName, userId); + int32_t result = + Permission::PermissionKit::RemoveUserGrantedReqPermissions(bundleName, Constants::DEFAULT_USERID); if (result) { APP_LOGE("RemoveUserGrantedReqPermissions failed"); return; } // 2.delete bundle side user data - if (!bundleMgr_->CleanBundleDataFiles(bundleName, userId)) { + if (!bundleMgr_->CleanBundleDataFiles(bundleName)) { APP_LOGE("Delete bundle side user data is fail"); return; } // 3.kill application // 4.revoke user rights - result = KillApplicationByUserId(bundleName, userId); + result = KillApplication(bundleName); if (result < 0) { APP_LOGE("Kill Application by bundle name is fail"); return; } + NotifyAppStatus(bundleName, EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED); } } @@ -523,6 +535,7 @@ std::shared_ptr AppMgrServiceInner::GetOrCreateAppRunningRecor const std::shared_ptr &appInfo, const std::shared_ptr &abilityInfo, const std::string &processName, const int32_t uid, RecordQueryResult &result) { + BYTRACE(BYTRACE_TAG_APP); return appRunningManager_->GetOrCreateAppRunningRecord(token, appInfo, abilityInfo, processName, uid, result); } @@ -534,6 +547,7 @@ std::shared_ptr AppMgrServiceInner::GetOrCreateAppRunningRecor void AppMgrServiceInner::TerminateAbility(const sptr &token) { + BYTRACE(BYTRACE_TAG_APP); APP_LOGD("AppMgrServiceInner::TerminateAbility begin"); if (!token) { APP_LOGE("AppMgrServiceInner::TerminateAbility token is null!"); @@ -557,6 +571,7 @@ void AppMgrServiceInner::TerminateAbility(const sptr &token) void AppMgrServiceInner::UpdateAbilityState(const sptr &token, const AbilityState state) { + BYTRACE(BYTRACE_TAG_APP); if (!token) { APP_LOGE("token is null!"); return; @@ -634,6 +649,7 @@ void AppMgrServiceInner::SetBundleManager(sptr bundleManager) void AppMgrServiceInner::RegisterAppStateCallback(const sptr &callback) { + BYTRACE(BYTRACE_TAG_APP); if (callback != nullptr) { appStateCallbacks_.push_back(callback); } @@ -641,6 +657,7 @@ void AppMgrServiceInner::RegisterAppStateCallback(const sptr void AppMgrServiceInner::StopAllProcess() { + BYTRACE(BYTRACE_TAG_APP); ClearRecentAppList(); appRunningManager_->ClearAppRunningRecordMap(); } @@ -650,6 +667,7 @@ void AppMgrServiceInner::AbilityBehaviorAnalysis(const sptr &toke const int32_t perceptibility, // 0:false,1:true const int32_t connectionState) // 0:false,1:true { + BYTRACE(BYTRACE_TAG_APP); if (!token) { APP_LOGE("token is null"); return; @@ -685,6 +703,7 @@ void AppMgrServiceInner::AbilityBehaviorAnalysis(const sptr &toke void AppMgrServiceInner::KillProcessByAbilityToken(const sptr &token) { + BYTRACE(BYTRACE_TAG_APP); if (!token) { APP_LOGE("token is null"); return; @@ -694,7 +713,6 @@ void AppMgrServiceInner::KillProcessByAbilityToken(const sptr &to APP_LOGE("app record is not exist for ability token"); return; } - std::list pids; pid_t pid = appRecord->GetPriorityObject()->GetPid(); if (pid > 0) { @@ -713,6 +731,7 @@ void AppMgrServiceInner::KillProcessByAbilityToken(const sptr &to void AppMgrServiceInner::StartAbility(const sptr &token, const sptr &preToken, const std::shared_ptr &abilityInfo, const std::shared_ptr &appRecord) { + BYTRACE(BYTRACE_TAG_APP); APP_LOGI("already create appRecord, just start ability"); if (!appRecord) { APP_LOGE("appRecord is null"); @@ -844,6 +863,7 @@ std::shared_ptr AppMgrServiceInner::GetAbilityRunningRecor void AppMgrServiceInner::AbilityTerminated(const sptr &token) { + BYTRACE(BYTRACE_TAG_APP); APP_LOGD("begin"); if (!token) { APP_LOGE("token is null!"); @@ -911,6 +931,7 @@ void AppMgrServiceInner::OnAbilityStateChanged( void AppMgrServiceInner::StartProcess(const std::string &appName, const std::string &processName, const std::shared_ptr &appRecord, const int uid) { + BYTRACE(BYTRACE_TAG_APP); if (!remoteClientManager_->GetSpawnClient() || !appRecord) { APP_LOGE("appSpawnClient or apprecord is null"); return; @@ -982,7 +1003,6 @@ void AppMgrServiceInner::RemoveAppFromRecentList(const std::string &appName, con appProcessManager_->RemoveAppFromRecentList(appTaskInfo); return; } - startTime = SystemTimeMillis(); pids.push_back(appTaskInfo->GetPid()); appRecord->ScheduleProcessSecurityExit(); @@ -1008,7 +1028,6 @@ void AppMgrServiceInner::ClearRecentAppList() if (GetAllPids(pids)) { return; } - startTime = SystemTimeMillis(); if (WaitForRemoteProcessExit(pids, startTime)) { appProcessManager_->ClearRecentAppList(); @@ -1074,6 +1093,7 @@ const std::shared_ptr AppMgrServiceInner::GetAppTaskInfoById(const void AppMgrServiceInner::AddAppDeathRecipient(const pid_t pid, const sptr &appDeathRecipient) const { + BYTRACE(BYTRACE_TAG_APP); std::shared_ptr appRecord = GetAppRunningRecordByPid(pid); if (appRecord) { appRecord->SetAppDeathRecipient(appDeathRecipient); @@ -1228,6 +1248,7 @@ void AppMgrServiceInner::SetEventHandler(const std::shared_ptr void AppMgrServiceInner::HandleAbilityAttachTimeOut(const sptr &token) { + BYTRACE(BYTRACE_TAG_APP); APP_LOGI("%{public}s called", __func__); if (!appRunningManager_) { APP_LOGE("appRunningManager_ is nullptr"); @@ -1444,5 +1465,19 @@ void AppMgrServiceInner::RestartResidentProcess(std::shared_ptr #include "app_log_wrapper.h" diff --git a/services/appmgr/src/app_running_manager.cpp b/services/appmgr/src/app_running_manager.cpp index 47f8f7f577..d9e54d84de 100644 --- a/services/appmgr/src/app_running_manager.cpp +++ b/services/appmgr/src/app_running_manager.cpp @@ -15,12 +15,12 @@ #include "app_running_manager.h" -#include "iremote_object.h" #include "datetime_ex.h" +#include "iremote_object.h" #include "app_log_wrapper.h" -#include "perf_profile.h" #include "appexecfwk_errors.h" +#include "perf_profile.h" namespace OHOS { namespace AppExecFwk { diff --git a/services/appmgr/src/app_running_record.cpp b/services/appmgr/src/app_running_record.cpp index 064858b76f..ca71bfabe0 100644 --- a/services/appmgr/src/app_running_record.cpp +++ b/services/appmgr/src/app_running_record.cpp @@ -18,6 +18,7 @@ #include "ability_running_record.h" #include "app_log_wrapper.h" #include "app_mgr_service_inner.h" +#include "bytrace.h" namespace OHOS { namespace AppExecFwk { @@ -173,7 +174,6 @@ void AppRunningRecord::LaunchApplication() launchData.SetProcessInfo(processInfo); launchData.SetRecordId(appRecordId_); launchData.SetUId(uid_); - APP_LOGI("ScheduleLaunchApplication app:%{public}s", GetName().c_str()); appLifeCycleDeal_->LaunchApplication(launchData); } @@ -318,6 +318,7 @@ void AppRunningRecord::UpdateAbilityState(const sptr &token, cons void AppRunningRecord::AbilityForeground(const std::shared_ptr &ability) { + BYTRACE(BYTRACE_TAG_APP); if (!ability) { APP_LOGE("ability is null"); return; @@ -350,6 +351,7 @@ void AppRunningRecord::AbilityForeground(const std::shared_ptr &ability) { + BYTRACE(BYTRACE_TAG_APP); if (!ability) { APP_LOGE("ability is null"); return; diff --git a/services/appmgr/src/cgroup_manager.cpp b/services/appmgr/src/cgroup_manager.cpp index c2da797b26..7371ed9565 100644 --- a/services/appmgr/src/cgroup_manager.cpp +++ b/services/appmgr/src/cgroup_manager.cpp @@ -15,8 +15,8 @@ #include "cgroup_manager.h" #include #include -#include #include +#include #include #include #include diff --git a/services/appmgr/src/kernal_system_memory_Info.h b/services/appmgr/src/kernel_system_memory_info.h similarity index 66% rename from services/appmgr/src/kernal_system_memory_Info.h rename to services/appmgr/src/kernel_system_memory_info.h index a770a7357a..066742242b 100644 --- a/services/appmgr/src/kernal_system_memory_Info.h +++ b/services/appmgr/src/kernel_system_memory_info.h @@ -12,33 +12,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef FOUNDATION_APPEXECFWK_SERVICES_KERNAL_SYSTEM_MEMORY_INFO_H -#define FOUNDATION_APPEXECFWK_SERVICES_KERNAL_SYSTEM_MEMORY_INFO_H +#ifndef FOUNDATION_APPEXECFWK_SERVICES_KERNEL_SYSTEM_MEMORY_INFO_H +#define FOUNDATION_APPEXECFWK_SERVICES_KERNEL_SYSTEM_MEMORY_INFO_H #include namespace OHOS { namespace AppExecFwk { namespace SystemEnv { -class kernal_system_memory_Info { -public: - kernal_system_memory_Info() = default; - ~kernal_system_memory_Info() = default; -}; - class KernelSystemMemoryInfo { public: KernelSystemMemoryInfo() = default; ~KernelSystemMemoryInfo() = default; - void init(std::map &memInfo); + void Init(std::map &memInfo); - int64_t GetMemTotal(); - int64_t GetMemFree(); - int64_t GetMemAvailable(); - int64_t GetBuffers(); - int64_t GetCached(); - int64_t GetSwapCached(); + int64_t GetMemTotal() const; + int64_t GetMemFree() const; + int64_t GetMemAvailable() const; + int64_t GetBuffers() const; + int64_t GetCached() const; + int64_t GetSwapCached() const; private: int64_t memTotal_ = 0; @@ -51,4 +45,4 @@ private: } // namespace SystemEnv } // namespace AppExecFwk } // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_SERVICES_KERNAL_SYSTEM_MEMORY_INFO_H \ No newline at end of file +#endif // FOUNDATION_APPEXECFWK_SERVICES_KERNEL_SYSTEM_MEMORY_INFO_H \ No newline at end of file diff --git a/services/appmgr/src/lmks/lmks_server.cpp b/services/appmgr/src/lmks/lmks_server.cpp index 302b41ed33..3a657f58d2 100644 --- a/services/appmgr/src/lmks/lmks_server.cpp +++ b/services/appmgr/src/lmks/lmks_server.cpp @@ -16,13 +16,13 @@ #include "lmks_server.h" #include -#include #include +#include #include #include -#include "securec.h" #include "hilog/log.h" +#include "securec.h" namespace OHOS { namespace LMKS { diff --git a/services/appmgr/src/lmks/lmks_utils.cpp b/services/appmgr/src/lmks/lmks_utils.cpp index f275a2af5b..8a1833a30f 100644 --- a/services/appmgr/src/lmks/lmks_utils.cpp +++ b/services/appmgr/src/lmks/lmks_utils.cpp @@ -16,12 +16,12 @@ #include "lmks_utils.h" #include -#include #include +#include #include -#include "securec.h" #include "hilog/log.h" +#include "securec.h" namespace OHOS { namespace LMKS { diff --git a/services/appmgr/src/process_optimizer.cpp b/services/appmgr/src/process_optimizer.cpp index 2a1c17c78e..2c58d77987 100644 --- a/services/appmgr/src/process_optimizer.cpp +++ b/services/appmgr/src/process_optimizer.cpp @@ -69,7 +69,7 @@ constexpr int LMKS_OOM_ADJ_LOW = 800; constexpr int LMKS_OOM_ADJ_MEDIUM = 600; // pressure level critical constexpr int LMKS_OOM_ADJ_CRITICAL = 0; -constexpr int MemoryLevel[] = {LMKS_OOM_ADJ_LOW, LMKS_OOM_ADJ_MEDIUM, LMKS_OOM_ADJ_CRITICAL}; +constexpr int G_MEMORY_LEVEL[] = {LMKS_OOM_ADJ_LOW, LMKS_OOM_ADJ_MEDIUM, LMKS_OOM_ADJ_CRITICAL}; } // namespace ProcessOptimizer::ProcessOptimizer(const LmksClientPtr &lmksClient, int suspendTimeout) @@ -441,7 +441,7 @@ void ProcessOptimizer::OnLowMemoryAlert(const CgroupManager::LowMemoryLevel leve std::list::iterator iter = appLru_.begin(); while (iter != appLru_.end()) { auto priorityObject = (*iter)->GetPriorityObject(); - if (priorityObject != nullptr && priorityObject->GetCurAdj() >= MemoryLevel[level]) { + if (priorityObject != nullptr && priorityObject->GetCurAdj() >= G_MEMORY_LEVEL[level]) { auto pid = priorityObject->GetPid(); if (pid <= 0) { APP_LOGE("pid %{public}d invalid", pid); diff --git a/services/appmgr/src/start_via_asan.cpp b/services/appmgr/src/start_via_asan.cpp index 5eb2d1d292..eaef73e15c 100644 --- a/services/appmgr/src/start_via_asan.cpp +++ b/services/appmgr/src/start_via_asan.cpp @@ -14,8 +14,9 @@ */ #include "start_via_asan.h" -#include "properties.h" + #include "app_log_wrapper.h" +#include "properties.h" namespace OHOS { namespace AppExecFwk { diff --git a/services/appmgr/src/system_environment_information.cpp b/services/appmgr/src/system_environment_information.cpp index d70125ece1..a44d03e73c 100644 --- a/services/appmgr/src/system_environment_information.cpp +++ b/services/appmgr/src/system_environment_information.cpp @@ -12,24 +12,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include "system_environment_information.h" + #include #include #include -#include +#include #include #include -#include +#include #include "app_log_wrapper.h" +#include "kernel_system_memory_info.h" #include "securec.h" -#include "kernal_system_memory_Info.h" -#include "system_environment_information.h" namespace OHOS { namespace AppExecFwk { namespace SystemEnv { -const int bytesKB = 1024; -void KernelSystemMemoryInfo::init(std::map &memInfo) +namespace { +static const int BYTES_KB = 1024; +} +void KernelSystemMemoryInfo::Init(std::map &memInfo) { auto findData = [&] (const std::string& key) -> std::string { auto iter = memInfo.find(key); @@ -42,40 +45,40 @@ void KernelSystemMemoryInfo::init(std::map &memInfo) } }; - memTotal_ = std::stoll(findData(std::string("MemTotal"))) * bytesKB; - memFree_ = std::stoll(findData(std::string("MemFree"))) * bytesKB; - memAvailable_ = std::stoll(findData(std::string("MemAvailable"))) * bytesKB; - buffers_ = std::stoll(findData(std::string("Buffers"))) * bytesKB; - cached_ = std::stoll(findData(std::string("Cached"))) * bytesKB; - swapCached_ = std::stoll(findData(std::string("SwapCached"))) * bytesKB; + memTotal_ = std::stoll(findData(std::string("MemTotal"))) * BYTES_KB; + memFree_ = std::stoll(findData(std::string("MemFree"))) * BYTES_KB; + memAvailable_ = std::stoll(findData(std::string("MemAvailable"))) * BYTES_KB; + buffers_ = std::stoll(findData(std::string("Buffers"))) * BYTES_KB; + cached_ = std::stoll(findData(std::string("Cached"))) * BYTES_KB; + swapCached_ = std::stoll(findData(std::string("SwapCached"))) * BYTES_KB; } -int64_t KernelSystemMemoryInfo::GetMemTotal() +int64_t KernelSystemMemoryInfo::GetMemTotal() const { return memTotal_; } -int64_t KernelSystemMemoryInfo::GetMemFree() +int64_t KernelSystemMemoryInfo::GetMemFree() const { return memFree_; } -int64_t KernelSystemMemoryInfo::GetMemAvailable() +int64_t KernelSystemMemoryInfo::GetMemAvailable() const { return memAvailable_; } -int64_t KernelSystemMemoryInfo::GetBuffers() +int64_t KernelSystemMemoryInfo::GetBuffers() const { return buffers_; } -int64_t KernelSystemMemoryInfo::GetCached() +int64_t KernelSystemMemoryInfo::GetCached() const { return cached_; } -int64_t KernelSystemMemoryInfo::GetSwapCached() +int64_t KernelSystemMemoryInfo::GetSwapCached() const { return swapCached_; } @@ -123,7 +126,7 @@ void GetMemInfo(KernelSystemMemoryInfo &memInfo) { std::map memListInfo; RequestSystemMemoryInfo(memListInfo); - memInfo.init(memListInfo); + memInfo.Init(memListInfo); } } // namespace SystemEnv } // namespace AppExecFwk diff --git a/services/appmgr/src/system_environment_information.h b/services/appmgr/src/system_environment_information.h index e82cb85335..81130d2fa8 100644 --- a/services/appmgr/src/system_environment_information.h +++ b/services/appmgr/src/system_environment_information.h @@ -15,7 +15,7 @@ #ifndef FOUNDATION_APPEXECFWK_SERVICES_SYSTEM_ENVIRONMENT_INFORMATION_H #define FOUNDATION_APPEXECFWK_SERVICES_SYSTEM_ENVIRONMENT_INFORMATION_H -#include "kernal_system_memory_Info.h" +#include "kernel_system_memory_info.h" namespace OHOS { namespace AppExecFwk { diff --git a/services/appmgr/test/BUILD.gn b/services/appmgr/test/BUILD.gn index c0c87131a8..54f4f78349 100644 --- a/services/appmgr/test/BUILD.gn +++ b/services/appmgr/test/BUILD.gn @@ -87,8 +87,10 @@ ohos_source_set("appmgr_test_source") { external_deps = [ "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "bytrace_standard:bytrace_core", ] } diff --git a/services/appmgr/test/mock/src/sys_mgr_client_mock.cpp b/services/appmgr/test/mock/src/sys_mgr_client_mock.cpp index ebd54c033c..e9fb2e2d83 100644 --- a/services/appmgr/test/mock/src/sys_mgr_client_mock.cpp +++ b/services/appmgr/test/mock/src/sys_mgr_client_mock.cpp @@ -16,8 +16,8 @@ #include "sys_mgr_client.h" #include "hilog_wrapper.h" #include "if_system_ability_manager.h" -#include "iservice_registry.h" #include "ipc_skeleton.h" +#include "iservice_registry.h" #include "string_ex.h" namespace OHOS { diff --git a/services/appmgr/test/unittest/ams_ability_running_record_test/BUILD.gn b/services/appmgr/test/unittest/ams_ability_running_record_test/BUILD.gn index da2df9194e..299b3961bd 100644 --- a/services/appmgr/test/unittest/ams_ability_running_record_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_ability_running_record_test/BUILD.gn @@ -59,6 +59,7 @@ ohos_unittest("AmsAbilityRunningRecordTest") { external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "bytrace_standard:bytrace_core", ] } diff --git a/services/appmgr/test/unittest/ams_app_death_recipient_test/BUILD.gn b/services/appmgr/test/unittest/ams_app_death_recipient_test/BUILD.gn index dd3ed982c8..cab3aee944 100644 --- a/services/appmgr/test/unittest/ams_app_death_recipient_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_app_death_recipient_test/BUILD.gn @@ -65,6 +65,7 @@ ohos_unittest("AppDeathRecipientTest") { external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "bytrace_standard:bytrace_core", ] } diff --git a/services/appmgr/test/unittest/ams_app_life_cycle_test/BUILD.gn b/services/appmgr/test/unittest/ams_app_life_cycle_test/BUILD.gn index 5111f1f3a6..7d1f9e6128 100644 --- a/services/appmgr/test/unittest/ams_app_life_cycle_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_app_life_cycle_test/BUILD.gn @@ -65,6 +65,7 @@ ohos_unittest("AmsAppLifeCycleTest") { external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "bytrace_standard:bytrace_core", ] } diff --git a/services/appmgr/test/unittest/ams_app_mgr_client_test/ams_app_mgr_client_test.cpp b/services/appmgr/test/unittest/ams_app_mgr_client_test/ams_app_mgr_client_test.cpp index abef7acf66..048ec60c74 100644 --- a/services/appmgr/test/unittest/ams_app_mgr_client_test/ams_app_mgr_client_test.cpp +++ b/services/appmgr/test/unittest/ams_app_mgr_client_test/ams_app_mgr_client_test.cpp @@ -21,12 +21,12 @@ #include "application_info.h" #include "app_log_wrapper.h" #include "iapp_state_callback.h" -#include "running_process_info.h" #include "mock_ability_token.h" +#include "mock_ams_mgr_scheduler.h" #include "mock_app_mgr_service.h" #include "mock_app_service_mgr.h" #include "mock_iapp_state_callback.h" -#include "mock_ams_mgr_scheduler.h" +#include "running_process_info.h" using namespace testing::ext; using testing::_; diff --git a/services/appmgr/test/unittest/ams_app_running_record_test/BUILD.gn b/services/appmgr/test/unittest/ams_app_running_record_test/BUILD.gn index bd3c29f75c..4a669fff48 100644 --- a/services/appmgr/test/unittest/ams_app_running_record_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_app_running_record_test/BUILD.gn @@ -57,6 +57,7 @@ ohos_unittest("AmsAppRunningRecordTest") { external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "bytrace_standard:bytrace_core", ] } diff --git a/services/appmgr/test/unittest/ams_app_state_callback_test/BUILD.gn b/services/appmgr/test/unittest/ams_app_state_callback_test/BUILD.gn index 08f9f08864..6880a77223 100644 --- a/services/appmgr/test/unittest/ams_app_state_callback_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_app_state_callback_test/BUILD.gn @@ -44,6 +44,7 @@ ohos_unittest("AmsAppStateCallbackTest") { external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "bytrace_standard:bytrace_core", ] } diff --git a/services/appmgr/test/unittest/ams_app_workflow_test/BUILD.gn b/services/appmgr/test/unittest/ams_app_workflow_test/BUILD.gn index 3808998370..6e29e6315b 100644 --- a/services/appmgr/test/unittest/ams_app_workflow_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_app_workflow_test/BUILD.gn @@ -62,6 +62,7 @@ ohos_unittest("AmsWorkFlowTest") { external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "bytrace_standard:bytrace_core", ] } diff --git a/services/appmgr/test/unittest/ams_app_workflow_test/ams_workflow_test.cpp b/services/appmgr/test/unittest/ams_app_workflow_test/ams_workflow_test.cpp index a762bde383..59c412fbdd 100644 --- a/services/appmgr/test/unittest/ams_app_workflow_test/ams_workflow_test.cpp +++ b/services/appmgr/test/unittest/ams_app_workflow_test/ams_workflow_test.cpp @@ -14,15 +14,15 @@ */ #include "app_mgr_service_inner.h" -#include -#include -#include "iremote_object.h" -#include "refbase.h" #include "app_launch_data.h" #include "app_log_wrapper.h" +#include +#include "iremote_object.h" #include "mock_ability_token.h" #include "mock_app_scheduler.h" #include "mock_app_spawn_client.h" +#include "refbase.h" +#include using namespace testing::ext; using testing::_; diff --git a/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp b/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp index 6adf18372c..5eaa9039a7 100644 --- a/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp +++ b/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp @@ -20,9 +20,9 @@ #undef private #include "app_log_wrapper.h" -#include "mock_app_mgr_service_inner.h" -#include "mock_ability_token.h" #include "app_state_callback_host.h" +#include "mock_ability_token.h" +#include "mock_app_mgr_service_inner.h" using namespace testing; using namespace testing::ext; diff --git a/services/appmgr/test/unittest/ams_recent_app_list_test/BUILD.gn b/services/appmgr/test/unittest/ams_recent_app_list_test/BUILD.gn index a84b7c49d6..d04d5f5dd1 100644 --- a/services/appmgr/test/unittest/ams_recent_app_list_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_recent_app_list_test/BUILD.gn @@ -63,6 +63,7 @@ ohos_unittest("AmsRecentAppListTest") { external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "bytrace_standard:bytrace_core", ] } diff --git a/services/appmgr/test/unittest/ams_service_app_spawn_client_test/BUILD.gn b/services/appmgr/test/unittest/ams_service_app_spawn_client_test/BUILD.gn index bc0b303ff9..0d60f14017 100644 --- a/services/appmgr/test/unittest/ams_service_app_spawn_client_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_service_app_spawn_client_test/BUILD.gn @@ -61,6 +61,7 @@ ohos_unittest("AmsServiceAppSpawnClientTest") { external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "bytrace_standard:bytrace_core", ] } diff --git a/services/appmgr/test/unittest/ams_service_app_spawn_msg_wrapper_test/ams_service_app_spawn_msg_wrapper_test.cpp b/services/appmgr/test/unittest/ams_service_app_spawn_msg_wrapper_test/ams_service_app_spawn_msg_wrapper_test.cpp index fd2da02ec8..b331180f84 100644 --- a/services/appmgr/test/unittest/ams_service_app_spawn_msg_wrapper_test/ams_service_app_spawn_msg_wrapper_test.cpp +++ b/services/appmgr/test/unittest/ams_service_app_spawn_msg_wrapper_test/ams_service_app_spawn_msg_wrapper_test.cpp @@ -15,9 +15,9 @@ #include -#include "securec.h" #include "app_log_wrapper.h" #include "app_spawn_msg_wrapper.h" +#include "securec.h" using namespace testing::ext; diff --git a/services/appmgr/test/unittest/ams_service_app_spawn_socket_test/ams_service_app_spawn_socket_test.cpp b/services/appmgr/test/unittest/ams_service_app_spawn_socket_test/ams_service_app_spawn_socket_test.cpp index 9f57ecfe63..4b7f75bc09 100644 --- a/services/appmgr/test/unittest/ams_service_app_spawn_socket_test/ams_service_app_spawn_socket_test.cpp +++ b/services/appmgr/test/unittest/ams_service_app_spawn_socket_test/ams_service_app_spawn_socket_test.cpp @@ -13,11 +13,12 @@ * limitations under the License. */ -#include "app_spawn_socket.h" #include -#include "securec.h" + #include "app_log_wrapper.h" +#include "app_spawn_socket.h" #include "mock_client_socket.h" +#include "securec.h" using namespace testing::ext; using namespace OHOS; diff --git a/services/appmgr/test/unittest/ams_service_event_drive_test/BUILD.gn b/services/appmgr/test/unittest/ams_service_event_drive_test/BUILD.gn index 4377b7b574..a650a74a48 100644 --- a/services/appmgr/test/unittest/ams_service_event_drive_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_service_event_drive_test/BUILD.gn @@ -63,6 +63,7 @@ ohos_unittest("AmsServiceEventDriveTest") { external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "bytrace_standard:bytrace_core", ] } diff --git a/services/appmgr/test/unittest/ams_service_event_drive_test/ams_service_event_drive_test.cpp b/services/appmgr/test/unittest/ams_service_event_drive_test/ams_service_event_drive_test.cpp index 24eef1ecd8..dd5532c6ca 100644 --- a/services/appmgr/test/unittest/ams_service_event_drive_test/ams_service_event_drive_test.cpp +++ b/services/appmgr/test/unittest/ams_service_event_drive_test/ams_service_event_drive_test.cpp @@ -20,10 +20,9 @@ #undef private #undef protected #include -#include #include "app_log_wrapper.h" -#include "iremote_object.h" #include "errors.h" +#include "iremote_object.h" #include "mock_app_mgr_service_inner.h" #include"system_environment_information.h" #include "system_memory_attr.h" diff --git a/services/appmgr/test/unittest/ams_service_load_ability_process_test/BUILD.gn b/services/appmgr/test/unittest/ams_service_load_ability_process_test/BUILD.gn index 5b8129733d..793d54be3a 100644 --- a/services/appmgr/test/unittest/ams_service_load_ability_process_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_service_load_ability_process_test/BUILD.gn @@ -65,6 +65,7 @@ ohos_unittest("AmsServiceLoadAbilityProcessTest") { external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "bytrace_standard:bytrace_core", ] } diff --git a/services/appmgr/test/unittest/ams_service_startup_test/BUILD.gn b/services/appmgr/test/unittest/ams_service_startup_test/BUILD.gn index 406be582db..c5701402b8 100644 --- a/services/appmgr/test/unittest/ams_service_startup_test/BUILD.gn +++ b/services/appmgr/test/unittest/ams_service_startup_test/BUILD.gn @@ -60,6 +60,7 @@ ohos_unittest("AmsServiceStartupTest") { external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "bytrace_standard:bytrace_core", ] } diff --git a/services/appmgr/test/unittest/app_mgr_service_event_handler_test/BUILD.gn b/services/appmgr/test/unittest/app_mgr_service_event_handler_test/BUILD.gn index ddd5a98eea..30b04f0c9c 100644 --- a/services/appmgr/test/unittest/app_mgr_service_event_handler_test/BUILD.gn +++ b/services/appmgr/test/unittest/app_mgr_service_event_handler_test/BUILD.gn @@ -65,6 +65,7 @@ ohos_unittest("AMSEventHandlerTest") { external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "bytrace_standard:bytrace_core", ] } diff --git a/services/bundlemgr/test/mock/include/mock_ability_mgr_host.h b/services/bundlemgr/test/mock/include/mock_ability_mgr_host.h index bf6e0e8a31..1fc25d504b 100644 --- a/services/bundlemgr/test/mock/include/mock_ability_mgr_host.h +++ b/services/bundlemgr/test/mock/include/mock_ability_mgr_host.h @@ -61,6 +61,10 @@ public: { return 0; } + virtual int MinimizeAbility(const sptr &token) override + { + return 0; + } virtual int ConnectAbility(const AAFwk::Want &want, const sptr &connect, const sptr &callerToken) override { @@ -308,6 +312,14 @@ public: { return 0; } + int StartContinuation(const Want &want, const sptr &abilityToken) override + { + return 0; + } + int NotifyContinuationResult(const sptr &abilityToken, const int32_t result) override + { + return 0; + } }; } // namespace AppExecFwk } // namespace OHOS diff --git a/services/formmgr/include/form_data_mgr.h b/services/formmgr/include/form_data_mgr.h index 4ac061d84b..d2d418f58d 100644 --- a/services/formmgr/include/form_data_mgr.h +++ b/services/formmgr/include/form_data_mgr.h @@ -321,7 +321,7 @@ public: * @param noHostTempFormsMap no host temp forms. * @param foundFormsMap Form Id list. */ - void GetNoHostTempForms(const int uid, std::map> &noHostTempFormsMap, + void GetNoHostTempForms(const int uid, std::map> &noHostTempFormsMap, std::map &foundFormsMap); /** diff --git a/services/formmgr/include/form_db_cache.h b/services/formmgr/include/form_db_cache.h index 786723efe3..9af492acb0 100644 --- a/services/formmgr/include/form_db_cache.h +++ b/services/formmgr/include/form_db_cache.h @@ -103,7 +103,7 @@ public: * @param foundFormsMap Form Id list. * @return Returns ERR_OK on success, others on failure. */ - ErrCode GetNoHostDBForms(const int uid, std::map> &noHostFormDBList, + ErrCode GetNoHostDBForms(const int uid, std::map> &noHostFormDBList, std::map &foundFormsMap); /** * @brief Get match count by bundleName and moduleName. diff --git a/services/formmgr/include/form_db_info.h b/services/formmgr/include/form_db_info.h index 0f63061742..b655669c1b 100644 --- a/services/formmgr/include/form_db_info.h +++ b/services/formmgr/include/form_db_info.h @@ -33,8 +33,8 @@ struct FormDBInfo { /** * @brief Constructors - * - */ + * + */ FormDBInfo() { formId = -1; @@ -43,7 +43,7 @@ struct FormDBInfo { /** * @brief Constructors * - */ + */ FormDBInfo(const int64_t formIdTmp, const FormRecord &formRecord) { formId = formIdTmp; @@ -125,7 +125,7 @@ public: } /** * @brief Constructors - * + * */ InnerFormInfo(const InnerFormInfo &innerFormInfo) { @@ -138,8 +138,8 @@ public: } /** * @brief Constructors - * - */ + * + */ InnerFormInfo(const int64_t formId, const FormRecord &formRecord) { formDBInfo_.formId = formId; diff --git a/services/formmgr/include/form_mgr_adapter.h b/services/formmgr/include/form_mgr_adapter.h index 91012a2584..9af9f1fa6e 100644 --- a/services/formmgr/include/form_mgr_adapter.h +++ b/services/formmgr/include/form_mgr_adapter.h @@ -425,12 +425,12 @@ private: * @brief get bundleName. * @param bundleName for output. * @return Returns true on success, others on failure. - */ + */ bool GetBundleName(std::string &bundleName); /** * @brief Update provider info to host - * + * * @param matchedFormId The Id of the form * @param callerToken Caller ability token. * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. @@ -443,14 +443,14 @@ private: /** * @brief If the form provider is system app and the config item 'formVisibleNotify' is true, * notify the form provider that the current form is visible. - * + * * @param bundleName BundleName * @return Returns true if the form provider is system app, false if not. */ bool CheckIsSystemAppByBundleName(const sptr &iBundleMgr, const std::string &bundleName); /** * @brief Create eventMaps for event notify. - * + * * @param matchedFormId The Id of the form * @param formRecord Form storage information * @param eventMaps eventMaps for event notify diff --git a/services/formmgr/include/form_timer_mgr.h b/services/formmgr/include/form_timer_mgr.h index 1175e6bdeb..57ddf271bb 100644 --- a/services/formmgr/include/form_timer_mgr.h +++ b/services/formmgr/include/form_timer_mgr.h @@ -150,29 +150,29 @@ public: * @brief Get dynamic refresh item. * @param formId The Id of the form. * @return Returns true on success, false on failure. - */ + */ bool GetDynamicItem(const int64_t formId, DynamicRefreshItem &dynamicItem); private: /** * @brief Add update at timer. * @param task Update time task. * @return Returns true on success, false on failure. - */ + */ bool AddUpdateAtTimer(const FormTimer &task); /** * @brief Add update at timer item. * @param task Update at timer item. - */ + */ void AddUpdateAtItem(const UpdateAtItem &atItem); /** * @brief Add update interval timer task. * @param task Update interval timer task. * @return Returns true on success, false on failure. - */ + */ bool AddIntervalTimer(const FormTimer &task); /** * @brief interval timer task timeout. - */ + */ void OnIntervalTimeOut(); /** * @brief Get remind tasks. diff --git a/services/formmgr/src/form_ams_helper.cpp b/services/formmgr/src/form_ams_helper.cpp index 7ffa8f4dc9..6760feb86c 100644 --- a/services/formmgr/src/form_ams_helper.cpp +++ b/services/formmgr/src/form_ams_helper.cpp @@ -13,10 +13,10 @@ * limitations under the License. */ +#include "form_ams_helper.h" #include "ability_manager_interface.h" -#include "appexecfwk_errors.h" #include "app_log_wrapper.h" -#include "form_ams_helper.h" +#include "appexecfwk_errors.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "iservice_registry.h" diff --git a/services/formmgr/src/form_bms_helper.cpp b/services/formmgr/src/form_bms_helper.cpp index 2f2a0d8e53..4f9f06919d 100644 --- a/services/formmgr/src/form_bms_helper.cpp +++ b/services/formmgr/src/form_bms_helper.cpp @@ -13,10 +13,10 @@ * limitations under the License. */ +#include "form_bms_helper.h" #include "ability_manager_interface.h" -#include "appexecfwk_errors.h" #include "app_log_wrapper.h" -#include "form_bms_helper.h" +#include "appexecfwk_errors.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "iservice_registry.h" diff --git a/services/formmgr/src/form_data_mgr.cpp b/services/formmgr/src/form_data_mgr.cpp index 5e6210a7b8..0809a2a491 100644 --- a/services/formmgr/src/form_data_mgr.cpp +++ b/services/formmgr/src/form_data_mgr.cpp @@ -161,6 +161,7 @@ FormRecord FormDataMgr::CreateFormRecord(const FormItemInfo &formInfo, const int newRecord.formTempFlg = formInfo.IsTemporaryForm(); newRecord.formVisibleNotify = formInfo.IsFormVisibleNotify(); newRecord.jsFormCodePath = formInfo.GetHapSourceByModuleName(newRecord.moduleName); + newRecord.formVisibleNotifyState = 0; if (newRecord.isEnableUpdate) { ParseUpdateConfig(newRecord, formInfo); } diff --git a/services/formmgr/src/form_db_info.cpp b/services/formmgr/src/form_db_info.cpp index f47f45c4f7..6c0551b52b 100644 --- a/services/formmgr/src/form_db_info.cpp +++ b/services/formmgr/src/form_db_info.cpp @@ -13,17 +13,19 @@ * limitations under the License. */ -#include "app_log_wrapper.h" #include "form_db_info.h" + +#include "json_util.h" + namespace OHOS { namespace AppExecFwk { namespace { -const std::string FORM_ID = "formId"; -const std::string FORM_NAME = "formName"; -const std::string BUNDLE_NAME = "bundleName"; -const std::string MODULE_NAME = "moduleName"; -const std::string ABILITY_NAME = "abilityName"; -const std::string FORM_USER_UIDS = "formUserUids"; +const std::string INNER_FORM_INFO_FORM_ID = "formId"; +const std::string INNER_FORM_INFO_FORM_NAME = "formName"; +const std::string INNER_FORM_INFO_BUNDLE_NAME = "bundleName"; +const std::string INNER_FORM_INFO_MODULE_NAME = "moduleName"; +const std::string INNER_FORM_INFO_ABILITY_NAME = "abilityName"; +const std::string INNER_FORM_INFO_FORM_USER_UIDS = "formUserUids"; } /** @@ -33,12 +35,12 @@ const std::string FORM_USER_UIDS = "formUserUids"; */ void InnerFormInfo::ToJson(nlohmann::json &jsonObject) const { - jsonObject[FORM_ID] = formDBInfo_.formId; - jsonObject[FORM_NAME] = formDBInfo_.formName; - jsonObject[BUNDLE_NAME] = formDBInfo_.bundleName; - jsonObject[MODULE_NAME] = formDBInfo_.moduleName; - jsonObject[ABILITY_NAME] = formDBInfo_.abilityName; - jsonObject[FORM_USER_UIDS] = formDBInfo_.formUserUids; + jsonObject[INNER_FORM_INFO_FORM_ID] = formDBInfo_.formId; + jsonObject[INNER_FORM_INFO_FORM_NAME] = formDBInfo_.formName; + jsonObject[INNER_FORM_INFO_BUNDLE_NAME] = formDBInfo_.bundleName; + jsonObject[INNER_FORM_INFO_MODULE_NAME] = formDBInfo_.moduleName; + jsonObject[INNER_FORM_INFO_ABILITY_NAME] = formDBInfo_.abilityName; + jsonObject[INNER_FORM_INFO_FORM_USER_UIDS] = formDBInfo_.formUserUids; } /** @@ -48,14 +50,57 @@ void InnerFormInfo::ToJson(nlohmann::json &jsonObject) const */ bool InnerFormInfo::FromJson(const nlohmann::json &jsonObject) { - formDBInfo_.formId = jsonObject.at(FORM_ID).get(); - formDBInfo_.formName = jsonObject.at(FORM_NAME).get(); - formDBInfo_.bundleName = jsonObject.at(BUNDLE_NAME).get(); - formDBInfo_.moduleName = jsonObject.at(MODULE_NAME).get(); - formDBInfo_.abilityName = jsonObject.at(ABILITY_NAME).get(); - formDBInfo_.formUserUids = jsonObject.at(FORM_USER_UIDS).get>(); - - return true; + const auto &jsonObjectEnd = jsonObject.end(); + int32_t parseResult = ERR_OK; + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + INNER_FORM_INFO_FORM_ID, + formDBInfo_.formId, + JsonType::NUMBER, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + INNER_FORM_INFO_FORM_NAME, + formDBInfo_.formName, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + INNER_FORM_INFO_BUNDLE_NAME, + formDBInfo_.bundleName, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + INNER_FORM_INFO_MODULE_NAME, + formDBInfo_.moduleName, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + INNER_FORM_INFO_ABILITY_NAME, + formDBInfo_.abilityName, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey>(jsonObject, + jsonObjectEnd, + INNER_FORM_INFO_FORM_USER_UIDS, + formDBInfo_.formUserUids, + JsonType::ARRAY, + false, + parseResult, + ArrayType::NUMBER); + return parseResult == ERR_OK; } void InnerFormInfo::AddUserUid(const int callingUid) @@ -63,7 +108,7 @@ void InnerFormInfo::AddUserUid(const int callingUid) auto iter = std::find(formDBInfo_.formUserUids.begin(), formDBInfo_.formUserUids.end(), callingUid); if (iter == formDBInfo_.formUserUids.end()) { formDBInfo_.formUserUids.push_back(callingUid); - } + } } bool InnerFormInfo::DeleteUserUid(const int callingUid) diff --git a/services/formmgr/src/form_mgr_adapter.cpp b/services/formmgr/src/form_mgr_adapter.cpp index 2f553f8ba3..fc60372f51 100644 --- a/services/formmgr/src/form_mgr_adapter.cpp +++ b/services/formmgr/src/form_mgr_adapter.cpp @@ -24,17 +24,17 @@ #include "form_cast_temp_connection.h" #include "form_constants.h" #include "form_data_mgr.h" -#include "form_delete_connection.h" #include "form_db_cache.h" #include "form_db_info.h" +#include "form_delete_connection.h" #include "form_dump_mgr.h" #include "form_event_notify_connection.h" #include "form_mgr_adapter.h" #include "form_provider_info.h" #include "form_provider_interface.h" #include "form_provider_mgr.h" -#include "form_supply_callback.h" #include "form_refresh_connection.h" +#include "form_supply_callback.h" #include "form_timer_mgr.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" @@ -68,7 +68,7 @@ int FormMgrAdapter::AddForm(const int64_t formId, const Want &want, return ERR_APPEXECFWK_FORM_INVALID_PARAM; } - // check form count limit + // check form count limit bool tempFormFlag = want.GetBoolParam(Constants::PARAM_FORM_TEMPORARY_KEY, false); int callingUid = IPCSkeleton::GetCallingUid(); int checkCode = 0; @@ -221,7 +221,7 @@ ErrCode FormMgrAdapter::HandleDeleteForm(const int64_t formId, const sptr } int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); - if (!FormDataMgr::GetInstance().ExistFormRecord(matchedFormId) || + if (!FormDataMgr::GetInstance().ExistFormRecord(matchedFormId) || !FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) { APP_LOGE("%{public}s, not exist such temp form:%{public}" PRId64 "", __func__, matchedFormId); return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; @@ -608,7 +608,7 @@ int FormMgrAdapter::DumpStorageFormInfos(std::string &formInfos) const FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); if (formDBInfos.size() > 0) { std::sort(formDBInfos.begin(), formDBInfos.end(), - [] (FormDBInfo &formDBInfoA, FormDBInfo &formDBInfoB) -> bool { + [] (FormDBInfo &formDBInfoA, FormDBInfo &formDBInfoB) -> bool { return formDBInfoA.formId < formDBInfoB.formId; }); FormDumpMgr::GetInstance().DumpStorageFormInfos(formDBInfos, formInfos); @@ -650,13 +650,13 @@ int FormMgrAdapter::DumpFormInfoByFormId(const std::int64_t formId, std::string FormDumpMgr::GetInstance().DumpFormInfo(formRecord, formInfo); reply = ERR_OK; } - + FormHostRecord formHostRecord; if (FormDataMgr::GetInstance().GetFormHostRecord(formId, formHostRecord)) { - FormDumpMgr::GetInstance().DumpFormHostInfo(formHostRecord, formInfo); + FormDumpMgr::GetInstance().DumpFormHostInfo(formHostRecord, formInfo); reply = ERR_OK; } - + return reply; } /** @@ -1021,14 +1021,14 @@ ErrCode FormMgrAdapter::GetBundleInfo(const AAFwk::Want &want, BundleInfo &bundl return ERR_APPEXECFWK_FORM_NO_SUCH_MODULE; } - for (const auto &abilityInfo : bundleInfo.abilityInfos) { + for (const auto &abilityInfo : bundleInfo.abilityInfos) { if (abilityInfo.bundleName == bundleName && abilityInfo.moduleName == moduleName && abilityInfo.name == abilityName) { packageName = bundleName + moduleName; break; } } - + if (packageName.empty()) { APP_LOGE("GetBundleInfo can not find target ability %{public}s", abilityName.c_str()); return ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY; @@ -1462,7 +1462,7 @@ int FormMgrAdapter::BatchAddFormRecords(const Want &want) bundleName.c_str(), abilityName.c_str(), formCount); - + for (int count = 0; count < formCount; count++) { // get from comfig info FormItemInfo formItemInfo; @@ -1486,7 +1486,7 @@ int FormMgrAdapter::BatchAddFormRecords(const Want &want) APP_LOGE("%{public}s fail, generateFormId no invalid formId", __func__); return ERR_APPEXECFWK_FORM_COMMON_CODE; } - + formItemInfo.SetFormId(newFormId); // allot form host record int callingUid = IPCSkeleton::GetCallingUid(); @@ -1512,7 +1512,7 @@ int FormMgrAdapter::ClearFormRecords() } /** * @brief Create eventMaps for event notify. - * + * * @param matchedFormId The Id of the form * @param formRecord Form storage information * @param eventMaps eventMaps for event notify @@ -1522,7 +1522,7 @@ bool FormMgrAdapter::CreateHandleEventMap(const int64_t matchedFormId, const For std::map> &eventMaps) { if (!formRecord.formVisibleNotify) { - APP_LOGW("%{public}s fail, the config item 'formVisibleNotify' is false, formId:%{public}" PRId64 ".", + APP_LOGW("%{public}s fail, the config item 'formVisibleNotify' is false, formId:%{public}" PRId64 ".", __func__, matchedFormId); return false; } @@ -1539,7 +1539,7 @@ bool FormMgrAdapter::CreateHandleEventMap(const int64_t matchedFormId, const For } /** * @brief Update provider info to host - * + * * @param matchedFormId The Id of the form * @param callerToken Caller ability token. * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. @@ -1563,7 +1563,7 @@ bool FormMgrAdapter::UpdateProviderInfoToHost(const int64_t matchedFormId, const formRecord.formVisibleNotifyState = formVisibleType; if (!FormDataMgr::GetInstance().UpdateFormRecord(matchedFormId, formRecord)) { - APP_LOGW("%{public}s fail, set formVisibleNotifyState error, formId:%{public}" PRId64 ".", + APP_LOGW("%{public}s fail, set formVisibleNotifyState error, formId:%{public}" PRId64 ".", __func__, matchedFormId); return false; } @@ -1582,7 +1582,7 @@ bool FormMgrAdapter::UpdateProviderInfoToHost(const int64_t matchedFormId, const /** * @brief If the form provider is system app and the config item 'formVisibleNotify' is true, * notify the form provider that the current form is visible. - * + * * @param bundleName BundleName * @return Returns true if the form provider is system app, false if not. */ diff --git a/services/formmgr/src/form_mgr_service.cpp b/services/formmgr/src/form_mgr_service.cpp index e7ead18631..53ed006eb0 100644 --- a/services/formmgr/src/form_mgr_service.cpp +++ b/services/formmgr/src/form_mgr_service.cpp @@ -12,13 +12,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +#include "form_mgr_service.h" + #include #include #include #include -#include "appexecfwk_errors.h" #include "app_log_wrapper.h" +#include "appexecfwk_errors.h" #include "common_event_manager.h" #include "common_event_support.h" #include "form_ams_helper.h" @@ -26,14 +29,13 @@ #include "form_constants.h" #include "form_data_mgr.h" #include "form_db_cache.h" -#include "form_mgr_service.h" #include "form_mgr_adapter.h" #include "form_task_mgr.h" #include "form_timer_mgr.h" #include "ipc_skeleton.h" #include "iservice_registry.h" -#include "permission/permission_kit.h" #include "permission/permission.h" +#include "permission/permission_kit.h" #include "string_ex.h" #include "system_ability_definition.h" @@ -366,7 +368,7 @@ ErrCode FormMgrService::Init() FormAmsHelper::GetInstance().SetEventHandler(handler_); /* Publish service maybe failed, so we need call this function at the last, * so it can't affect the TDD test program */ - bool ret = Publish(DelayedSingleton::GetInstance().get()); + bool ret = Publish(DelayedSingleton::GetInstance().get()); if (!ret) { APP_LOGE("%{public}s fail, FormMgrService::Init Publish failed!", __func__); return ERR_INVALID_OPERATION; @@ -406,7 +408,7 @@ bool FormMgrService::CheckFormPermission(const std::string &bundleName) const } int result = PermissionKit::VerifyPermission(bundleName, Constants::PERMISSION_REQUIRE_FORM, 0); if (result != PermissionState::PERMISSION_GRANTED) { - APP_LOGW("permission = %{public}s, bundleName = %{public}s, result = %{public}d", + APP_LOGW("permission = %{public}s, bundleName = %{public}s, result = %{public}d", Constants::PERMISSION_REQUIRE_FORM.c_str(), bundleName.c_str(), result); } return result == PermissionState::PERMISSION_GRANTED; diff --git a/services/formmgr/src/form_provider_mgr.cpp b/services/formmgr/src/form_provider_mgr.cpp index 35a7e9af62..a5e0ae604b 100644 --- a/services/formmgr/src/form_provider_mgr.cpp +++ b/services/formmgr/src/form_provider_mgr.cpp @@ -304,11 +304,11 @@ ErrCode FormProviderMgr::UpdateForm(const int64_t formId, } // update formProviderInfo to formRecord FormDataMgr::GetInstance().UpdateFormProviderInfo(formId, formRecord.formProviderInfo); - // check if cache data size is less than 1k or not + // check if cache data size is less than 1k or not std::string jsonData = formRecord.formProviderInfo.GetFormDataString(); // get json data APP_LOGD("%{public}s , jsonData is %{public}s.", __func__, jsonData.c_str()); if (jsonData.size() <= Constants::MAX_FORM_DATA_SIZE) { - APP_LOGI("%{public}s, updateJsForm, data is less than 1k, cache data.", __func__); + APP_LOGI("%{public}s, updateJsForm, data is less than 1k, cache data.", __func__); FormCacheMgr::GetInstance().AddData(formId, jsonData); } else { FormCacheMgr::GetInstance().DeleteData(formId); diff --git a/services/formmgr/src/form_storage_mgr.cpp b/services/formmgr/src/form_storage_mgr.cpp index 92f7cda824..d26511c54c 100644 --- a/services/formmgr/src/form_storage_mgr.cpp +++ b/services/formmgr/src/form_storage_mgr.cpp @@ -13,21 +13,21 @@ * limitations under the License. */ -#include +#include "form_storage_mgr.h" #include #include #include -#include +#include +#include #include #include -#include #include -#include "securec.h" #include "app_log_wrapper.h" #include "form_storage_mgr.h" #include "kvstore_death_recipient_callback.h" +#include "securec.h" #include "string_ex.h" #include "types.h" @@ -95,7 +95,7 @@ void FormStorageMgr::SaveEntries( */ ErrCode FormStorageMgr::LoadFormData(std::vector &innerFormInfos) { - APP_LOGI("%{public}s called.", __func__); + APP_LOGD("%{public}s called.", __func__); bool ret = ERR_OK; { std::lock_guard lock(kvStorePtrMutex_); @@ -118,7 +118,7 @@ ErrCode FormStorageMgr::LoadFormData(std::vector &innerFormInfos) SaveEntries(allEntries, innerFormInfos); } - APP_LOGI("%{public}s, readdir over", __func__); + APP_LOGD("%{public}s, readdir over", __func__); return ret; } @@ -139,7 +139,7 @@ ErrCode FormStorageMgr::GetStorageFormInfoById(const std::string &formId, InnerF return ERR_APPEXECFWK_FORM_COMMON_CODE; } } - + DistributedKv::Status status = DistributedKv::Status::ERROR; std::vector allEntries; DistributedKv::Key key(formId); @@ -147,7 +147,7 @@ ErrCode FormStorageMgr::GetStorageFormInfoById(const std::string &formId, InnerF // sync call GetEntries, the callback will be trigger at once status = kvStorePtr_->GetEntries(key, allEntries); } - + if (status != DistributedKv::Status::SUCCESS) { APP_LOGE("get entries error: %{public}d", status); ret = ERR_APPEXECFWK_FORM_COMMON_CODE; @@ -223,7 +223,7 @@ ErrCode FormStorageMgr::ModifyStorageFormInfo(const InnerFormInfo &innerFormInfo if (ret == ERR_OK) { SaveStorageFormInfo(innerFormInfo); } - + return ret; } diff --git a/services/formmgr/src/form_sys_event_receiver.cpp b/services/formmgr/src/form_sys_event_receiver.cpp index c969bf47e9..74e0efb5d8 100644 --- a/services/formmgr/src/form_sys_event_receiver.cpp +++ b/services/formmgr/src/form_sys_event_receiver.cpp @@ -15,8 +15,8 @@ #include -#include "appexecfwk_errors.h" #include "app_log_wrapper.h" +#include "appexecfwk_errors.h" #include "bundle_info.h" #include "common_event_manager.h" #include "common_event_support.h" @@ -27,9 +27,9 @@ #include "form_db_cache.h" #include "form_db_info.h" #include "form_provider_mgr.h" +#include "form_sys_event_receiver.h" #include "form_timer_mgr.h" #include "form_util.h" -#include "form_sys_event_receiver.h" #include "want.h" namespace OHOS { diff --git a/services/formmgr/src/form_timer_mgr.cpp b/services/formmgr/src/form_timer_mgr.cpp index 6163830ff4..67dfcd3c13 100644 --- a/services/formmgr/src/form_timer_mgr.cpp +++ b/services/formmgr/src/form_timer_mgr.cpp @@ -13,17 +13,19 @@ * limitations under the License. */ +#include "form_timer_mgr.h" + #include + #include "ability_context.h" -#include "appexecfwk_errors.h" #include "app_log_wrapper.h" +#include "appexecfwk_errors.h" #include "common_event_manager.h" #include "common_event_support.h" #include "form_constants.h" #include "form_provider_mgr.h" #include "form_refresh_limiter.h" #include "form_timer_option.h" -#include "form_timer_mgr.h" #include "form_util.h" #include "want.h" @@ -642,7 +644,7 @@ bool FormTimerMgr::GetUpdateAtTimer(const int64_t formId, UpdateAtItem &updateAt { APP_LOGI("%{public}s start", __func__); { - std::lock_guard lock(updateAtMutex_); + std::lock_guard lock(updateAtMutex_); std::list::iterator itItem; for (itItem = updateAtTimerTasks_.begin(); itItem != updateAtTimerTasks_.end(); itItem++) { if (itItem->refreshTask.formId == formId) { @@ -660,7 +662,7 @@ bool FormTimerMgr::GetUpdateAtTimer(const int64_t formId, UpdateAtItem &updateAt * @brief Get dynamic refresh item. * @param formId The Id of the form. * @return Returns true on success, false on failure. - */ + */ bool FormTimerMgr::GetDynamicItem(const int64_t formId, DynamicRefreshItem &dynamicItem) { APP_LOGI("%{public}s start", __func__); @@ -672,7 +674,7 @@ bool FormTimerMgr::GetDynamicItem(const int64_t formId, DynamicRefreshItem &dyna dynamicItem.settedTime = itItem->settedTime; APP_LOGI("%{public}s, get dynamic item successfully", __func__); return true; - } + } } APP_LOGI("%{public}s, dynamic item not find", __func__); return false; @@ -802,7 +804,7 @@ void FormTimerMgr::ClearUpdateAtTimerResource() /** * @brief Update limiter task alarm. * @return Returns true on success, false on failure. - */ + */ bool FormTimerMgr::UpdateLimiterAlarm() { APP_LOGI("%{public}s start", __func__); @@ -811,7 +813,7 @@ bool FormTimerMgr::UpdateLimiterAlarm() } /** * @brief Clear limiter timer resource. - */ + */ void FormTimerMgr::ClearLimiterTimerResource() { APP_LOGI("%{public}s start", __func__); @@ -822,7 +824,7 @@ void FormTimerMgr::ClearLimiterTimerResource() /** * @brief Update dynamic refresh task alarm. * @return Returns true on success, false on failure. - */ + */ bool FormTimerMgr::UpdateDynamicAlarm() { APP_LOGI("%{public}s start", __func__); @@ -834,7 +836,7 @@ bool FormTimerMgr::UpdateDynamicAlarm() /** * @brief Clear dynamic refresh resource. - */ + */ void FormTimerMgr::ClearDynamicResource() { APP_LOGI("%{public}s start", __func__); diff --git a/services/formmgr/src/form_util.cpp b/services/formmgr/src/form_util.cpp index d3f08c5f02..af615f981c 100644 --- a/services/formmgr/src/form_util.cpp +++ b/services/formmgr/src/form_util.cpp @@ -13,8 +13,8 @@ * limitations under the License. */ -#include #include +#include #include #include #include diff --git a/services/formmgr/test/mock/include/mock_ability_manager.h b/services/formmgr/test/mock/include/mock_ability_manager.h index 1d603fbcf3..41b7dc6f6f 100644 --- a/services/formmgr/test/mock/include/mock_ability_manager.h +++ b/services/formmgr/test/mock/include/mock_ability_manager.h @@ -259,6 +259,15 @@ public: { return 0; } + + int StartContinuation(const Want &want, const sptr &abilityToken) override + { + return 0; + } + int NotifyContinuationResult(const sptr &abilityToken, const int32_t result) override + { + return 0; + } }; class MockAbilityMgrStub : public IRemoteStub { @@ -308,6 +317,10 @@ public: { return 0; } + virtual int MinimizeAbility(const sptr &token) override + { + return 0; + } virtual int ConnectAbility( const AAFwk::Want &want, const sptr &connect, const sptr &callerToken) { @@ -575,6 +588,15 @@ public: return 0; } + int StartContinuation(const Want &want, const sptr &abilityToken) override + { + return 0; + } + int NotifyContinuationResult(const sptr &abilityToken, const int32_t result) override + { + return 0; + } + private: Semaphore sem_; }; diff --git a/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp b/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp index 19556a29f3..e4490d7e1d 100644 --- a/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp +++ b/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp @@ -17,8 +17,9 @@ #include #include #include -#include "appexecfwk_errors.h" + #include "app_log_wrapper.h" +#include "appexecfwk_errors.h" #define private public #include "form_data_mgr.h" #undef private diff --git a/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp b/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp index e062b3f41c..2b88927702 100644 --- a/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp +++ b/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp @@ -31,8 +31,8 @@ #include "mock_ability_manager.h" #include "mock_bundle_manager.h" #include "mock_form_host_client.h" -#include "permission/permission_kit.h" #include "permission/permission.h" +#include "permission/permission_kit.h" #include "running_process_info.h" #include "system_ability_definition.h" diff --git a/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp index 1d7f2c0a86..43ba2ed680 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp @@ -33,8 +33,8 @@ #include "mock_ability_manager.h" #include "mock_bundle_manager.h" #include "mock_form_host_client.h" -#include "permission/permission_kit.h" #include "permission/permission.h" +#include "permission/permission_kit.h" #include "running_process_info.h" #include "system_ability_definition.h" diff --git a/services/formmgr/test/unittest/fms_form_mgr_cast_temp_form_test/fms_form_mgr_cast_temp_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_cast_temp_form_test/fms_form_mgr_cast_temp_form_test.cpp index 6bd87bac09..8234f472ef 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_cast_temp_form_test/fms_form_mgr_cast_temp_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_cast_temp_form_test/fms_form_mgr_cast_temp_form_test.cpp @@ -14,6 +14,7 @@ */ #include + #include "form_ams_helper.h" #include "form_bms_helper.h" #include "form_data_mgr.h" diff --git a/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp index 01e862d910..7ba1b29c6e 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp @@ -14,23 +14,24 @@ */ #include + #include "form_bms_helper.h" #include "form_db_cache.h" #include "form_host_interface.h" #define private public +#include "form_data_mgr.h" #include "form_mgr.h" #include "form_mgr_service.h" -#include "form_data_mgr.h" #undef private #include "if_system_ability_manager.h" #include "inner_bundle_info.h" #include "ipc_skeleton.h" #include "iservice_registry.h" -#include "permission/permission.h" -#include "permission/permission_kit.h" #include "mock_bundle_manager.h" #include "mock_form_host_client.h" +#include "permission/permission.h" +#include "permission/permission_kit.h" using namespace testing::ext; using namespace OHOS; diff --git a/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp index b9cd43b3bb..2dfea50c35 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp @@ -22,16 +22,16 @@ #define private public #include "form_bms_helper.h" #include "form_constants.h" -#include "form_mgr_service.h" -#include "form_mgr_adapter.h" #include "form_data_mgr.h" #include "form_mgr.h" +#include "form_mgr_service.h" +#include "form_mgr_adapter.h" #undef private -#include "mock_form_host_client.h" #include "mock_bundle_manager.h" +#include "mock_form_host_client.h" +#include "permission/permission.h" #include "permission/permission_def.h" #include "permission/permission_kit.h" -#include "permission/permission.h" using namespace testing::ext; using namespace OHOS; diff --git a/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp index 30a5b3673c..1cf03c5618 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp @@ -30,10 +30,10 @@ #include "ipc_skeleton.h" #include "iservice_registry.h" #include "mock_bundle_manager.h" -#include "mock_form_token.h" #include "mock_form_host_client.h" -#include "permission/permission_kit.h" +#include "mock_form_token.h" #include "permission/permission.h" +#include "permission/permission_kit.h" #include "running_process_info.h" #include "system_ability_definition.h" diff --git a/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp b/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp index f20fec9b9b..69244b5b00 100644 --- a/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp +++ b/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp @@ -17,8 +17,8 @@ #include #include #include -#include #include +#include #include "app_log_wrapper.h" #define private public diff --git a/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp index d6e661b62e..a4a99bf8f7 100644 --- a/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp +++ b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp @@ -14,18 +14,18 @@ */ #include -#include #include +#include #include "app_log_wrapper.h" #include "appexecfwk_errors.h" #define private public #include "form_bms_helper.h" #include "form_constants.h" -#include "form_timer_mgr.h" -#include "form_mgr_service.h" -#include "form_mgr_adapter.h" #include "form_data_mgr.h" +#include "form_mgr_adapter.h" +#include "form_mgr_service.h" +#include "form_timer_mgr.h" #undef private #include "mock_bundle_manager.h" diff --git a/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp index 2b094e5940..4625d9cd53 100644 --- a/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp +++ b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp @@ -25,20 +25,20 @@ #include "form_host_interface.h" #include "form_mgr.h" #undef private +#include "form_bms_helper.h" #include "form_mgr_service.h" #include "form_refresh_limiter.h" #include "form_sys_event_receiver.h" #include "if_system_ability_manager.h" #include "inner_bundle_info.h" #include "ipc_skeleton.h" -#include "form_bms_helper.h" #include "iservice_registry.h" #include "mock_ability_manager.h" #include "mock_bundle_manager.h" #include "mock_form_host_client.h" -#include "permission/permission_kit.h" #include "permission/permission.h" +#include "permission/permission_kit.h" #include "running_process_info.h" #include "system_ability_definition.h" diff --git a/services/test/mock/include/mock_ability_mgr_host.h b/services/test/mock/include/mock_ability_mgr_host.h index 006845c540..50b3dedb65 100644 --- a/services/test/mock/include/mock_ability_mgr_host.h +++ b/services/test/mock/include/mock_ability_mgr_host.h @@ -55,6 +55,10 @@ public: { return 0; } + virtual int MinimizeAbility(const sptr &token) override + { + return 0; + } virtual int ConnectAbility(const AAFwk::Want &want, const sptr &connect, const sptr &callerToken) override { @@ -305,6 +309,14 @@ public: { return 0; } + int StartContinuation(const Want &want, const sptr &abilityToken) override + { + return 0; + } + int NotifyContinuationResult(const sptr &abilityToken, const int32_t result) override + { + return 0; + } }; } // namespace AppExecFwk } // namespace OHOS diff --git a/services/test/mock/src/system_ability_helper.cpp b/services/test/mock/src/system_ability_helper.cpp index 00c4654a81..5c7567701c 100644 --- a/services/test/mock/src/system_ability_helper.cpp +++ b/services/test/mock/src/system_ability_helper.cpp @@ -17,9 +17,9 @@ #include -#include "system_ability_definition.h" #include "app_log_wrapper.h" #include "mock_ability_mgr_host.h" +#include "system_ability_definition.h" namespace OHOS { namespace AppExecFwk { diff --git a/services/test/moduletest/common/ams/BUILD.gn b/services/test/moduletest/common/ams/BUILD.gn index dfe219c3ae..1153fde20f 100755 --- a/services/test/moduletest/common/ams/BUILD.gn +++ b/services/test/moduletest/common/ams/BUILD.gn @@ -87,8 +87,10 @@ ohos_source_set("appmgr_mst_source") { external_deps = [ "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "bytrace_standard:bytrace_core", ] } diff --git a/services/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp b/services/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp index 3449f21a90..d6193a5187 100644 --- a/services/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp +++ b/services/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp @@ -18,14 +18,14 @@ #include "app_mgr_service_inner.h" #undef private -#include #include +#include -#include "semaphore_ex.h" #include "app_scheduler_host.h" #include "app_scheduler_proxy.h" #include "mock_app_mgr_service_inner.h" #include "mock_app_spawn_socket.h" +#include "semaphore_ex.h" using namespace testing::ext; using testing::_; diff --git a/services/test/moduletest/common/ams/ipc_ams_mgr_test/ams_ipc_ams_mgr_module_test.cpp b/services/test/moduletest/common/ams/ipc_ams_mgr_test/ams_ipc_ams_mgr_module_test.cpp index fb70baede0..b85df8ce86 100644 --- a/services/test/moduletest/common/ams/ipc_ams_mgr_test/ams_ipc_ams_mgr_module_test.cpp +++ b/services/test/moduletest/common/ams/ipc_ams_mgr_test/ams_ipc_ams_mgr_module_test.cpp @@ -18,19 +18,18 @@ #define private public #include "app_mgr_client.h" #undef private +#include "ams_mgr_scheduler.h" +#include "app_mgr_proxy.h" +#include "app_mgr_service_event_handler.h" +#include "app_record_id.h" +#include "app_scheduler_proxy.h" #include "mock_ability_token.h" #include "mock_application.h" #include "mock_iapp_state_callback.h" -#include "iremote_object.h" -#include "app_record_id.h" -#include "ams_mgr_proxy.h" #include "mock_app_mgr_service.h" -#include "mock_app_service_mgr.h" #include "mock_app_mgr_service_inner.h" -#include "app_mgr_service_event_handler.h" -#include "ams_mgr_scheduler.h" -#include "app_mgr_proxy.h" -#include "app_scheduler_proxy.h" +#include "mock_app_service_mgr.h" +#include "iremote_object.h" using namespace testing::ext; using OHOS::iface_cast; diff --git a/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp b/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp index 5e1f5bbea8..580e0cdd31 100644 --- a/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp +++ b/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp @@ -14,13 +14,13 @@ */ #include -#include "semaphore_ex.h" -#include "app_scheduler_proxy.h" #include "app_scheduler_host.h" +#include "app_scheduler_proxy.h" +#include "semaphore_ex.h" #include "mock_ability_token.h" -#include "mock_application.h" #include "mock_app_scheduler.h" +#include "mock_application.h" using namespace testing::ext; using namespace OHOS::AppExecFwk; diff --git a/services/test/moduletest/common/ams/service_event_drive_test/ams_service_event_drive_module_test.cpp b/services/test/moduletest/common/ams/service_event_drive_test/ams_service_event_drive_module_test.cpp index 2f0de0cbcc..3bddabe678 100644 --- a/services/test/moduletest/common/ams/service_event_drive_test/ams_service_event_drive_module_test.cpp +++ b/services/test/moduletest/common/ams/service_event_drive_test/ams_service_event_drive_module_test.cpp @@ -19,9 +19,10 @@ #include "app_mgr_service.h" #undef private #undef protected -#include -#include "semaphore_ex.h" #include "app_log_wrapper.h" +#include "semaphore_ex.h" + +#include using namespace testing::ext; using namespace OHOS::AppExecFwk; diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/include/ams_st_data_ability_data_a.h b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/include/ams_st_data_ability_data_a.h index 48f930a9e3..d64782dde9 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/include/ams_st_data_ability_data_a.h +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/include/ams_st_data_ability_data_a.h @@ -38,7 +38,8 @@ public: void SubscribeEvent(const Want &want); bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); STtools::Event event; - int fd; + FILE *file = nullptr; + int fd = -1; ~AmsStDataAbilityDataA(); protected: diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_data_a.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_data_a.cpp index d259b18fe1..ebbc51ba44 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_data_a.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_data_a.cpp @@ -67,6 +67,11 @@ void DataTestDataAEventSubscriber::OnReceiveEvent(const CommonEventData &data) AmsStDataAbilityDataA::~AmsStDataAbilityDataA() { + if (file != nullptr) { + fclose(file); + file = nullptr; + fd = -1; + } CommonEventManager::UnSubscribeCommonEvent(subscriber_); } @@ -100,15 +105,15 @@ int AmsStDataAbilityDataA::Insert(const Uri &uri, const NativeRdb::ValuesBucket APP_LOGI("AmsStDataAbilityDataA <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_A_CODE, "Insert"); if (fd <= 0) { - APP_LOGI("-------------------AmsStDataAbilityDataA <<<>>> file fd <= 0"); + APP_LOGI("AmsStDataAbilityDataA <<<>>> file fd <= 0"); return DEFAULT_INSERT_RESULT; } int dupFd = dup(fd); FILE *file = fdopen(dupFd, "r"); if (file == nullptr) { - APP_LOGI("-------------------AmsStDataAbilityDataA <<<>>> file == nullptr"); + APP_LOGI("AmsStDataAbilityDataA <<<>>> file == nullptr"); } else { - APP_LOGI("-------------------AmsStDataAbilityDataA <<<>>> file != nullptr"); + APP_LOGI("AmsStDataAbilityDataA <<<>>> file != nullptr"); fclose(file); file = nullptr; } @@ -167,13 +172,18 @@ int AmsStDataAbilityDataA::OpenFile(const Uri &uri, const std::string &mode) { APP_LOGI("AmsStDataAbilityDataA <<<>>>"); - FILE *fd1 = fopen("/system/vendor/test.txt", "r"); - if (fd1 == nullptr) { - APP_LOGI("-------------------------------AmsStDataAbilityDataA <<<>>> fdr == nullptr"); + if (file != nullptr) { + fclose(file); + file = nullptr; + fd = -1; + } + file = fopen("/system/vendor/test.txt", "r"); + if (file == nullptr) { + APP_LOGI("AmsStDataAbilityDataA <<<>>> fdr == nullptr"); return -1; } - fd = fileno(fd1); - APP_LOGI("--------------------------------AmsStDataAbilityDataA fd: %{public}d", fd); + fd = fileno(file); + APP_LOGI("AmsStDataAbilityDataA fd: %{public}d", fd); PublishEvent(abilityEventName, ABILITY_DATA_A_CODE, "OpenFile"); return fd; } diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c1.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c1.cpp index 8a5ae47ab0..795358cce2 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c1.cpp @@ -98,15 +98,15 @@ int AmsStDataAbilityDataC1::Insert(const Uri &uri, const NativeRdb::ValuesBucket APP_LOGI("AmsStDataAbilityDataC1 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, "Insert"); if (fd <= 0) { - APP_LOGI("-------------------AmsStDataAbilityDataC1 <<<>>> file fd <= 0"); + APP_LOGI("AmsStDataAbilityDataC1 <<<>>> file fd <= 0"); return DEFAULT_INSERT_RESULT; } int dupFd = dup(fd); FILE *file = fdopen(dupFd, "r"); if (file == nullptr) { - APP_LOGI("-------------------AmsStDataAbilityDataC1 <<<>>> file == nullptr"); + APP_LOGI("AmsStDataAbilityDataC1 <<<>>> file == nullptr"); } else { - APP_LOGI("-------------------AmsStDataAbilityDataC1 <<<>>> file != nullptr"); + APP_LOGI("AmsStDataAbilityDataC1 <<<>>> file != nullptr"); fclose(file); file = nullptr; } @@ -159,11 +159,11 @@ int AmsStDataAbilityDataC1::OpenFile(const Uri &uri, const std::string &mode) FILE *fd1 = fopen("/system/vendor/test.txt", "r"); if (fd1 == nullptr) { - APP_LOGI("-------------------------------AmsStDataAbilityDataC1 <<<>>> fdr == nullptr"); + APP_LOGI("AmsStDataAbilityDataC1 <<<>>> fdr == nullptr"); return -1; } fd = fileno(fd1); - APP_LOGI("--------------------------------AmsStDataAbilityDataC1 fd: %{public}d", fd); + APP_LOGI("AmsStDataAbilityDataC1 fd: %{public}d", fd); PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, "OpenFile"); return fd; } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp index d49b9e98ca..a99add0aa9 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp @@ -15,18 +15,18 @@ #include "fifth_ability.h" #include "app_log_wrapper.h" -#include "ohos/aafwk/base/base_types.h" -#include "test_utils.h" #include "ohos/aafwk/base/array_wrapper.h" +#include "ohos/aafwk/base/base_types.h" #include "ohos/aafwk/base/bool_wrapper.h" #include "ohos/aafwk/base/byte_wrapper.h" -#include "ohos/aafwk/base/short_wrapper.h" +#include "ohos/aafwk/base/double_wrapper.h" +#include "ohos/aafwk/base/float_wrapper.h" #include "ohos/aafwk/base/int_wrapper.h" #include "ohos/aafwk/base/long_wrapper.h" -#include "ohos/aafwk/base/float_wrapper.h" -#include "ohos/aafwk/base/double_wrapper.h" +#include "ohos/aafwk/base/short_wrapper.h" #include "ohos/aafwk/base/string_wrapper.h" #include "ohos/aafwk/base/zchar_wrapper.h" +#include "test_utils.h" namespace OHOS { namespace AppExecFwk { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp index 723d581587..eab7fd56f8 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp @@ -14,22 +14,21 @@ */ #include "second_ability.h" -#include "ohos/aafwk/base/base_types.h" #include "app_log_wrapper.h" -#include "uri.h" -#include "ohos/aafwk/content/operation_builder.h" -#include "test_utils.h" #include "ohos/aafwk/base/array_wrapper.h" +#include "ohos/aafwk/base/base_types.h" #include "ohos/aafwk/base/bool_wrapper.h" -#include "ohos/aafwk/base/zchar_wrapper.h" #include "ohos/aafwk/base/byte_wrapper.h" -#include "ohos/aafwk/base/short_wrapper.h" +#include "ohos/aafwk/base/double_wrapper.h" +#include "ohos/aafwk/base/float_wrapper.h" #include "ohos/aafwk/base/int_wrapper.h" #include "ohos/aafwk/base/long_wrapper.h" -#include "ohos/aafwk/base/float_wrapper.h" -#include "ohos/aafwk/base/double_wrapper.h" +#include "ohos/aafwk/base/short_wrapper.h" #include "ohos/aafwk/base/string_wrapper.h" #include "ohos/aafwk/base/zchar_wrapper.h" +#include "ohos/aafwk/content/operation_builder.h" +#include "test_utils.h" +#include "uri.h" namespace OHOS { namespace AppExecFwk { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a1.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a1.h index 9f08a10ead..1d3595ffea 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a1.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a1.h @@ -41,6 +41,7 @@ public: void SubscribeEvent(const Want &want); bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); STtools::Event event; + FILE *fd1 = nullptr; void TestLifeCycle(); ~AmsStKitDataAbilityDataA1(); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a2.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a2.h index aa9e88cc6f..b00844a05f 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a2.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a2.h @@ -41,6 +41,7 @@ public: void SubscribeEvent(const Want &want); bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); STtools::Event event; + FILE *fd1 = nullptr; void TestLifeCycle(); ~AmsStKitDataAbilityDataA2(); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a3.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a3.h index a5ad845810..cf3e758729 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a3.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a3.h @@ -41,6 +41,7 @@ public: void SubscribeEvent(const Want &want); bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); STtools::Event event; + FILE *fd1 = nullptr; void TestLifeCycle(); ~AmsStKitDataAbilityDataA3(); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a1.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a1.cpp index 424a15b05e..09f24cd33d 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a1.cpp @@ -191,6 +191,10 @@ void AmsStKitDataAbilityDataA1::Init(const std::shared_ptr &ability AmsStKitDataAbilityDataA1::~AmsStKitDataAbilityDataA1() { + if (fd1 != nullptr) { + fclose(fd1); + fd1 = nullptr; + } CommonEventManager::UnSubscribeCommonEvent(subscriber_); } @@ -313,7 +317,11 @@ std::vector AmsStKitDataAbilityDataA1::GetFileTypes(const Uri &uri, int AmsStKitDataAbilityDataA1::OpenFile(const Uri &uri, const std::string &mode) { APP_LOGI("AmsStKitDataAbilityDataA1 <<<>>>"); - FILE *fd1 = fopen("/system/vendor/test.txt", "r"); + if (fd1 != nullptr) { + fclose(fd1); + fd1 = nullptr; + } + fd1 = fopen("/system/vendor/test.txt", "r"); if (fd1 == nullptr) return -1; int fd = fileno(fd1); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a2.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a2.cpp index 45ee1a2db2..5f4b3030fd 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a2.cpp @@ -189,6 +189,10 @@ void AmsStKitDataAbilityDataA2::Init(const std::shared_ptr &ability AmsStKitDataAbilityDataA2::~AmsStKitDataAbilityDataA2() { + if (fd1 != nullptr) { + fclose(fd1); + fd1 = nullptr; + } CommonEventManager::UnSubscribeCommonEvent(subscriber_); } @@ -310,7 +314,11 @@ std::vector AmsStKitDataAbilityDataA2::GetFileTypes(const Uri &uri, int AmsStKitDataAbilityDataA2::OpenFile(const Uri &uri, const std::string &mode) { APP_LOGI("AmsStKitDataAbilityDataA2 <<<>>>"); - FILE *fd1 = fopen("/system/vendor/test.txt", "r"); + if (fd1 != nullptr) { + fclose(fd1); + fd1 = nullptr; + } + fd1 = fopen("/system/vendor/test.txt", "r"); if (fd1 == nullptr) return -1; int fd = fileno(fd1); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a3.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a3.cpp index 22e40532e8..cb3f96f471 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a3.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a3.cpp @@ -190,6 +190,10 @@ void AmsStKitDataAbilityDataA3::Init(const std::shared_ptr &ability AmsStKitDataAbilityDataA3::~AmsStKitDataAbilityDataA3() { + if (fd1 != nullptr) { + fclose(fd1); + fd1 = nullptr; + } CommonEventManager::UnSubscribeCommonEvent(subscriber_); } @@ -313,7 +317,11 @@ std::vector AmsStKitDataAbilityDataA3::GetFileTypes(const Uri &uri, int AmsStKitDataAbilityDataA3::OpenFile(const Uri &uri, const std::string &mode) { APP_LOGI("AmsStKitDataAbilityDataA3 <<<>>>"); - FILE *fd1 = fopen("/system/vendor/test.txt", "r"); + if (fd1 != nullptr) { + fclose(fd1); + fd1 = nullptr; + } + fd1 = fopen("/system/vendor/test.txt", "r"); if (fd1 == nullptr) return -1; int fd = fileno(fd1); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_page_a.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_page_a.cpp index ac8ee66443..f9f65930b9 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_page_a.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_page_a.cpp @@ -18,9 +18,9 @@ #include #include +#include "abs_shared_result_set.h" #include "app_log_wrapper.h" #include "data_ability_helper.h" -#include "abs_shared_result_set.h" #include "data_ability_predicates.h" #include "values_bucket.h" diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_data_b.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_data_b.h index 964081eaa8..8ce2ea8a70 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_data_b.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_data_b.h @@ -41,6 +41,7 @@ public: void SubscribeEvent(const Want &want); bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); STtools::Event event; + FILE *fd1 = nullptr; ~AmsStKitDataAbilityDataB(); protected: diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_data_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_data_b.cpp index a20e2ca2dc..af7ee1353c 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_data_b.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_data_b.cpp @@ -189,6 +189,10 @@ void AmsStKitDataAbilityDataB::Init(const std::shared_ptr &abilityI AmsStKitDataAbilityDataB::~AmsStKitDataAbilityDataB() { + if (fd1 != nullptr) { + fclose(fd1); + fd1 = nullptr; + } CommonEventManager::UnSubscribeCommonEvent(subscriber_); } @@ -310,7 +314,11 @@ std::vector AmsStKitDataAbilityDataB::GetFileTypes(const Uri &uri, int AmsStKitDataAbilityDataB::OpenFile(const Uri &uri, const std::string &mode) { APP_LOGI("AmsStKitDataAbilityDataB <<<>>>"); - FILE *fd1 = fopen("/system/vendor/test.txt", "r"); + if (fd1 != nullptr) { + fclose(fd1); + fd1 = nullptr; + } + fd1 = fopen("/system/vendor/test.txt", "r"); if (fd1 == nullptr) return -1; int fd = fileno(fd1); diff --git a/test/resource/formsystemtestability/fmsSystemPerformance/include/form_ability_performance.h b/test/resource/formsystemtestability/fmsSystemPerformance/include/form_ability_performance.h index 7202744de7..98267ecc81 100755 --- a/test/resource/formsystemtestability/fmsSystemPerformance/include/form_ability_performance.h +++ b/test/resource/formsystemtestability/fmsSystemPerformance/include/form_ability_performance.h @@ -59,7 +59,7 @@ public: std::string caseName_ = ""; int code_ = 0; - FormAbilityPerformance *ability_; + FormAbilityPerformance *ability_ = nullptr; }; protected: virtual void Init(const std::shared_ptr &abilityInfo, diff --git a/test/resource/formsystemtestability/fmsSystemStress/include/form_ability_stress.h b/test/resource/formsystemtestability/fmsSystemStress/include/form_ability_stress.h index 72ecbf2ce0..4cc9556ee3 100755 --- a/test/resource/formsystemtestability/fmsSystemStress/include/form_ability_stress.h +++ b/test/resource/formsystemtestability/fmsSystemStress/include/form_ability_stress.h @@ -81,7 +81,7 @@ public: std::string caseName_ = ""; int code_ = 0; - FormAbilityStress *ability_; + FormAbilityStress *ability_ = nullptr; }; protected: virtual void Init(const std::shared_ptr &abilityInfo, diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_a.h b/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_a.h index bb63b78c25..66a648f87c 100644 --- a/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_a.h +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_a.h @@ -79,7 +79,7 @@ public: std::string caseName_ = ""; int code_ = 0; - FormAbilityA *ability_; + FormAbilityA *ability_ = nullptr; }; protected: virtual void Init(const std::shared_ptr &abilityInfo, diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_deleteform.h b/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_deleteform.h index 9af88ac6a1..19f53a8434 100644 --- a/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_deleteform.h +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_deleteform.h @@ -63,7 +63,7 @@ public: void OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const override; void OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const override; void OnFormUninstall(const int64_t formId) const override; - FormAbilityDeleteForm *ability_; + FormAbilityDeleteForm *ability_ = nullptr; std::string caseName_; }; protected: diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_releaseform.h b/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_releaseform.h index a596482858..7bdbff428b 100644 --- a/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_releaseform.h +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormal/include/form_ability_releaseform.h @@ -53,7 +53,7 @@ public: void OnAcquired(const int32_t result, const FormJsInfo &formJsInfo) const override; void OnUpdate(const int32_t result, const FormJsInfo &formJsInfo) const override; void OnFormUninstall(const int64_t formId) const override; - FormAbilityReleaseForm *ability_; + FormAbilityReleaseForm *ability_ = nullptr; std::string caseName_; std::string lastformId_; }; diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormalB/include/form_ability_b.h b/test/resource/formsystemtestability/fmsSystemTestHostNormalB/include/form_ability_b.h index d5e5c7a636..5edd87f78d 100644 --- a/test/resource/formsystemtestability/fmsSystemTestHostNormalB/include/form_ability_b.h +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormalB/include/form_ability_b.h @@ -29,7 +29,7 @@ public: void handleEvent(std::string action, std::string data); void FMS_deleteFormCommon(std::string strFormId); - + void FMS_acquireForm_1400(std::string data); void FMS_acquireForm_1500(std::string data); void FMS_acquireForm_1800_2(std::string data); @@ -39,7 +39,7 @@ public: void FMS_acquireForm_tempForm(std::string data); void FMS_acquireFormBatch(std::string data); void FMS_acquireFormTempBatch(std::string data); - + std::shared_ptr subscriber_; class AcquireFormCallback : public FormCallback { @@ -54,7 +54,7 @@ public: std::string caseName_ = ""; int code_ = 0; - FormAbilityB *ability_; + FormAbilityB *ability_ = nullptr; }; protected: virtual void Init(const std::shared_ptr &abilityInfo, diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormalC/config.json b/test/resource/formsystemtestability/fmsSystemTestHostNormalC/config.json index c3bb05c974..d86af9a185 100644 --- a/test/resource/formsystemtestability/fmsSystemTestHostNormalC/config.json +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormalC/config.json @@ -47,7 +47,7 @@ } ] }], - "defPermissions": [ + "defPermissions": [ { "name": "ohos.permission.REQUIRE_FORM", "grantMode": "system_grant", diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNormalC/include/form_ability_c.h b/test/resource/formsystemtestability/fmsSystemTestHostNormalC/include/form_ability_c.h index 5b13e2e4c3..8fb20dcef4 100644 --- a/test/resource/formsystemtestability/fmsSystemTestHostNormalC/include/form_ability_c.h +++ b/test/resource/formsystemtestability/fmsSystemTestHostNormalC/include/form_ability_c.h @@ -29,7 +29,7 @@ public: void handleEvent(std::string action, std::string data); void FMS_deleteFormCommon(std::string strFormId); - + void FMS_acquireForm_3100(std::string data); void FMS_acquireForm_3200(std::string data); @@ -50,7 +50,7 @@ public: std::string caseName_ = ""; int code_ = 0; - FormAbilityC *ability_; + FormAbilityC *ability_ = nullptr; }; protected: virtual void Init(const std::shared_ptr &abilityInfo, diff --git a/test/resource/formsystemtestability/fmsSystemTestHostNotSys/config.json b/test/resource/formsystemtestability/fmsSystemTestHostNotSys/config.json index bf7d51772e..8adf4d53ac 100644 --- a/test/resource/formsystemtestability/fmsSystemTestHostNotSys/config.json +++ b/test/resource/formsystemtestability/fmsSystemTestHostNotSys/config.json @@ -47,7 +47,7 @@ } ] }], - "defPermissions": [ + "defPermissions": [ { "name": "ohos.permission.REQUIRE_FORM", "grantMode": "system_grant", diff --git a/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostA/config.json b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostA/config.json index 8a8d382473..9021cdb56c 100644 --- a/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostA/config.json +++ b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostA/config.json @@ -47,7 +47,7 @@ } ] }], - "defPermissions": [ + "defPermissions": [ { "name": "ohos.permission.REQUIRE_FORM", "grantMode": "system_grant", diff --git a/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostA/include/form_ability_self_starting_a.h b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostA/include/form_ability_self_starting_a.h index 78e8f9a3af..765a1dd9f1 100644 --- a/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostA/include/form_ability_self_starting_a.h +++ b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostA/include/form_ability_self_starting_a.h @@ -42,7 +42,7 @@ public: std::string caseName_ = ""; int code_ = 0; - FormAbilitySelfStartingA *ability_; + FormAbilitySelfStartingA *ability_ = nullptr; }; protected: virtual void Init(const std::shared_ptr &abilityInfo, diff --git a/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostB/config.json b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostB/config.json index 9306f37ea3..ce2020d1f1 100644 --- a/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostB/config.json +++ b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostB/config.json @@ -47,7 +47,7 @@ } ] }], - "defPermissions": [ + "defPermissions": [ { "name": "ohos.permission.REQUIRE_FORM", "grantMode": "system_grant", diff --git a/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostB/include/form_ability_self_starting_b.h b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostB/include/form_ability_self_starting_b.h index e56fe20afb..fc3775131f 100644 --- a/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostB/include/form_ability_self_starting_b.h +++ b/test/resource/formsystemtestability/fmsSystemTestSelfStarting/selfStartingTestHostB/include/form_ability_self_starting_b.h @@ -27,7 +27,7 @@ public: ~FormAbilitySelfStartingB(); void SubscribeEvent(); void handleEvent(std::string action, std::string data); - + void FMS_Start_0300_02(std::string data); void FMS_Start_0300_03(std::string data); @@ -43,7 +43,7 @@ public: std::string caseName_ = ""; int code_ = 0; - FormAbilitySelfStartingB *ability_; + FormAbilitySelfStartingB *ability_ = nullptr; }; protected: virtual void Init(const std::shared_ptr &abilityInfo, diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_A.cpp b/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_A.cpp index 393563683e..0f419e6d47 100755 --- a/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_A.cpp +++ b/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_A.cpp @@ -321,7 +321,7 @@ void FormStServiceAbilityA::OnUpdate(const int64_t formId) void FormStServiceAbilityA::OnTriggerEvent(const int64_t formId, const std::string &message) { APP_LOGI("%{public}s start", __func__); - + struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; diff --git a/test/resource/formsystemtestability/formSystemTestServiceB/src/form_st_service_ability_B.cpp b/test/resource/formsystemtestability/formSystemTestServiceB/src/form_st_service_ability_B.cpp index a59b6ad449..fc07a7a8d3 100644 --- a/test/resource/formsystemtestability/formSystemTestServiceB/src/form_st_service_ability_B.cpp +++ b/test/resource/formsystemtestability/formSystemTestServiceB/src/form_st_service_ability_B.cpp @@ -241,7 +241,7 @@ bool FormStServiceAbilityB::PublishEvent(const std::string &eventName, const int sptr FormStServiceAbilityB::OnConnect(const Want &want) { APP_LOGI("FormStServiceAbilityB::OnConnect"); - + sptr formProviderClient = new (std::nothrow) FormProviderClient(); std::shared_ptr thisAbility = this->shared_from_this(); formProviderClient->SetOwner(thisAbility); @@ -324,7 +324,7 @@ void FormStServiceAbilityB::OnUpdate(const int64_t formId) void FormStServiceAbilityB::OnTriggerEvent(const int64_t formId, const std::string &message) { APP_LOGI("%{public}s start", __func__); - + struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; diff --git a/test/resource/formsystemtestability/formSystemTestServiceD/src/form_st_service_ability_D.cpp b/test/resource/formsystemtestability/formSystemTestServiceD/src/form_st_service_ability_D.cpp index 564a083f8f..f4988dacef 100644 --- a/test/resource/formsystemtestability/formSystemTestServiceD/src/form_st_service_ability_D.cpp +++ b/test/resource/formsystemtestability/formSystemTestServiceD/src/form_st_service_ability_D.cpp @@ -241,7 +241,7 @@ bool FormStServiceAbilityD::PublishEvent(const std::string &eventName, const int sptr FormStServiceAbilityD::OnConnect(const Want &want) { APP_LOGI("FormStServiceAbilityD::OnConnect"); - + sptr formProviderClient = new (std::nothrow) FormProviderClient(); std::shared_ptr thisAbility = this->shared_from_this(); formProviderClient->SetOwner(thisAbility); @@ -320,7 +320,7 @@ void FormStServiceAbilityD::OnUpdate(const int64_t formId) void FormStServiceAbilityD::OnTriggerEvent(const int64_t formId, const std::string &message) { APP_LOGI("%{public}s start", __func__); - + struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; diff --git a/test/resource/formsystemtestability/formSystemTestServiceE/src/form_st_service_ability_E.cpp b/test/resource/formsystemtestability/formSystemTestServiceE/src/form_st_service_ability_E.cpp index 6dcbaeb598..bfcc357b11 100644 --- a/test/resource/formsystemtestability/formSystemTestServiceE/src/form_st_service_ability_E.cpp +++ b/test/resource/formsystemtestability/formSystemTestServiceE/src/form_st_service_ability_E.cpp @@ -241,7 +241,7 @@ bool FormStServiceAbilityE::PublishEvent(const std::string &eventName, const int sptr FormStServiceAbilityE::OnConnect(const Want &want) { APP_LOGI("FormStServiceAbilityE::OnConnect"); - + sptr formProviderClient = new (std::nothrow) FormProviderClient(); std::shared_ptr thisAbility = this->shared_from_this(); formProviderClient->SetOwner(thisAbility); @@ -320,7 +320,7 @@ void FormStServiceAbilityE::OnUpdate(const int64_t formId) void FormStServiceAbilityE::OnTriggerEvent(const int64_t formId, const std::string &message) { APP_LOGI("%{public}s start", __func__); - + struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; diff --git a/test/systemtest/BUILD.gn b/test/systemtest/BUILD.gn index 9865e4bf44..ff5888548d 100755 --- a/test/systemtest/BUILD.gn +++ b/test/systemtest/BUILD.gn @@ -28,4 +28,4 @@ group("systemtest") { "common/ems:systemtest_ems", "common/task_dispatcher:systemtest_task", ] -} +} \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_ability_append_test/ams_ability_append_test.cpp b/test/systemtest/common/ams/ams_ability_append_test/ams_ability_append_test.cpp index a9e75d6e55..f425ac2ed4 100644 --- a/test/systemtest/common/ams/ams_ability_append_test/ams_ability_append_test.cpp +++ b/test/systemtest/common/ams/ams_ability_append_test/ams_ability_append_test.cpp @@ -13,8 +13,8 @@ * limitations under the License. */ #include -#include #include +#include #include #include #include @@ -232,7 +232,7 @@ HWTEST_F(AmsAbilityAppendTest, AMS_Ability_Append_00200, Function | MediumTest | GTEST_LOG_(INFO) << eCode; EXPECT_EQ(TestWaitCompleted(event, "onStart", MAIN_ABILITY_B_CODE, START_DELAY), 0); EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_B_CODE, START_DELAY), 0); - + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_A_CODE, START_DELAY), 0); STAbilityUtil::PublishEvent( g_EVENT_REQU_FIRST, CODE_, "Ability_" + std::to_string((int)AppendApi::TerminateAndRemoveMisson) + "_0"); diff --git a/test/systemtest/common/ams/ams_app_process_manage_test/BUILD.gn b/test/systemtest/common/ams/ams_app_process_manage_test/BUILD.gn index 8220c1d887..7bdb3b15ab 100755 --- a/test/systemtest/common/ams/ams_app_process_manage_test/BUILD.gn +++ b/test/systemtest/common/ams/ams_app_process_manage_test/BUILD.gn @@ -58,6 +58,8 @@ ohos_systemtest("ams_app_process_manage_test") { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] + resource_config_file = + "//foundation/appexecfwk/standard/test/resource/mstbundlemgrservice/ohos_test.xml" } group("systemtest") { diff --git a/test/systemtest/common/ams/ams_data_ability_test/ams_data_ability_test.cpp b/test/systemtest/common/ams/ams_data_ability_test/ams_data_ability_test.cpp index becf6b9f58..ca601b40de 100644 --- a/test/systemtest/common/ams/ams_data_ability_test/ams_data_ability_test.cpp +++ b/test/systemtest/common/ams/ams_data_ability_test/ams_data_ability_test.cpp @@ -13,8 +13,8 @@ * limitations under the License. */ #include -#include #include +#include #include #include #include diff --git a/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_data_test.cpp b/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_data_test.cpp index aaacd595f1..c42f21215b 100644 --- a/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_data_test.cpp +++ b/test/systemtest/common/ams/ams_kit_test/acts_ams_kit_data_test.cpp @@ -13,8 +13,8 @@ * limitations under the License. */ #include -#include #include +#include #include #include #include diff --git a/test/systemtest/common/ams/ams_service_ability_test/ams_service_ability_test.cpp b/test/systemtest/common/ams/ams_service_ability_test/ams_service_ability_test.cpp index 9c395954ea..d6c6acfe71 100644 --- a/test/systemtest/common/ams/ams_service_ability_test/ams_service_ability_test.cpp +++ b/test/systemtest/common/ams/ams_service_ability_test/ams_service_ability_test.cpp @@ -21,8 +21,8 @@ #include "ability_connect_callback_proxy.h" #include "ability_connect_callback_stub.h" #include "ability_lifecycle_executor.h" -#include "ability_manager_service.h" #include "ability_manager_errors.h" +#include "ability_manager_service.h" #include "ams_service_ability_test_def.h" #include "app_mgr_service.h" #include "common_event.h" @@ -1147,10 +1147,10 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest16001() const EXPECT_EQ(ERR_OK, eCode); // start page ability2 EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_ACTIVE, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + event, PAGE_STATE_ON_ACTIVE, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), 0); usleep(WAIT_TIME); // ability "B2" state ACTIVE @@ -1159,10 +1159,10 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest16001() const STAbilityUtil::PublishEvent(REQ_EVENT_NAME_APP_B2, AbilityState_Test::USER_DEFINE, OPERATION_START_OTHER_ABILITY); // page ability2 start service ability3 EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), 0); usleep(WAIT_TIME); } @@ -1185,17 +1185,17 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest16002() const // service ability B3 start service ability A1 STAbilityUtil::PublishEvent(REQ_EVENT_NAME_APP_B3, AbilityState_Test::USER_DEFINE, OPERATION_START_OTHER_ABILITY); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), 0); usleep(WAIT_TIME); // service ability A1 connect service ability B3 STAbilityUtil::PublishEvent(REQ_EVENT_NAME_APP_A1, AbilityState_Test::USER_DEFINE, OPERATION_CONNECT_OTHER_ABILITY); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), 0); usleep(WAIT_TIME); @@ -1207,7 +1207,7 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest16002() const STAbilityUtil::PublishEvent( REQ_EVENT_NAME_APP_A1, AbilityState_Test::USER_DEFINE, OPERATION_DISCONNECT_OTHER_ABILITY); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_DISCONNECT, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + event, SERVICE_STATE_ON_DISCONNECT, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), 0); usleep(WAIT_TIME); @@ -1215,10 +1215,10 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest16002() const bool ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_B3, 0, "StopSelfAbility"); EXPECT_TRUE(ret); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), 0); usleep(WAIT_TIME); @@ -1226,10 +1226,10 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest16002() const ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_A1, 0, "StopSelfAbility"); EXPECT_TRUE(ret); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), 0); usleep(WAIT_TIME); @@ -1237,13 +1237,13 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest16002() const ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_B2, 0, "StopSelfAbility"); EXPECT_TRUE(ret); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_INACTIVE, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + event, PAGE_STATE_ON_INACTIVE, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), 0); usleep(WAIT_TIME); } @@ -1281,10 +1281,10 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest17001() const EXPECT_EQ(ERR_OK, eCode); // start page ability2 EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_ACTIVE, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + event, PAGE_STATE_ON_ACTIVE, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), 0); usleep(WAIT_TIME); // ability "B2" state ACTIVE @@ -1293,10 +1293,10 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest17001() const // start service ability3 STAbilityUtil::PublishEvent(REQ_EVENT_NAME_APP_B2, AbilityState_Test::USER_DEFINE, OPERATION_START_OTHER_ABILITY); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), 0); usleep(WAIT_TIME); } @@ -1305,19 +1305,19 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest17002() const { // start service ability4 EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), 0); usleep(WAIT_TIME); // start service ability1 EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), 0); usleep(WAIT_TIME); @@ -1325,10 +1325,10 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest17002() const bool ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_B3, 0, "StopSelfAbility"); EXPECT_TRUE(ret); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), 0); usleep(WAIT_TIME); @@ -1336,10 +1336,10 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest17002() const ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_A1, 0, "StopSelfAbility"); EXPECT_TRUE(ret); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), 0); usleep(WAIT_TIME); @@ -1347,10 +1347,10 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest17002() const ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_C4, 0, "StopSelfAbility"); EXPECT_TRUE(ret); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), 0); usleep(WAIT_TIME); @@ -1358,13 +1358,13 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest17002() const ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_B2, 0, "StopSelfAbility"); EXPECT_TRUE(ret); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ONINACTIVE, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + event, SERVICE_STATE_ONINACTIVE, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + event, SERVICE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + event, SERVICE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), 0); usleep(WAIT_TIME); } @@ -1402,10 +1402,10 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest18001() const EXPECT_EQ(ERR_OK, eCode); // start page ability2 EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_ACTIVE, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + event, PAGE_STATE_ON_ACTIVE, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), 0); usleep(WAIT_TIME); // ability "B2" state ACTIVE @@ -1414,19 +1414,19 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest18001() const STAbilityUtil::PublishEvent(REQ_EVENT_NAME_APP_B2, AbilityState_Test::USER_DEFINE, OPERATION_CONNECT_OTHER_ABILITY); // connect service ability3 EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), 0); usleep(WAIT_TIME); // connect service ability4 EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), 0); usleep(WAIT_TIME); } @@ -1435,10 +1435,10 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest18002() const { // connect service ability1 EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), 0); usleep(WAIT_TIME); @@ -1446,24 +1446,24 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest18002() const bool ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_B2, 0, "DisConnectOtherAbility"); EXPECT_TRUE(ret); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), 0); usleep(WAIT_TIME); @@ -1471,13 +1471,13 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest18002() const ret = STAbilityUtil::StopAbility(REQ_EVENT_NAME_APP_B2, 0, "StopSelfAbility"); EXPECT_TRUE(ret); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_INACTIVE, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + event, PAGE_STATE_ON_INACTIVE, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + event, PAGE_STATE_ON_BACKGROUND, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), + event, PAGE_STATE_ON_STOP, AbilityLifecycleExecutor::LifecycleState::INITIAL, DELAY_TIME), 0); usleep(WAIT_TIME); } @@ -1844,20 +1844,20 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest23001() const ErrCode eCode = STAbilityUtil::StartAbility(want1, abilityMs); EXPECT_EQ(ERR_OK, eCode); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), 0); usleep(WAIT_TIME); // service ability A1 connect service ability B3 STAbilityUtil::PublishEvent(REQ_EVENT_NAME_APP_A1, AbilityState_Test::USER_DEFINE, OPERATION_CONNECT_OTHER_ABILITY); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_CONNECT, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), 0); usleep(WAIT_TIME); @@ -1873,10 +1873,10 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest23001() const eCode = STAbilityUtil::StartAbility(want2, abilityMs); EXPECT_EQ(ERR_OK, eCode); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_ACTIVE, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + event, PAGE_STATE_ON_ACTIVE, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), 0); usleep(WAIT_TIME); // ability "B2" state ACTIVE @@ -1908,10 +1908,10 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest23002() const ErrCode eCode = STAbilityUtil::StartAbility(want3, abilityMs); EXPECT_EQ(ERR_OK, eCode); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), + event, PAGE_STATE_ON_START, AbilityLifecycleExecutor::LifecycleState::INACTIVE, DELAY_TIME), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), + event, SERVICE_STATE_ON_COMMAND, AbilityLifecycleExecutor::LifecycleState::ACTIVE, DELAY_TIME), 0); usleep(WAIT_TIME); @@ -1940,7 +1940,7 @@ void AmsServiceAbilityTest::AmsServiceAbilityTest23002() const STAbilityUtil::PublishEvent( REQ_EVENT_NAME_APP_E2, AbilityState_Test::USER_DEFINE, OPERATION_DISCONNECT_OTHER_ABILITY); EXPECT_EQ(STAbilityUtil::WaitCompleted( - event, SERVICE_STATE_ON_DISCONNECT, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), + event, SERVICE_STATE_ON_DISCONNECT, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, DELAY_TIME), 0); usleep(WAIT_TIME); // check B3 connect number diff --git a/test/systemtest/common/ams/ams_service_ability_test/ams_service_ability_test_def.h b/test/systemtest/common/ams/ams_service_ability_test/ams_service_ability_test_def.h index 91a323c7aa..52b91eb286 100644 --- a/test/systemtest/common/ams/ams_service_ability_test/ams_service_ability_test_def.h +++ b/test/systemtest/common/ams/ams_service_ability_test/ams_service_ability_test_def.h @@ -15,8 +15,8 @@ #ifndef AMS_SERVICE_ABILITY_TEST_DEF_H_ #define AMS_SERVICE_ABILITY_TEST_DEF_H_ -#include #include +#include namespace OHOS { namespace AppExecFwk { diff --git a/test/systemtest/common/ams/tool/include/st_ability_util.h b/test/systemtest/common/ams/tool/include/st_ability_util.h index fbf90caaee..f76e49f317 100644 --- a/test/systemtest/common/ams/tool/include/st_ability_util.h +++ b/test/systemtest/common/ams/tool/include/st_ability_util.h @@ -337,7 +337,8 @@ public: virtual ~InstallToolStatusReceiver() override; virtual void OnStatusNotify(const int progress) override; virtual void OnFinished(const int32_t resultCode, const std::string &resultMsg) override; - static int TestWaitCompleted(STtools::Event &event, const std::string eventName, const int code, const int timeout = 10); + static int TestWaitCompleted(STtools::Event &event, const std::string eventName, const int code, + const int timeout = 10); static void TestCompleted(STtools::Event &event, const std::string &eventName, const int code); STtools::Event event_ = STtools::Event(); diff --git a/test/systemtest/common/ems/BUILD.gn b/test/systemtest/common/ems/BUILD.gn index a93450a75c..39bc0392dd 100755 --- a/test/systemtest/common/ems/BUILD.gn +++ b/test/systemtest/common/ems/BUILD.gn @@ -25,4 +25,4 @@ group("systemtest_ems") { "ems_inner_event_system_test:systemtest", "ems_logger_system_test:systemtest", ] -} +} \ No newline at end of file diff --git a/test/systemtest/common/ems/ems_dumper_system_test/BUILD.gn b/test/systemtest/common/ems/ems_dumper_system_test/BUILD.gn index 68ed667eb9..c71d4cab92 100755 --- a/test/systemtest/common/ems/ems_dumper_system_test/BUILD.gn +++ b/test/systemtest/common/ems/ems_dumper_system_test/BUILD.gn @@ -40,4 +40,4 @@ group("systemtest") { testonly = true deps = [ ":EmsDumperSystemTest" ] -} +} \ No newline at end of file diff --git a/test/systemtest/common/ems/ems_event_handler_system_test/BUILD.gn b/test/systemtest/common/ems/ems_event_handler_system_test/BUILD.gn index 3cfaad8535..4760ace7da 100755 --- a/test/systemtest/common/ems/ems_event_handler_system_test/BUILD.gn +++ b/test/systemtest/common/ems/ems_event_handler_system_test/BUILD.gn @@ -42,4 +42,4 @@ group("systemtest") { testonly = true deps = [ ":EmsEventHandlerSystemTest" ] -} +} \ No newline at end of file diff --git a/test/systemtest/common/ems/ems_event_queue_system_test/BUILD.gn b/test/systemtest/common/ems/ems_event_queue_system_test/BUILD.gn index e647f4b2d6..755713a4cd 100644 --- a/test/systemtest/common/ems/ems_event_queue_system_test/BUILD.gn +++ b/test/systemtest/common/ems/ems_event_queue_system_test/BUILD.gn @@ -40,4 +40,4 @@ group("systemtest") { testonly = true deps = [ ":EmsEventQueueSystemTest" ] -} +} \ No newline at end of file diff --git a/test/systemtest/common/ems/ems_event_runner_system_test/BUILD.gn b/test/systemtest/common/ems/ems_event_runner_system_test/BUILD.gn index f408548611..c2310bab8e 100755 --- a/test/systemtest/common/ems/ems_event_runner_system_test/BUILD.gn +++ b/test/systemtest/common/ems/ems_event_runner_system_test/BUILD.gn @@ -40,4 +40,4 @@ group("systemtest") { testonly = true deps = [ ":EmsEventRunnerSystemTest" ] -} +} \ No newline at end of file diff --git a/test/systemtest/common/ems/ems_inner_event_system_test/BUILD.gn b/test/systemtest/common/ems/ems_inner_event_system_test/BUILD.gn index 18a0d238ed..4acf095136 100644 --- a/test/systemtest/common/ems/ems_inner_event_system_test/BUILD.gn +++ b/test/systemtest/common/ems/ems_inner_event_system_test/BUILD.gn @@ -40,4 +40,4 @@ group("systemtest") { testonly = true deps = [ ":EmsInnerEventSystemTest" ] -} +} \ No newline at end of file diff --git a/test/systemtest/common/ems/ems_logger_system_test/BUILD.gn b/test/systemtest/common/ems/ems_logger_system_test/BUILD.gn index 1ec08c8d3b..b950bfbf01 100755 --- a/test/systemtest/common/ems/ems_logger_system_test/BUILD.gn +++ b/test/systemtest/common/ems/ems_logger_system_test/BUILD.gn @@ -40,4 +40,4 @@ group("systemtest") { testonly = true deps = [ ":EmsLoggerSystemTest" ] -} +} \ No newline at end of file diff --git a/test/systemtest/common/fms/common/src/system_test_form_util.cpp b/test/systemtest/common/fms/common/src/system_test_form_util.cpp index 4176c7a728..4354c620cc 100755 --- a/test/systemtest/common/fms/common/src/system_test_form_util.cpp +++ b/test/systemtest/common/fms/common/src/system_test_form_util.cpp @@ -678,7 +678,7 @@ sptr SystemTestFormUtil::GetFmsService() return nullptr; } sptr remoteObject = systemManager->GetSystemAbility(FORM_MGR_SERVICE_ID); - + std::cout << "SendTransactCmd end." << std::endl; return remoteObject; } diff --git a/test/systemtest/common/fms/fms_acquire_form_test/fms_acquire_form_test.cpp b/test/systemtest/common/fms/fms_acquire_form_test/fms_acquire_form_test.cpp index a623fd2547..e0617fbfdd 100644 --- a/test/systemtest/common/fms/fms_acquire_form_test/fms_acquire_form_test.cpp +++ b/test/systemtest/common/fms/fms_acquire_form_test/fms_acquire_form_test.cpp @@ -67,7 +67,7 @@ public: void StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName); void TerminateAbility(const std::string &eventName, const std::string &abilityName); - + class FormEventSubscriber : public CommonEventSubscriber { public: explicit FormEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; @@ -290,7 +290,7 @@ HWTEST_F(FmsAcquireFormTest, FMS_acquireForm_1500, Function | MediumTest | Level sleep(1); FmsAcquireFormCatched1500(strFormId); - + sleep(1); FmsAcquireFormDeleteA(strFormId); std::cout << "END FMS_acquireForm_1500" << std::endl; @@ -837,7 +837,7 @@ void FmsAcquireFormTest::FmsAcquireFormCatched1500(std::string strFormId) } else { GTEST_LOG_(INFO) << "FMS_acquireForm_1500, formId:" << strFormId2; } - + GTEST_LOG_(INFO) << "FMS_acquireForm_1500, add catched form end"; // wait delete form EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_DELETE_FORM_COMMON, EVENT_CODE_999)); diff --git a/test/systemtest/common/fms/fms_acquire_form_test_max/fms_acquire_form_test_batch.cpp b/test/systemtest/common/fms/fms_acquire_form_test_max/fms_acquire_form_test_batch.cpp index 0e8a711b45..197ced8c13 100644 --- a/test/systemtest/common/fms/fms_acquire_form_test_max/fms_acquire_form_test_batch.cpp +++ b/test/systemtest/common/fms/fms_acquire_form_test_max/fms_acquire_form_test_batch.cpp @@ -76,7 +76,7 @@ public: void StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName); void TerminateAbility(const std::string &eventName, const std::string &abilityName); - + class FormEventSubscriber : public CommonEventSubscriber { public: explicit FormEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; @@ -182,7 +182,7 @@ HWTEST_F(FmsAcquireFormTestBatch, FMS_acquireForm_2900, Function | MediumTest | FMS_acquireFormBatchB(bundleName, abilityName, countB); int count = Constants::MAX_RECORD_PER_APP - 1; std::cout << "FMS_acquireForm_2900, form size of the host A:" << count << std::endl; - + sleep(1); std::string strFormId = FmsAcquireForm2900A(); normalFormsMaxA.emplace_back(strFormId); @@ -641,7 +641,7 @@ void FmsAcquireFormTestBatch::FMS_acquireFormBatchB(const std::string &bundleNam } else { GTEST_LOG_(INFO) << "FMS_acquireFormBatchB, result:" << result; } - + std::cout << "END FMS_acquireFormBatchB" << std::endl; } void FmsAcquireFormTestBatch::FMS_acquireTempFormBatch(const std::string &bundleName, const std::string &abilityName, @@ -667,7 +667,7 @@ void FmsAcquireFormTestBatch::FMS_acquireTempFormBatch(const std::string &bundle } else { GTEST_LOG_(INFO) << "FMS_acquireTempFormBatch, result:" << result; } - + std::cout << "END FMS_acquireTempFormBatch" << std::endl; } diff --git a/test/systemtest/common/fms/fms_acquire_form_test_max/fms_acquire_form_test_max.cpp b/test/systemtest/common/fms/fms_acquire_form_test_max/fms_acquire_form_test_max.cpp index 340d8d8c9c..a37652d27e 100644 --- a/test/systemtest/common/fms/fms_acquire_form_test_max/fms_acquire_form_test_max.cpp +++ b/test/systemtest/common/fms/fms_acquire_form_test_max/fms_acquire_form_test_max.cpp @@ -75,7 +75,7 @@ public: void StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName); void TerminateAbility(const std::string &eventName, const std::string &abilityName); - + class FormEventSubscriber : public CommonEventSubscriber { public: explicit FormEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; @@ -174,7 +174,7 @@ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_2900, Function | MediumTest | Le normalFormsMaxA.emplace_back(strFormId2); std::cout << "FMS_acquireForm_2900, form size of the host A:" << normalFormsMaxA.size() << std::endl; } - + std::cout << "END FMS_acquireForm_2900" << std::endl; } /** @@ -256,7 +256,7 @@ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_3100, Function | MediumTest | Le std::cout << "add form count:" << count + 1 << std::endl; } std::cout << "END add form to the host B" << std::endl; - + std::cout << "START add form to the host C" << std::endl; std::string bundleNameC = "com.ohos.form.manager.normalc"; std::string abilityNameC = "FormAbilityC"; @@ -429,7 +429,7 @@ HWTEST_F(FmsAcquireFormTestMax, FMS_acquireForm_3500, Function | MediumTest | Le std::string abilityNameB = "FormAbilityB"; std::cout << "bundleName: " << bundleNameB << std::endl; std::cout << "abilityName: " << abilityNameB << std::endl; - + bool result = FmsAcquireFormTempForFailed(bundleNameB, abilityNameB); EXPECT_TRUE(result); if (result) { diff --git a/test/systemtest/common/fms/fms_delete_form_test/fms_delete_form_test.cpp b/test/systemtest/common/fms/fms_delete_form_test/fms_delete_form_test.cpp index 4aae43bb0d..045002daac 100644 --- a/test/systemtest/common/fms/fms_delete_form_test/fms_delete_form_test.cpp +++ b/test/systemtest/common/fms/fms_delete_form_test/fms_delete_form_test.cpp @@ -52,7 +52,7 @@ public: void StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName); void TerminateAbility(const std::string &eventName, const std::string &abilityName); - + class FormEventSubscriber : public CommonEventSubscriber { public: explicit FormEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; @@ -356,7 +356,7 @@ HWTEST_F(FmsDeleteFormTest, FMS_deleteForm_0500, Function | MediumTest | Level1) SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM, EVENT_CODE_100, eventData); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100)); std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100); - + GTEST_LOG_(INFO) << "FMS_deleteForm_0500, data:[" << data << "]" << std::endl; bool result1 = data != ""; EXPECT_TRUE(result1); @@ -642,7 +642,7 @@ HWTEST_F(FmsDeleteFormTest, FMS_deleteForm_1100, Function | MediumTest | Level1) SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM, EVENT_CODE_100, eventData); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100)); std::string formOne = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100); - + GTEST_LOG_(INFO) << "FMS_deleteForm_1100, formOne:[" << formOne << "]" << std::endl; if (formOne != "") { std::string bundleName2 = "com.ohos.form.manager.normal"; diff --git a/test/systemtest/common/fms/fms_fuzz_test/fms_fuzz_test_config/config.json b/test/systemtest/common/fms/fms_fuzz_test/fms_fuzz_test_config/config.json index cddf5115eb..cd8c99c96d 100755 --- a/test/systemtest/common/fms/fms_fuzz_test/fms_fuzz_test_config/config.json +++ b/test/systemtest/common/fms/fms_fuzz_test/fms_fuzz_test_config/config.json @@ -1,29 +1,29 @@ { - "ExecutionTimes": 10, - "FormManagerAbility": { - "ReleaseForm": [], - "DeleteForm": [], - "AcquireForm": [], - "UpdateForm": [], - "CastTempForm": [], - "NotifyVisibleForms": [], - "NotifyInvisibleForms": [], - "SetFormNextRefreshTime": [], - "RequestForm":[], - "EnableUpdateForm": [], - "DisableUpdateForm": [], - "CheckFMSReady": [], - "GetAllFormsInfo":[], - "GetFormsInfoByApp": [], - "GetFormsInfoByModule": [], - "ProcessFormUpdate": [], - "ProcessFormUninstall": [], - "OnDeathReceived":[], - "OnCreate": [], - "OnDelete": [], - "OnCastTemptoNormal":[], - "OnUpdate": [], - "OnVisibilityChanged": [], - "OnTriggerEvent": [] - } + "ExecutionTimes": 10, + "FormManagerAbility": { + "ReleaseForm": [], + "DeleteForm": [], + "AcquireForm": [], + "UpdateForm": [], + "CastTempForm": [], + "NotifyVisibleForms": [], + "NotifyInvisibleForms": [], + "SetFormNextRefreshTime": [], + "RequestForm":[], + "EnableUpdateForm": [], + "DisableUpdateForm": [], + "CheckFMSReady": [], + "GetAllFormsInfo":[], + "GetFormsInfoByApp": [], + "GetFormsInfoByModule": [], + "ProcessFormUpdate": [], + "ProcessFormUninstall": [], + "OnDeathReceived":[], + "OnCreate": [], + "OnDelete": [], + "OnCastTemptoNormal":[], + "OnUpdate": [], + "OnVisibilityChanged": [], + "OnTriggerEvent": [] + } } diff --git a/test/systemtest/common/fms/fms_release_form_test/fms_release_form_test.cpp b/test/systemtest/common/fms/fms_release_form_test/fms_release_form_test.cpp index 57b6502c06..f12f44272e 100644 --- a/test/systemtest/common/fms/fms_release_form_test/fms_release_form_test.cpp +++ b/test/systemtest/common/fms/fms_release_form_test/fms_release_form_test.cpp @@ -52,7 +52,7 @@ public: void StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName); void TerminateAbility(const std::string &eventName, const std::string &abilityName); - + class FormEventSubscriber : public CommonEventSubscriber { public: explicit FormEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; @@ -296,7 +296,7 @@ HWTEST_F(FmsReleaseFormTest, FMS_releaseForm_0500, Function | MediumTest | Level SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM, EVENT_CODE_100, eventData); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100)); std::string data = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100); - + GTEST_LOG_(INFO) << "FMS_releaseForm_0500, data:[" << data << "]" << std::endl; if (data != "") { std::string bundleName2 = "com.ohos.form.manager.normal"; @@ -571,7 +571,7 @@ HWTEST_F(FmsReleaseFormTest, FMS_releaseForm_1100, Function | MediumTest | Level HWTEST_F(FmsReleaseFormTest, FMS_releaseForm_1200, Function | MediumTest | Level1) { std::cout << "============START FMS_releaseForm_1200" << std::endl; - + std::string bundleName = "com.ohos.form.manager.normal"; std::string abilityName = "FormAbilityReleaseForm"; MAP_STR_STR params; @@ -610,7 +610,7 @@ HWTEST_F(FmsReleaseFormTest, FMS_releaseForm_1200, Function | MediumTest | Level HWTEST_F(FmsReleaseFormTest, FMS_releaseForm_1300, Function | MediumTest | Level2) { std::cout << "============START FMS_releaseForm_1300" << std::endl; - + std::string bundleName = "com.ohos.form.manager.normal"; std::string abilityName = "FormAbilityReleaseForm"; MAP_STR_STR params; @@ -696,7 +696,7 @@ HWTEST_F(FmsReleaseFormTest, FMS_releaseForm_1000, Function | MediumTest | Level SystemTestFormUtil::PublishEvent(FORM_EVENT_REQ_ONE_NORMAL_FORM, EVENT_CODE_100, eventData); EXPECT_EQ(0, SystemTestFormUtil::WaitCompleted(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100)); std::string formOne = SystemTestFormUtil::GetData(event, FORM_EVENT_RECV_ONE_NORMAL_FORM, EVENT_CODE_100); - + GTEST_LOG_(INFO) << "FMS_releaseForm_1000, formOne:[" << formOne << "]" << std::endl; if (formOne != "") { std::string bundleName2 = "com.ohos.form.manager.normal"; diff --git a/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0100.sh b/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0100.sh index 99bec35cf8..f3b009ef7e 100644 --- a/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0100.sh +++ b/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0100.sh @@ -2,16 +2,14 @@ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - - ps -e|grep FormMgrService diff --git a/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0200.sh b/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0200.sh index be54ce070e..8330544487 100644 --- a/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0200.sh +++ b/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0200.sh @@ -2,16 +2,15 @@ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - - + sleepSeconds=10 loop=1 @@ -34,4 +33,4 @@ do fi done -exit +exit \ No newline at end of file diff --git a/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0300.sh b/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0300.sh index f77885dfca..2523335aa3 100644 --- a/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0300.sh +++ b/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0300.sh @@ -2,9 +2,9 @@ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0400.sh b/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0400.sh index 85e490bca3..205a4a4795 100644 --- a/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0400.sh +++ b/test/systemtest/common/fms/fms_self_starting_test/FMS_Start_0400.sh @@ -2,16 +2,15 @@ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - - + sleepSeconds=10 loop=4 @@ -34,4 +33,4 @@ do fi done -exit +exit \ No newline at end of file diff --git a/test/systemtest/common/fms/fms_self_starting_test/fms_self_starting_test.cpp b/test/systemtest/common/fms/fms_self_starting_test/fms_self_starting_test.cpp index 9fdbbdb5da..4c19a1b705 100644 --- a/test/systemtest/common/fms/fms_self_starting_test/fms_self_starting_test.cpp +++ b/test/systemtest/common/fms/fms_self_starting_test/fms_self_starting_test.cpp @@ -69,7 +69,7 @@ public: void ClearStorage(); bool CheckKvStore(); void TryTwice(const std::function &func); - + class FormEventSubscriber : public CommonEventSubscriber { public: explicit FormEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}; @@ -110,7 +110,7 @@ void FmsSelfStartingTest::SetUpTestCase() << "addFormStatus : " << selfStarting.addFormStatus << ", deleteFormStatus:" << selfStarting.deleteFormStatus << ", compareStatus:" << selfStarting.compareStatus << std::endl; - + if (selfStarting.addFormStatus) { selfStartingParser.ClearStorage(); for (int iCount = 0; iCount < ADD_FORM_A_NUMBER; iCount++) { @@ -286,7 +286,7 @@ HWTEST_F(FmsSelfStartingTest, FMS_Start_0300_03, Function | MediumTest | Level1) opbefore.close(); opafter.close(); EXPECT_TRUE(beforeKill != afterKill); - + EXPECT_TRUE(CompareA()); EXPECT_TRUE(CompareB()); diff --git a/test/systemtest/common/fms/fms_self_starting_test/self_starting_test_config_parser.h b/test/systemtest/common/fms/fms_self_starting_test/self_starting_test_config_parser.h index ea7898007a..b02ca7be21 100644 --- a/test/systemtest/common/fms/fms_self_starting_test/self_starting_test_config_parser.h +++ b/test/systemtest/common/fms/fms_self_starting_test/self_starting_test_config_parser.h @@ -58,7 +58,7 @@ public: jsonObj.at(STRESS_TEST_COMPARE_TIME_KEY).get_to(selfStarting.compareStatus); } } - + void ClearStorage() { { @@ -159,7 +159,7 @@ public: } bool ret = true; APP_LOGD("%{public}s called, formId[%{public}s]", __func__, formId.c_str()); - + DistributedKv::Status status = DistributedKv::Status::ERROR; std::vector allEntries; DistributedKv::Key key(formId); @@ -167,7 +167,7 @@ public: // sync call GetEntries, the callback will be trigger at once status = kvStorePtr_->GetEntries(key, allEntries); } - + if (status != DistributedKv::Status::SUCCESS) { APP_LOGE("get entries error: %{public}d", status); ret = false; diff --git a/test/systemtest/common/fms/fms_stress_test/BUILD.gn b/test/systemtest/common/fms/fms_stress_test/BUILD.gn index 43a4b1fd63..6b36d4286b 100755 --- a/test/systemtest/common/fms/fms_stress_test/BUILD.gn +++ b/test/systemtest/common/fms/fms_stress_test/BUILD.gn @@ -1,3 +1,4 @@ + # 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. @@ -71,4 +72,4 @@ group("systemtest") { testonly = true deps = [ ":FmsStressTest" ] -} +} \ No newline at end of file diff --git a/tools/fm/src/fms_command.cpp b/tools/fm/src/fms_command.cpp index 92c816e58d..739ac77c07 100755 --- a/tools/fm/src/fms_command.cpp +++ b/tools/fm/src/fms_command.cpp @@ -12,9 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include #include #include -#include #include "appexecfwk_errors.h" #include "app_log_wrapper.h" diff --git a/tools/test/BUILD.gn b/tools/test/BUILD.gn index 915053fc6d..b5f3f7a7fd 100644 --- a/tools/test/BUILD.gn +++ b/tools/test/BUILD.gn @@ -29,4 +29,4 @@ group("unittest") { testonly = true deps = [ "unittest/bm:unittest" ] -} +} \ No newline at end of file diff --git a/tools/test/mock/mock_bundle_mgr_host.h b/tools/test/mock/mock_bundle_mgr_host.h index 0893c733e4..f31e10f981 100644 --- a/tools/test/mock/mock_bundle_mgr_host.h +++ b/tools/test/mock/mock_bundle_mgr_host.h @@ -57,9 +57,10 @@ public: MOCK_METHOD1(HasSystemCapability, bool(const std::string &capName)); MOCK_METHOD1(GetSystemAvailableCapabilities, bool(std::vector &systemCaps)); MOCK_METHOD0(IsSafeMode, bool()); - MOCK_METHOD2(CleanBundleCacheFiles, - bool(const std::string &bundleName, const sptr &cleanCacheCallback)); - MOCK_METHOD2(CleanBundleDataFiles, bool(const std::string &bundleName, const int userId)); + + bool CleanBundleCacheFiles(const std::string &bundleName, const sptr &cleanCacheCallback); + bool CleanBundleDataFiles(const std::string &bundleName); + MOCK_METHOD1(RegisterBundleStatusCallback, bool(const sptr &bundleStatusCallback)); MOCK_METHOD1(ClearBundleStatusCallback, bool(const sptr &bundleStatusCallback)); MOCK_METHOD0(UnregisterBundleStatusCallback, bool()); @@ -67,7 +68,10 @@ public: bool DumpInfos(const DumpFlag flag, const std::string &bundleName, std::string &result); MOCK_METHOD1(IsApplicationEnabled, bool(const std::string &bundleName)); - MOCK_METHOD2(SetApplicationEnabled, bool(const std::string &bundleName, bool isEnable)); + + bool SetApplicationEnabled(const std::string &bundleName, bool isEnable); + bool SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnable); + MOCK_METHOD0(GetBundleInstaller, sptr()); MOCK_METHOD3(CanRequestPermission, bool(const std::string &bundleName, const std::string &permissionName, const int userId)); @@ -75,7 +79,6 @@ public: bool(const std::string &bundleName, const std::string &permission, const int userId)); MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); - MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); -- Gitee From 51176ce559cf5612e04684f02ec187977f28a901 Mon Sep 17 00:00:00 2001 From: jiangdayuan Date: Wed, 22 Dec 2021 16:02:49 +0800 Subject: [PATCH 2/6] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E7=BC=96=E8=AF=91?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: jiangdayuan Change-Id: I41439523c108019de6ae516cb463edbfa01bb2b3 --- kits/BUILD.gn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kits/BUILD.gn b/kits/BUILD.gn index bb315d455e..c7e6ef6e14 100755 --- a/kits/BUILD.gn +++ b/kits/BUILD.gn @@ -135,7 +135,7 @@ ohos_shared_library("appkit_native") { "$SUBSYSTEM_DIR/common:libappexecfwk_common", "$SUBSYSTEM_DIR/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "$SUBSYSTEM_DIR/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + # "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/interfaces/innerkits/want:want", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", -- Gitee From 223498235933cb3d4159551087e1eeded42c5427 Mon Sep 17 00:00:00 2001 From: jiangdayuan Date: Wed, 22 Dec 2021 16:29:48 +0800 Subject: [PATCH 3/6] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E7=BC=96=E8=AF=91?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: jiangdayuan Change-Id: I182280295652007b3abb54d737c6579e60b24441 --- kits/BUILD.gn | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/kits/BUILD.gn b/kits/BUILD.gn index c7e6ef6e14..e78c3aa5e8 100755 --- a/kits/BUILD.gn +++ b/kits/BUILD.gn @@ -135,7 +135,7 @@ ohos_shared_library("appkit_native") { "$SUBSYSTEM_DIR/common:libappexecfwk_common", "$SUBSYSTEM_DIR/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "$SUBSYSTEM_DIR/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - # "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/interfaces/innerkits/want:want", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", @@ -192,7 +192,7 @@ ohos_shared_library("app_context") { "$SUBSYSTEM_DIR/common:libappexecfwk_common", "$SUBSYSTEM_DIR/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "$SUBSYSTEM_DIR/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + # "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", -- Gitee From 3bcb67d4fdead5575c3deec67c35a6f4d36ea46a Mon Sep 17 00:00:00 2001 From: jiangdayuan Date: Thu, 23 Dec 2021 09:15:37 +0800 Subject: [PATCH 4/6] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E9=97=A8=E7=A6=81?= =?UTF-8?q?=E7=BC=96=E8=AF=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: I42796ff9d8102076f28146befff2770f284cea0e --- .../appexecfwk_base/src/form_info.cpp | 273 +++--------------- .../include/bundlemgr/bundle_mgr_interface.h | 2 +- .../include/bundlemgr/bundle_mgr_proxy.h | 2 +- .../src/appmgr/configuration.cpp | 2 +- services/appmgr/src/app_mgr_service.cpp | 4 +- .../test/mock/include/mock_bundle_manager.h | 2 +- .../bundlemgr/include/bundle_mgr_host_impl.h | 2 +- .../test/mock/include/mock_bundle_manager.h | 2 +- 8 files changed, 45 insertions(+), 244 deletions(-) mode change 100644 => 100755 interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h mode change 100644 => 100755 interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_proxy.h mode change 100644 => 100755 interfaces/innerkits/appexecfwk_core/src/appmgr/configuration.cpp mode change 100644 => 100755 services/appmgr/src/app_mgr_service.cpp mode change 100644 => 100755 services/appmgr/test/mock/include/mock_bundle_manager.h mode change 100644 => 100755 services/bundlemgr/include/bundle_mgr_host_impl.h mode change 100644 => 100755 services/formmgr/test/mock/include/mock_bundle_manager.h diff --git a/interfaces/innerkits/appexecfwk_base/src/form_info.cpp b/interfaces/innerkits/appexecfwk_base/src/form_info.cpp index b6aa9f6f6c..526d55f3b1 100644 --- a/interfaces/innerkits/appexecfwk_base/src/form_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/form_info.cpp @@ -15,16 +15,17 @@ #include "form_info.h" -#include #include -#include #include - -#include "bundle_constants.h" -#include "json_util.h" +#include +#include +#include "json_serializer.h" #include "nlohmann/json.hpp" -#include "parcel_macro.h" #include "string_ex.h" +#include "parcel_macro.h" +#include "app_log_wrapper.h" +#include "nlohmann/json.hpp" +#include "bundle_constants.h" namespace OHOS { namespace AppExecFwk { @@ -196,7 +197,7 @@ bool FormInfo::Marshalling(Parcel &parcel) const void to_json(nlohmann::json &jsonObject, const FormCustomizeData &customizeDatas) { - jsonObject = nlohmann::json { + jsonObject = nlohmann::json{ {JSON_KEY_NAME, customizeDatas.name}, {JSON_KEY_VALUE, customizeDatas.value} }; @@ -210,7 +211,7 @@ void to_json(nlohmann::json &jsonObject, const FormWindow &formWindow) void to_json(nlohmann::json &jsonObject, const FormInfo &formInfo) { - jsonObject = nlohmann::json { + jsonObject = nlohmann::json{ {JSON_KEY_NAME, formInfo.name}, {JSON_KEY_PACKAGE, formInfo.package}, {JSON_KEY_BUNDLE_NAME, formInfo.bundleName}, @@ -242,24 +243,8 @@ void to_json(nlohmann::json &jsonObject, const FormInfo &formInfo) void from_json(const nlohmann::json &jsonObject, FormCustomizeData &customizeDatas) { - const auto &jsonObjectEnd = jsonObject.end(); - int32_t parseResult = ERR_OK; - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_NAME, - customizeDatas.name, - JsonType::STRING, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_VALUE, - customizeDatas.value, - JsonType::STRING, - false, - parseResult, - ArrayType::NOT_ARRAY); + customizeDatas.name = jsonObject.at(JSON_KEY_NAME).get(); + customizeDatas.value = jsonObject.at(JSON_KEY_VALUE).get(); } void from_json(const nlohmann::json &jsonObject, FormWindow &formWindow) @@ -270,216 +255,32 @@ void from_json(const nlohmann::json &jsonObject, FormWindow &formWindow) void from_json(const nlohmann::json &jsonObject, FormInfo &formInfo) { - const auto &jsonObjectEnd = jsonObject.end(); - int32_t parseResult = ERR_OK; - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_BUNDLE_NAME, - formInfo.bundleName, - JsonType::STRING, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_PACKAGE, - formInfo.package, - JsonType::STRING, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_MODULE_NAME, - formInfo.moduleName, - JsonType::STRING, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_ABILITY_NAME, - formInfo.abilityName, - JsonType::STRING, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_NAME, - formInfo.name, - JsonType::STRING, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_DESCRIPTION, - formInfo.description, - JsonType::STRING, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_RELATED_BUNDLE_NAME, - formInfo.relatedBundleName, - JsonType::STRING, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_JS_COMPONENT_NAME, - formInfo.jsComponentName, - JsonType::STRING, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_DEEP_LINK, - formInfo.deepLink, - JsonType::STRING, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_FORMCONFIG_ABILITY, - formInfo.formConfigAbility, - JsonType::STRING, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_SCHEDULED_UPDATE_TIME, - formInfo.scheduledUpateTime, - JsonType::STRING, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_SRC, - formInfo.src, - JsonType::STRING, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_ORIGINAL_BUNDLE_NAME, - formInfo.originalBundleName, - JsonType::STRING, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_DESCRIPTION_ID, - formInfo.descriptionId, - JsonType::NUMBER, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_UPDATE_DURATION, - formInfo.updateDuration, - JsonType::NUMBER, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_DEFAULT_DIMENSION, - formInfo.defaultDimension, - JsonType::NUMBER, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_DEFAULT_FLAG, - formInfo.defaultFlag, - JsonType::BOOLEAN, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_FORM_VISIBLE_NOTIFY, - formInfo.formVisibleNotify, - JsonType::BOOLEAN, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_UPDATE_ENABLED, - formInfo.updateEnabled, - JsonType::BOOLEAN, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_TYPE, - formInfo.type, - JsonType::NUMBER, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_COLOR_MODE, - formInfo.colorMode, - JsonType::NUMBER, - false, - parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey>(jsonObject, - jsonObjectEnd, - JSON_KEY_SUPPORT_DIMENSIONS, - formInfo.supportDimensions, - JsonType::ARRAY, - false, - parseResult, - ArrayType::NUMBER); - GetValueIfFindKey>(jsonObject, - jsonObjectEnd, - JSON_KEY_CUSTOMIZE_DATA, - formInfo.customizeDatas, - JsonType::ARRAY, - false, - parseResult, - ArrayType::OBJECT); - GetValueIfFindKey>(jsonObject, - jsonObjectEnd, - JSON_KEY_LANDSCAPE_LAYOUTS, - formInfo.landscapeLayouts, - JsonType::ARRAY, - false, - parseResult, - ArrayType::STRING); - GetValueIfFindKey>(jsonObject, - jsonObjectEnd, - JSON_KEY_PORTRAIT_LAYOUTS, - formInfo.portraitLayouts, - JsonType::ARRAY, - false, - parseResult, - ArrayType::STRING); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - JSON_KEY_WINDOW, - formInfo.window, - JsonType::OBJECT, - false, - parseResult, - ArrayType::NOT_ARRAY); + formInfo.bundleName = jsonObject.at(JSON_KEY_BUNDLE_NAME).get(); + formInfo.package = jsonObject.at(JSON_KEY_PACKAGE).get(); + formInfo.moduleName = jsonObject.at(JSON_KEY_MODULE_NAME).get(); + formInfo.abilityName = jsonObject.at(JSON_KEY_ABILITY_NAME).get(); + formInfo.name = jsonObject.at(JSON_KEY_NAME).get(); + formInfo.description = jsonObject.at(JSON_KEY_DESCRIPTION).get(); + formInfo.relatedBundleName = jsonObject.at(JSON_KEY_RELATED_BUNDLE_NAME).get(); + formInfo.jsComponentName = jsonObject.at(JSON_KEY_JS_COMPONENT_NAME).get(); + formInfo.deepLink = jsonObject.at(JSON_KEY_DEEP_LINK).get(); + formInfo.formConfigAbility = jsonObject.at(JSON_KEY_FORMCONFIG_ABILITY).get(); + formInfo.scheduledUpateTime = jsonObject.at(JSON_KEY_SCHEDULED_UPDATE_TIME).get(); + formInfo.src = jsonObject.at(JSON_KEY_SRC).get(); + formInfo.originalBundleName = jsonObject.at(JSON_KEY_ORIGINAL_BUNDLE_NAME).get(); + formInfo.descriptionId = jsonObject.at(JSON_KEY_DESCRIPTION_ID).get(); + formInfo.updateDuration = jsonObject.at(JSON_KEY_UPDATE_DURATION).get(); + formInfo.defaultDimension = jsonObject.at(JSON_KEY_DEFAULT_DIMENSION).get(); + formInfo.defaultFlag = jsonObject.at(JSON_KEY_DEFAULT_FLAG).get(); + formInfo.formVisibleNotify = jsonObject.at(JSON_KEY_FORM_VISIBLE_NOTIFY).get(); + formInfo.updateEnabled = jsonObject.at(JSON_KEY_UPDATE_ENABLED).get(); + formInfo.type = jsonObject.at(JSON_KEY_TYPE).get(); + formInfo.colorMode = jsonObject.at(JSON_KEY_COLOR_MODE).get(); + formInfo.supportDimensions = jsonObject.at(JSON_KEY_SUPPORT_DIMENSIONS).get>(); + formInfo.customizeDatas = jsonObject.at(JSON_KEY_CUSTOMIZE_DATA).get>(); + formInfo.landscapeLayouts = jsonObject.at(JSON_KEY_LANDSCAPE_LAYOUTS).get>(); + formInfo.portraitLayouts = jsonObject.at(JSON_KEY_PORTRAIT_LAYOUTS).get>(); + formInfo.window = jsonObject.at(JSON_KEY_WINDOW).get(); } } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h b/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h old mode 100644 new mode 100755 index 5f8a23b409..a2ae51c5d1 --- a/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h +++ b/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h @@ -394,7 +394,7 @@ public: * @param userId Indicates the user id. * @return Returns true if the data cleared successfully; returns false otherwise. */ - virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId) = 0; + virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0) = 0; /** * @brief Register the specific bundle status callback. * @param bundleStatusCallback Indicates the callback to be invoked for returning the bundle status changed result. diff --git a/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_proxy.h b/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_proxy.h old mode 100644 new mode 100755 index f58b37ad99..5ae129a5de --- a/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_proxy.h +++ b/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_proxy.h @@ -359,7 +359,7 @@ public: * @param userId Indicates the user id. * @return Returns true if the data cleared successfully; returns false otherwise. */ - virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId) override; + virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0) override; /** * @brief Register the specific bundle status callback through the proxy object. * @param bundleStatusCallback Indicates the callback to be invoked for returning the bundle status changed result. diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/configuration.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/configuration.cpp old mode 100644 new mode 100755 index 1e80e4fa4c..9fca79f9af --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/configuration.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/configuration.cpp @@ -19,7 +19,7 @@ #include "app_log_wrapper.h" #include "string_ex.h" -namespace { +namespace ConfigurationInner { const std::string CONNECTION_SYMBOL {"#"}; const std::string EMPTY_STRING {""}; diff --git a/services/appmgr/src/app_mgr_service.cpp b/services/appmgr/src/app_mgr_service.cpp old mode 100644 new mode 100755 index faef254bf5..8a7669b9de --- a/services/appmgr/src/app_mgr_service.cpp +++ b/services/appmgr/src/app_mgr_service.cpp @@ -310,8 +310,8 @@ void AppMgrService::GetSystemMemoryAttr(SystemMemoryAttr &memoryInfo, std::strin int memThreshold = 0; nlohmann::json memJson = nlohmann::json::parse(strConfig, nullptr, false); if (memJson.is_discarded()) { - memThreshold = experienceMemThreshold; - APP_LOGE("%{public}s, discarded memThreshold = %{public}d", __func__, experienceMemThreshold); + memThreshold = EXPERIENCE_MEM_THRESHOLD; + APP_LOGE("%{public}s, discarded memThreshold = %{public}d", __func__, EXPERIENCE_MEM_THRESHOLD); } else { if (!memJson.contains("memoryThreshold")) { memThreshold = EXPERIENCE_MEM_THRESHOLD; diff --git a/services/appmgr/test/mock/include/mock_bundle_manager.h b/services/appmgr/test/mock/include/mock_bundle_manager.h old mode 100644 new mode 100755 index de865d26d9..d7f0d402bd --- a/services/appmgr/test/mock/include/mock_bundle_manager.h +++ b/services/appmgr/test/mock/include/mock_bundle_manager.h @@ -173,7 +173,7 @@ public: { return true; }; - virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId) override + virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0) override { return true; }; diff --git a/services/bundlemgr/include/bundle_mgr_host_impl.h b/services/bundlemgr/include/bundle_mgr_host_impl.h old mode 100644 new mode 100755 index 7d18e72e12..68c1916157 --- a/services/bundlemgr/include/bundle_mgr_host_impl.h +++ b/services/bundlemgr/include/bundle_mgr_host_impl.h @@ -337,7 +337,7 @@ public: * @param userId Indicates the user id. * @return Returns true if the data cleared successfully; returns false otherwise. */ - virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId) override; + virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0) override; /** * @brief Register the specific bundle status callback. * @param bundleStatusCallback Indicates the callback to be invoked for returning the bundle status changed result. diff --git a/services/formmgr/test/mock/include/mock_bundle_manager.h b/services/formmgr/test/mock/include/mock_bundle_manager.h old mode 100644 new mode 100755 index 7f82e1c095..6bc8061935 --- a/services/formmgr/test/mock/include/mock_bundle_manager.h +++ b/services/formmgr/test/mock/include/mock_bundle_manager.h @@ -160,7 +160,7 @@ public: { return true; } - virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId) override + virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0) override { return true; } -- Gitee From 4d87cc1de8c4b44e46906d308a70f27b0038cfbd Mon Sep 17 00:00:00 2001 From: jiangdayuan Date: Thu, 23 Dec 2021 22:03:14 +0800 Subject: [PATCH 5/6] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E7=BC=96=E8=AF=91?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: jiangdayuan Change-Id: Ib13d03716666ea3fb039f47114af2e02b3e14cae --- .../mock/include/mock_ability_manager_client_interface1.h | 2 +- services/appmgr/src/app_mgr_service_inner.cpp | 8 ++++---- tools/test/mock/mock_bundle_mgr_host.h | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h b/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h index eb6f925b40..23e691ac05 100644 --- a/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h +++ b/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h @@ -199,7 +199,7 @@ public: { return true; }; - virtual bool CleanBundleDataFiles(const std::string &bundleName) + virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0) { return true; }; diff --git a/services/appmgr/src/app_mgr_service_inner.cpp b/services/appmgr/src/app_mgr_service_inner.cpp index a4301bc1d8..c49092471f 100644 --- a/services/appmgr/src/app_mgr_service_inner.cpp +++ b/services/appmgr/src/app_mgr_service_inner.cpp @@ -383,23 +383,23 @@ void AppMgrServiceInner::ClearUpApplicationDataByUserId(const std::string &bundl return; } - int32_t clearUid = bundleMgr_->GetUidByBundleName(bundleName, 0); + int32_t clearUid = bundleMgr_->GetUidByBundleName(bundleName, userId); if (bundleMgr_->CheckIsSystemAppByUid(callerUid) || callerUid == clearUid) { // request to clear user information permission. int32_t result = - Permission::PermissionKit::RemoveUserGrantedReqPermissions(bundleName, Constants::DEFAULT_USERID); + Permission::PermissionKit::RemoveUserGrantedReqPermissions(bundleName, userId); if (result) { APP_LOGE("RemoveUserGrantedReqPermissions failed"); return; } // 2.delete bundle side user data - if (!bundleMgr_->CleanBundleDataFiles(bundleName)) { + if (!bundleMgr_->CleanBundleDataFiles(bundleName, userId)) { APP_LOGE("Delete bundle side user data is fail"); return; } // 3.kill application // 4.revoke user rights - result = KillApplication(bundleName); + result = KillApplicationByUserId(bundleName, userId); if (result < 0) { APP_LOGE("Kill Application by bundle name is fail"); return; diff --git a/tools/test/mock/mock_bundle_mgr_host.h b/tools/test/mock/mock_bundle_mgr_host.h index f31e10f981..6c48cf2f5b 100644 --- a/tools/test/mock/mock_bundle_mgr_host.h +++ b/tools/test/mock/mock_bundle_mgr_host.h @@ -59,7 +59,7 @@ public: MOCK_METHOD0(IsSafeMode, bool()); bool CleanBundleCacheFiles(const std::string &bundleName, const sptr &cleanCacheCallback); - bool CleanBundleDataFiles(const std::string &bundleName); + bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0); MOCK_METHOD1(RegisterBundleStatusCallback, bool(const sptr &bundleStatusCallback)); MOCK_METHOD1(ClearBundleStatusCallback, bool(const sptr &bundleStatusCallback)); -- Gitee From ff9cdaf88516a75b102452a05e73cdbf1c632895 Mon Sep 17 00:00:00 2001 From: wangtiantian Date: Fri, 24 Dec 2021 01:04:05 +0000 Subject: [PATCH 6/6] fix bug Signed-off-by: wangtiantian --- interfaces/innerkits/appexecfwk_base/src/ability_info.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp b/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp index a408051ead..52b76a2c77 100644 --- a/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp @@ -419,11 +419,11 @@ void from_json(const nlohmann::json &jsonObject, AbilityInfo &abilityInfo) false, parseResult, ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, + GetValueIfFindKey(jsonObject, jsonObjectEnd, JSON_KEY_BACKGROUND_MODES, abilityInfo.backgroundModes, - JsonType::BOOLEAN, + JsonType::NUMBER, false, parseResult, ArrayType::NOT_ARRAY); -- Gitee